3

The following code shows an array of records in the $rows array from the MySQL query. I have added also an if statement to check if $rows turns up empty, but it is not working.

$rows = array();

$result1 = mysql_query("SELECT * FROM TestPhase where Pid<10", $db) or die("cannot select");
while($row = mysql_fetch_array($result1)) {
  $rows []= array(
    'id' => $row['id'],
    'parent' => $row['parent'],
    'name' => $row['name'],
  );

}


if($rows == ""){
    echo "No Data";

    }

This if statement is not working. How do I check if the array returns empty and echo "No Data".

How would I check to see if the array is empty in javascript? I have placed the $rows array in a var treeData.

if (treeData) is empty{
$("button").hide();
     }

How do I check if treeData is empty to hide the button.

1
  • How did you place the data from php into javascript? With json or from php? Commented Sep 25, 2012 at 15:20

5 Answers 5

28

PHP
Simply use empty(), i.e.

if(empty($rows)){
    echo 'No Data';
}

Alternatively you could also use count(), i.e.

if(count($rows) < 1){ // or if(count($rows) === 0)
    echo 'No Data';
}

JavaScript
You can use the length property

if(treeData.length == 0){
    $("button").hide();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this worked great. But please see the updated question. How do I do this in javascript?
3

Use count to check

if(!count($rows)){
    echo "No Data";
}

Using JavaScript, here is the example

var arr = new Array('one', 'two', 'three'); //assume you have list of values in array
if(!arr.length){ //if no array value exist, show alert()
   alert('No Data');
}

Comments

1

You can't treat an array like a string (i.e. $rows == ""). Use count() or empty() instead:

if(count($rows) == 0)
{
    echo "No Data";
}

Comments

0

Use empty:

if( empty( $rows) ) { ... }

Comments

0
if ( count( $rows ) == 0 ) {...}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.