SenTisso
SenTisso

Reputation: 641

SQL SELECT returns array but PHP considers that as null

I'm selecting something in mySQL via PHP and that command returns some array (which is right), but when I put that returning SELECT inside if condition and ask if it is returning null than PHP says it is returning null (which is not right, because it is returning array)

include '../db.php'; // my config

function select($command) {
  global $db;
  $sql = "".$command."";
  $sqlDone = $db -> prepare($sql);
  $sqlDone -> execute();
  $data = $sqlDone -> fetchAll();
  return $data;
}

$select = "SELECT likes.ID, likes.ID_user, likes.ID_post FROM likes WHERE likes.ID_user = '53' AND likes.ID_post = '2'"

if (select($select) == null) { // goes throw this
  print_r(select($select)); // returns array
} else {
    echo 'not null';
}

I tried to use !is_null and it doesn't work anyway. I tried to put that select command with same values directly inside phpmyadmin and it returns array, so I'm confused. Can you help me out?

Screenshot of phpmyadmin

Upvotes: 1

Views: 866

Answers (1)

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

PDO's fetchAll() returns an array, if there are no results, it returns an empty array (not NULL).

Just use empty()

$return = select($select); //put this into a variable, because if you don't, you'll query the database twice and may get different results.
if (empty($return)) { // goes throw this
  print_r($return); // returns array
} else {
    echo 'not null';
}

Side note, your function doesn't really do anything special. You could achieve the same thing with this:

$return = $db->prepare($select)->execute()->fetchAll();

If you used a PDO wrapper, it could be even shorter. For example, using my own wrapper GrumpyPDO, you would use

$return = $db->all($select);

then if you had variables to pass to the query, you would do

$select = "SELECT likes.ID, likes.ID_user, likes.ID_post FROM likes WHERE likes.ID_user = ? AND likes.ID_post = ?"
$return = $db->all($select, [$userid, $postid]);

Upvotes: 1

Related Questions