PHP Mysql If statement not working - php

Got a issue where if the rows are equal to 0 the else statement is not called. if i type in the correct details on the site, the first condition is met and the xml is displayed, however if the incorrect details are entered, the error xml is not displayed.
echo "<users>";
$result = mysql_query("SELECT * FROM `numbers` WHERE `email` = '".$email."' AND `password` = '".$password."'") or die('Invalid query: ' . mysql_error());
if (!$result) die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if(mysql_num_rows($result) != 0)
{
echo "<usercallback>";
echo "<id>".$row['id']."</id>";
//echo "<number>".$row2['number']."</number>";
//echo "<gender>".$row2['gender']."</gender>";
//echo "<relationship>".$row2['relationship']."</relationship>";
echo "</usercallback>";
}
else
{
echo "<usercallback>";
echo "<id>error</id>";
echo "</usercallback>";
}
}
echo "</users>";

actually you have to put the if mysql_num_rows check outside the while block
echo "<users>";
$result = mysql_query("SELECT * FROM `numbers` WHERE `email` = '".$email."' AND `password` = '".$password."'") or die('Invalid query: ' . mysql_error());
if(mysql_num_rows($result) != 0)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<usercallback>";
echo "<id>".$row['id']."</id>";
//echo "<number>".$row2['number']."</number>";
//echo "<gender>".$row2['gender']."</gender>";
//echo "<relationship>".$row2['relationship']."</relationship>";
echo "</usercallback>";
}
}
else
{
echo "<usercallback>";
echo "<id>error</id>";
echo "</usercallback>";
}
echo "</users>";

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
If there are no rows then $row will be false and it will never enter the above while loop.
So you can not get error message

You check for rows while performing the loop, you should check for the number of rows BEFORE the while loop.

It looks like you're expecting a zero-row response from MySQL to result in an undef $result. That's not what happens. mysql_query() returns null if there was an error. You can test the "truth" of its return value to see if the query ran correctly. If the query results in 0 rows of response, it ran correctly. The value to test, then is mysql_num_rows($result).
However, it can be done simpler. I usually write this like:
$res = mysql_query("SELECT 1");
if (!$res) {
//do whatever error reporting if the SQL was bad
//though you should probably deal with any condition that ends up
//here before you go into production!
}
if (mysql_num_rows($res) == 0) {
//put out my "no results found" message
}
while ($row = mysql_fetch_assoc($res)) {
//do my per-row business
}
mysql_fetch_assoc() returns false when there are no (or no more) results to return. So if it's empty, that while loop will never run, so it doesn't need to be inside an else.

Related

Handling x2 (multiple) php $sql $results with if statement

I have a sql database that when a key is passed from the web page input box back to the sql database (server)
this generates the encoded key and passes it back to the web page.
If the wrong key is sent then it returns wrong key. If it is correct it will return the generated key.
This works perfectly.
However when i try to add an additional check in the name of payment 1 for true 0 for false i can not combine the two. Meaning i would like both conditions to be met to make this work. Here is the code that works.
$sql = "SELECT decrypt_key FROM keys WHERE software_key=" . "'" . $software_key_encoded . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["decrypt_key"];
}
} else {
echo "Failed";
}
$conn->close();
}
else {
echo "Failed";
}
followed by what i am trying to do, This throws the error of
Trying to get property of non-object in /---/ Failed
$sql = "SELECT decrypt_key FROM keys WHERE software_key=" . "'" . $software_key_encoded . "'";
$eql = "SELECT payment FROM new_keys WHERE payment =1";
$result = $conn->query($sql) && $result1 = $conn->query($eql);
if ($result->num_rows > 0 && $result1->num_rows > 1) {
while($row = $result->fetch_assoc()) {
echo $row["decrypt_key"];
#echo $row["payment"];
}
} else {
echo "Failed";
}
$conn->close();
}
else {
echo "Failed";
}
$result = $conn->query($sql) && $result1 = $conn->query($eql);
change this line to:
$result = $conn->query($sql);
$result1 = $conn->query($eql);
and in if statement change $result1->num_rows > 1 to $result1->num_rows > 0;
Split the result variables in 2 different statements like below
$result = $conn->query($sql);
$result1 = $conn->query($eql);
If you still face any issue please post the error message too.

PHP and SQL wont work?

$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if (!$sql) {
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)); {
echo $row1;
}
} else {
echo "Funker ikke";
}
I cant get it to work, all I get is the: else "Funker ikke".
1) Using wrong if condition. If query return true then insert into if condition
2) Wrong echo data using MYSQL_NUM. It return numeric array
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {// if true
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)) {
echo $row1['0'];//numeric array
}
} else {
echo "Funker ikke";
}
UPDATED as per below comments
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
$row1 = mysqli_fetch_array($sql, MYSQL_NUM);
echo $row1['0']; //numeric array
} else {
echo "Funker ikke";
}
Read http://php.net/manual/en/mysqli-result.fetch-array.php
Your code is correct except the not sign before sql in if condition.According to you if your sql query is wrong then the $row1 is displayed else if it is correct then "funker ikke" gets printed.Just the opposite. This code works:
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
// as the query can only return 1 row the while look is unnecessary
//while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)) {
$row = mysqli_fetch_array($sql, MYSQL_NUM)
echo $row[0];
} else {
echo "Funker ikke";
}
Your code are having two error there.
First, it should be true condition only can get into the display loop. But you put the condition as !$sql means false only can get into the loop. So, you should change !$sql to $sql. Besides, after the While loop should not direct put the semicolon. You try see the following code
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM))
{
echo $row1[0];
}
}
else {
echo "Funker ikke";
}
There are a few errors in your code
First you do not need a while loop to process a single result, SELECT COUNT() can only return one row.
Second as mysqli_query() for a SELECT query will return either FALSE or a mysqli_result object it would be better to flip your if condition as below and test specifically for FALSE rather than TRUE.
Third, a mysqli_fetch_array($sql, MYSQL_NUM) returns an array, you have to use array notation to get the only returned value i.e. $row[0]
Also when any mysqli_ function fails it leaves some error information that is very useful, so show that info or send it to an application error file if you dont want users to see them when the code goes live.
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql === FALSE) {
echo "Funker ikke";
echo mysqli_error($db);
exit;
} else {
$row = mysqli_fetch_array($sql, MYSQL_NUM);
echo $row[0];
}

PHP if else while (with mysql) statement not working

I have this piece of code in a function of mine that echos "Empty" if it cannot grab the data stored in the variable $result. The "Empty" part works fine. However, it will not echo the users data if the conditional enters the else part, why?
$result = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC LIMIT ".$load.",1") or die (mysql_error());
if(!mysql_fetch_row($result)) {
echo "Empty";
} else {
while($data = mysql_fetch_array($result))
{
if($name == true) {
echo ucfirst($data['user']);
} else {
echo ucfirst($data['earnings']);
}
}
}
By calling mysql_fetch_row($result) as a test, you are missing the first row of your data always. Check if number of rows is 0 instead.
HI I think you issue is in mysql_fetch_array(). This function will return array not associative array..
you can use
$result = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC LIMIT ".$load.",1") or die (mysql_error());
if(mysql_num_rows($result) == 0) {
echo "Empty";
} else {
while($data = mysql_fetch_array($result,MYSQL_BOTH))
{
if($name == true) {
echo ucfirst($data['user']);
} else {
echo ucfirst($data['earnings']);
}
}
}
Use mysql_num_rows intead of mysql_fetch_row to check empty recordset.
I pass the 2nd parameter in mysql_fetch_array which MYSQL_BOTH that will return both array and associative array..
Or you can use
mysql_fetch_assoc() function istead of mysql_fetch_array()..
Feel free to ask question..
try this
$result = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC LIMIT ".$load.",1") or die (mysql_error());
if(!$result) {
echo "Empty";
} else {
while($data = mysql_fetch_array($result))
{
if($name == true) {
echo ucfirst($data['user']);
} else {
echo ucfirst($data['earnings']);
}
}
}

while ($row=mysql_fetch_array($query)) is not working

What i try to do is check the user's Id by verifying in a cookie (called "identification").
thats my code:
if(!$noCookie) {
$sql = "SELECT * FROM `". TABLE_PREFIX ."_logged` WHERE `logged_cookie` = '". $usersCookie ."' LIMIT 1";
$query = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($query) <= 0) {
echo 'yes cookie';
$row = mysql_fetch_array($query) or die(mysql_error());
print_r($row);
while ($row=mysql_fetch_array($query)) {
echo $usersId = $row["logged_user_id"];
}
} else {
echo 'no cookie';
}
}
What happends is that if the user's cookie is the same one like in the table,
it will return the user's id.
so thats what im trying to do, the IF says "yes cookie", but inside the while it doesnt do anything!
and its not giving me an error.
Since there are no rows, there's nothing to be fetched.
if (mysql_num_rows($query) <= 0) {
Should this be > 0?
You only ran mysql_fetch_array when mysql_num_rows($query) evaluated to 0 or less; i.e. there are no rows.
Perhaps you meant:
if (mysql_num_rows($query) > 0) { // <-----
echo 'yes cookie';
$row = mysql_fetch_array($query) or die(mysql_error());
// ...
}
else {
echo 'no cookie';
}
Also note that you're running mysql_fetch_array in two different places, which is normally not right. Your while loop will not include the first result row, because you already did mysql_fetch_array once before the loop.
if(!$noCookie) {
$sql = "SELECT * FROM `". TABLE_PREFIX ."_logged` WHERE `logged_cookie` = '". $usersCookie ."' LIMIT 1";
$query = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($query) > 0) {
echo 'yes cookie';
$row = mysql_fetch_array($query) or die(mysql_error());
foreach ($row as $r)
echo $r["logged_user_id"];
} else {
echo 'no cookie';
}
}

How can I show a message when no rows have been selected in mysql, php?

My code looks like this:
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
Problem is that when there is no row to select, nothing happens, my $row array is empty.
How can i have this present a message of "no row found" when no rows match the select?
try
if (mysql_num_rows($result) == 0) {
// Show message
} else {
// do your while stuff here
}
Use mysql_num_rows() to determine the amount of rows in your result.
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
if(mysql_num_rows($result) == 0) {
echo "No row found!"
} else {
while($row = mysql_fetch_array($result)) {
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
}
}
if (mysql_num_rows($result) == 0) {
echo "Result is empty!";
}
You should've read the description of mysql_query, it gives you the answer: http://php.net/mysql_query
mysql_num_rows() only works on buffered queries. If you have potentially a large/huge result set you might switch to unbuffered queries and num_rows is not an option anymore.
You can test the return value of the first call to mysql_fetch_array(). If it's FALSE there were no matching records.
<?php
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo '0 rows';
}
else {
do {
echo htmlspecialchars($row['x']), "<br />\n";
} while($row=mysql_fetch_array($result, MYSQL_ASSOC));
}
The downside of this do { } while() is that the $row=mysql_fetch... code has been duplicated. But it's only a small doublet.
This method never seems to fail for me.
if(!$result = mysqli_query($con,"SELECT * FROM `picdb` WHERE `picid` = '$picid' ")){
// Enter you error message here.
} else {
// Do all your magic.
}

Categories