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.
PHP if else while (with mysql) statement not working
-
14-10-2022 - |
質問
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']);
}
}
}
解決
他のヒント
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']);
}
}
}
所属していません StackOverflow