简体   繁体   中英

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. 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 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.

怎么样:

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

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'])){

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM