Something wrong about an sql statement in php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Spectrum_tr
Forum Newbie
Posts: 14
Joined: Sat Dec 10, 2005 11:22 am

Something wrong about an sql statement in php

Post by Spectrum_tr »

Hi. I can not understand what is wrong with this statement. I looked at once, twice and lots of times...

Code: Select all

<?php

session_start();

$link = mysql_connect('localhost', 'root')
   or die('Could not connect: ' . mysql_error());

mysql_select_db('cse343') or die('Could not select database');

$uname = $_POST['user_name'];
$pass = $_POST['password'];

$_SESSION['username'] = $uname;

$check = check_authentication ($username, $password);

if ( $check )
{
	echo "<a href=\"modify_e.php?id=$uname\">insert or update or delete EDUCATION table</a><br />";
	echo "<a href=\"modify_j.php?id=$uname\">insert or update or delete JOB table</a><br />";
	echo "<a href=\"cv.php?id=$uname\">view CV </a><br />";
}
else
{
	echo "The username and password is wrong";
}

function check_authentication($username,$password)
{
	$query = "Select sname from users where username = $uname AND passwd = $pass";

	$result = mysql_query($query);
	$row = mysql_num_rows($result);

	if ($row==1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

?>


The query:

$query = "Select sname from users where username = $uname AND passwd = $pass";

is wrong. But its not wrong due to the grammar of sql. Can anybody show me a way? Thanks for your helps...
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Code: Select all

$query = "SELECT `sname` FROM `users` WHERE `username` = '$uname' AND `passwd` = '$pass'";
and you can cut down on your authentication function like so:

Code: Select all

<?php

function check_authentication ($uname, $pass)
{
    $query = "SELECT `sname` FROM `users` WHERE `username` = '$uname' AND `passwd` = '$pass'";

    if (mysql_num_rows(mysql_query($query)) !== 0) {
        return true;
    } else {
        return false;
    }
}
?>
And also of high importance, read up about SQL injection.
Spectrum_tr
Forum Newbie
Posts: 14
Joined: Sat Dec 10, 2005 11:22 am

Post by Spectrum_tr »

ok. i got it. thanks for your help... :)
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

just had an after thought, change the criteria in the if to === 1 from !== 0.
Spectrum_tr
Forum Newbie
Posts: 14
Joined: Sat Dec 10, 2005 11:22 am

Post by Spectrum_tr »

yes you are right. ill change. see you thanks
Post Reply