sqlselect返回数组,但php将其视为null

toiithl6  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(335)

我通过php在mysql中选择了一些东西,这个命令返回了一些数组(这是正确的),但是当我把返回的select放在if条件中并询问它是否返回null时,php说它返回null(这是不正确的,因为它返回的是数组)

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';
}

我试着用!是空的,它无论如何都不工作。我试图将具有相同值的select命令直接放在phpmyadmin中,它返回数组,所以我很困惑。你能帮我吗?

dpiehjr4

dpiehjr41#

pdo的 fetchAll() 返回一个数组,如果没有结果,则返回一个空数组(不为null)。
只是使用 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';
}

旁注,你的函数并没有什么特别的作用。你可以用这个来达到同样的效果:

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

如果使用pdo Package 器,它可能会更短。例如,使用我自己的 Package 器grumpypdo

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

如果有变量要传递给查询,那么

$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]);

相关问题