PHP and MySql check if table is empty

I'm a little noob, and it's hard for me ...

I need some code that looks for a db table to find a row that matches the variable $ id. In the "description" field there is a field that I need to capture. If it is null, I need to show one message, if not another. Here is the code I have (I know that I need to add the mysqli escape line just by doing it very quickly 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>';
}
+5
source share
4 answers

mysqli_fetch_arraywill retrieve the row regardless of whether the columns in this row are null. You want to check if installed $row['description']instead of installing $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: , , , 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>';
}

, .

+11

:

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

!$row , . null, :

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

, ( 0 null):

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

, , 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'];

, description, No description . , if PHP.

+2

All Articles