准备好的语句绑定变量应该在它应该返回0

时间:2013-08-18 00:26:06

标签: php prepared-statement

在以下代码中,如果 $ get_artist 是数据库中不存在的主键,则绑定变量 $ artistid 应始终返回0,右?但它没有,它总是没有返回,不是0,没有! 为什么呢?

if (isset($_GET['artist']) && is_numeric($_GET['artist'])) {
   $get_artist = (int)$_GET['artist'];
}

$sql = 'SELECT artist_id, name, legal_name, photo_basename
        FROM artist
        WHERE artist_id = ?';
$conn = connect('read');
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('i', $get_artist);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
$stmt->bind_result($artistid, $name, $legalname, $photo);
$stmt->fetch();
$stmt->free_result();
$stmt->close();


// if $get_artist is an invalid primary key, it should echo 0, right?
echo $artistid;

1 个答案:

答案 0 :(得分:1)

如果查询没有返回任何行,则永远不会填充变量(包括$artistid)。

您可以查看return value of $stmt->fetch()。如果是null,则没有(更多)行。如果它在您第一次调用它时返回null,则表示根本没有结果行,并且您的变量将不会设置为任何内容(因此PHP默认值null可能适用)。