PHP&MySQL检查表是否为空 [英] PHP & MySql check if table is empty
问题描述
我有点菜鸟,我很难受...
I'm a bit of a noob- and I'm having a hard time...
我需要一些代码来搜索数据库表以查找与$ id变量匹配的行.该表"description"中有一个字段需要我抓取.如果为空,我需要显示一条消息,如果不是另一条消息.这是我的代码(我知道我需要添加mysqli转义字符串,只需从内存中快速完成此操作即可):
I need a bit of of code that searches a db table to find the row that matches the $id variable. There's a field in that table 'description' that I need to grab. If it's null, I need to show one message, if not another. Here's the code I have (I know I need to add the mysqli escape string, just doing this real quick from memory):
$query = "SELECT description FROM posts WHERE id = $id";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC) ;
if(!$row){
echo "<p>'No description'</p>";
} else {
echo '<p>' . $row['description'] . '</p>';
}
推荐答案
mysqli_fetch_array
将获取一行,无论该行中的列是否为空.您要检查是否设置了 $ row ['description']
,而不是是否设置了 $ row
:
mysqli_fetch_array
will fetch a row regardless of if the columns in that row are null. You want to be checking if $row['description']
is set instead of if $row
is set:
$query = "SELECT description FROM posts WHERE id = $id";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(isset($row['description'])) {
echo "<p>No description</p>";
} else {
echo '<p>' . $row['description'] . '</p>';
}
或者,您也可以不从描述为NULL的数据库中获取行:
$query = "SELECT description FROM posts WHERE id = $id AND description IS NOT NULL LIMIT 1";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(! $row) {
echo "<p>No description</p>";
} else {
echo '<p>' . $row['description'] . '</p>';
}
现在,您将检查是否可以抓行.
Now you'd check to see if you were able to grab a row or not.
这篇关于PHP&MySQL检查表是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!