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.

Havelock
  • 6,913
  • 4
  • 34
  • 42
user1684586
  • 175
  • 2
  • 4
  • 13

5 Answers5

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();
}
Havelock
  • 6,913
  • 4
  • 34
  • 42
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');
}
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
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";
}
BenM
  • 52,573
  • 26
  • 113
  • 168
0

Use empty:

if( empty( $rows) ) { ... }
moonwave99
  • 21,957
  • 3
  • 43
  • 64
0
if ( count( $rows ) == 0 ) {...}
Gustav Barkefors
  • 5,016
  • 26
  • 30