2

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.
2
  • WHERE username LIKE "'.$name.'%"'); is missing a ' before the variable Commented Apr 10, 2013 at 16:35
  • No it doesn't because i'm using " not ' :) Commented Apr 10, 2013 at 16:38

4 Answers 4

1

As mentioned, you have to check for rows before the loop.

$rows = mysql_num_rows($users);
if($rows==0) echo "No rows..";
else {
  foreach() {
Sign up to request clarification or add additional context in comments.

Comments

1

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:

  1. I have re-formatted the code as it looked ugly
  2. The query is executed only if a user provides some text for name, why execute the query when the name is empty !

Comments

0

instead of

if(!array_count_values($usersList)){

use

if(empty($usersList)){

Comments

0

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.

6 Comments

No because $name is seperate value
Try adding: echo 'here'; above if(!array_count_values($usersList)){ and see if the loop is being executed
It begins but when it's empty it doesn't do anything
so does it echo 'here' when you use a name that isnt in the database?
No it doesn't do anything. :/
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.