[英]PHP & MySql check if table is empty
I'm a bit of a noob- and I'm having a hard time... 我有点像菜鸟 - 我很难过......
I need a bit of of code that searches a db table to find the row that matches the $id variable. 我需要一些代码来搜索db表以找到与$ id变量匹配的行。 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.
如果它为null,我需要显示一条消息,如果不是另一条消息。 Here's the code I have (I know I need to add the mysqli escape string, just doing this real quick from memory):
这是我的代码(我知道我需要添加mysqli转义字符串,只需从内存中快速执行此操作):
$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
will fetch a row regardless of if the columns in that row are null. 无论该行中的列是否为空,
mysqli_fetch_array
都将获取一行。 You want to be checking if $row['description']
is set instead of if $row
is set: 您想要检查是否设置了
$row['description']
而不是设置了$row
:
$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>';
}
EDIT: Or, as an alternative, you can not fetch rows from the database where description is NULL: 编辑:或者,作为替代方案,您无法从描述为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. 现在你要检查一下你是否能够抓住一排。
怎么样:
SELECT COUNT(*) FROM table WHERE `description` IS NOT NULL
The !$row
will only occur if no record is found. 只有找不到记录才会出现
!$row
。 If the field description is really null
, you have to check it this way: 如果字段描述确实为
null
,则必须以这种方式检查:
if(is_null($row['description'])){
but I recommend you to check if the value is empty (or 0 or null): 但我建议你检查值是否为空(或0或null):
if(empty($row['description'])){
BTW, you can do the check from within your query using COALESCE
: 顺便说一句,您可以使用
COALESCE
在查询中进行检查:
$query = "SELECT COALESCE(description, 'No description') FROM posts WHERE id = $id";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC) ;
echo $row['description'];
This way, when there is a value for the description
field, it will be shown otherwise No description
will be output. 这样,当
description
字段有值时,将显示否则将不输出No description
。 So that way, you can do away with the if
condition of PHP. 这样,你可以取消PHP的
if
条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.