Reputation: 137
I am trying to write a very simple query in php.
$conn = createConnection();
$sql = "select count(username) from passenger where username = '$passengerId' and password ='$password'";
$result = mysql_query($sql);
$count = mysql_result($result, 0);
echo $count;
if ($count == 1)
echo "true == 1";
else
echo "false != 1";
echo print_r(mysql_result($result, 0));
echo $count;
at the end, echo print_r(mysql_result($result, 0))
gives me 1 as expected, but echo $count
does not print anything. Also the if statement give me false != 1
. I am not sure what kind of problem occurs here.
Upvotes: 0
Views: 140
Reputation: 7474
Try this:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count(username) as totalUser from passenger where username = '$passengerId' and password ='$password'";
$result=mysqli_query($con,$sql);
// Associative array
$row=mysqli_fetch_assoc($result);
printf ("%s",$row["totalUser"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
See, if that solves your problem.
Upvotes: 1
Reputation: 1804
print_r will always return 1 when TRUE.
For example
print_r(mysql_result($result, 0));
// Equals this
print_r(TRUE);
In above case both will return 1 and 0 for FALSE
But In your Case you use echo and print_r together which is also wrong. Basically your query not able to find any record from DB.
echo print_r(0); //will always return 01 use either echo or print_r
Upvotes: 1
Reputation: 12391
The reason is count will return either 0 or any integer value but the result set will always be there because either the row of result set will have any value or zero but the row would exist
Iterate over the result set and see if it is 0 or any integer value.
Upvotes: 0