0

I have been through quite some different codes on this site. To find what wrong with my code. Basically I just want to search in a table and test the result. I wrote something like this:

<?php

ob_start();
session_start();

$conn = new mysqli('localhost','username','password','mytable');

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");

if(mysql_num_rows($result) == 0) 
{ 
    echo "User not found";
}

$password = 'something2';
$userData = mysql_fetch_array($result, MYSQL_ASSOC);

if($password != $userData['Password']) 
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
            header('Location: welcome.php');
}
?>

And I get always the message :

"User not found." and "password not found." 

when I know the username and password are in the table...

No I'm quite knew with PHP/MySQL so there might be something quite big right in front of my face and I can't see it!!!!

Can somebody help please. Thanx.

Dharmesh Porwal
  • 1,406
  • 2
  • 12
  • 21
NorKayak
  • 41
  • 7

4 Answers4

1

Takes less than a second to spot. (If you had error reporting on it would take even less than that)

1) Your connection is mysqli but your query call is mysql

$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");

2) Value of $valuetotest is a string value and needs to be within quotes in your query. Should be like

SELECT id FROM members WHERE UserName = 'hellohi'  

And not like

SELECT id FROM members WHERE UserName = hellohi  

And Oh, How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • Yes even then you have to use `UserName='$valuetotest'`, but sorry i am not going to suggest something in my answer which can cause harm to your code later. Please move on the prepared statements and see the link i added to my answer. – Hanky Panky Jan 13 '15 at 08:17
0
<?php

$result = mysqli_query("SELECT `id`, `Password` FROM `members` WHERE `UserName` = '$valuetotest'");

if(mysqli_num_rows($result) == 0) 
{ 
    echo "User not found";
}

$password = 'something2';
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);

if($password != $userData['Password']) 
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
            header('Location: welcome.php');
}

?>
John V
  • 875
  • 6
  • 12
-1

You are selecting a text so you should use ' ' Symbols in your Select statement. Like this:

$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = '$valuetotest'");
Noxoreos
  • 23
  • 5
-2
$result = mysql_query("SELECT id FROM members WHERE UserName = '".$valuetotest."'");
Ali Mohammadi
  • 1,306
  • 1
  • 14
  • 28