PHP & MySql check if table is empty

房东的猫 提交于 2021-02-07 14:31:23

问题


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

回答1:


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

EDIT: Or, as an alternative, you can not fetch rows from the database where description is 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.




回答2:


The !$row will only occur if no record is found. If the field description is really null, you have to check it this way:

if(is_null($row['description'])){

but I recommend you to check if the value is empty (or 0 or null):

if(empty($row['description'])){



回答3:


BTW, you can do the check from within your query using 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. So that way, you can do away with the if condition of PHP.




回答4:


How about:

SELECT COUNT(*) FROM table WHERE `description` IS NOT NULL


来源:https://stackoverflow.com/questions/4854148/php-mysql-check-if-table-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!