Reputation: 135
i've got a problem with my php script. I want to check my script if there is anything in array and if there's no to echo a message but when array is empty it just don't echo nothing.
That's my code:
include("mysql_connect.php");
$name = $_POST['playerName'];
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if($name==""){
echo 'Type in player name!';
}else{
while($usersList= mysql_fetch_assoc($users)){
if(!array_count_values($usersList)){
echo 'Player not found';
}else{
echo $usersList['username'].', ';
}
}//While end.
}//If name is empty end.
Upvotes: 2
Views: 501
Reputation: 5012
The problem seems is that, if a user enters a invalid
name, the while loop
does not execute, as the query simply cannot find any rows, the code
should be as follows
include("mysql_connect.php");
$name = $_POST['playerName'];
if( $name === "" ){
echo 'Type in player name!';
} else {
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if ( mysql_num_rows($users) == 0) {
echo "Invalid Player name provided";
} else {
while($usersList= mysql_fetch_assoc($users)){
{
echo $usersList['username'].', ';
} //While end.
}
}//empty name
Notes:
re-formatted
the code as it looked uglyexecute
the query when the name is empty
!Upvotes: 1
Reputation: 2572
As mentioned, you have to check for rows before the loop.
$rows = mysql_num_rows($users);
if($rows==0) echo "No rows..";
else {
foreach() {
Upvotes: 1
Reputation: 586
Your while loop wont be executed if $users is empty, so the condition:
if(!array_count_values($usersList)){
echo 'Player not found';
}
will never be met because it is contained in a loop which will never run.
Upvotes: 0
Reputation: 110
instead of
if(!array_count_values($usersList)){
use
if(empty($usersList)){
Upvotes: 0