user2683843 user2683843 - 4 months ago 8
SQL Question

PHP MYSQL Query returns 0 rows instead of 1

So my query returns 0 rows,username not found.But it finds it and highlights it.Should return 1 row how do i fix this
This image provides best explanation of my problem

LogMe.php -script that trys to login user,inside there is sql querry

<?php
$servername = "sql206.eu.ai";
$username = "euai_18493372";
$password = "123456";
$dbname = "euai_18493372_Users";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";



echo $_POST["username1"];
echo $_POST["password"];
$name=$_POST["username"];
$mypass=$_POST["password"];


$query = mysql_query("SELECT username FROM users WHERE username='$name.' ");
if (mysql_num_rows($query)>0)
{
echo "Username found";
}else{echo "No username foudn";}


$conn->close();

?>

Answer

Your issue is that MySQLi and MySQL are DIFFERENT - you are mixing the two connecton types, so instead stick with your MySQLi Object Orientated approach (with the -> arrows) as MySQL_ has been DEPRECATED.

Other Notes:

  • Passwords should be stored as hashed values rather than plain text, so you find the username and call the password hash from the DB and then hash the give user input in the same way. Typically using the password_verify PHP function.

  • Your SQL query here: if ($conn->query($sql) === TRUE) { echo "New record created successfully,registration succesfull"; SELECTs users and does not create them. Your wording is confusing.

  • mysql(i)_num_rows can occassionally give incorrect result counts due to table setup and types of data that are being output into the rows, so for a marginally more reliable method of getting the desired output use MySQL Count. (This doesn't seem to be the case in this instance but is worth baring in mind in general).

  • It is a very good idea to explore using Prepared Statements or at the very least to properly clean your user input ($_POSTs) values before they touch your database. This prevents SQL injection attacks which can compromise your data.

Solution

(From comments) : Check your username='$name.' syntax, you have a period (.) in your string. This looks like a syntax errror.