nuet maessen
nuet maessen

Reputation: 131

how to check in database for records

i am using a simple database for a guestbook. I just can't figure out how to check if there has nobody written in the guestbook yet. Because in that case, there should be an echo: "Be the first to write in the guestbook". Otherwise, the rows should be echoed. How can i do that?

Piece of the code:

if (mysqli_connect_errno($con))
{
    echo "Connectie Database mislukt: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT name,message,email,datetime FROM guestbook");

    while($row = mysqli_fetch_array($result))
{ ?>

     <div class="velden"> <!-- voor styling van alle echo's; zie CSS -->
        <div class="header">
            <div class="naam"><?php echo $row['name']; ?></div> <!-- echo naam-->
            <div class="email"><?php echo $row['email']; ?></div> <!-- echo email-->
            <div class="tijd"><?php echo $row['datetime']; ?></div> <!-- echo datum en tijd-->

        </div>

        <div class="bericht"><?php echo $row['message']; ?></div> <!-- echo bericht-->

    </div>
    <?php } ?>

So there should be something like:

If(nobody has written) {
echo 'Be the first to write in the database";
} else {
//do the echo's
}

Upvotes: 0

Views: 35

Answers (3)

hexerei software
hexerei software

Reputation: 3160

you should query

SELECT count(*) AS num FROM guestbook

if database is empty result will be 0, otherwise total number or rows in table

Upvotes: 0

dbinns66
dbinns66

Reputation: 791

You can get the number of rows after you execute the query and then if the count is 0 echo "be the first..." else do you while that displays the guestbook... http://www.w3schools.com/php/func_mysqli_num_rows.asp

Upvotes: 0

button
button

Reputation: 656

I believe mysqli_num_rows (http://php.net/manual/en/mysqli-result.num-rows.php) is what you're after.

if(mysqli_num_rows($result) == 0) {
    echo 'Be the first to sign my guestbook!';
} else {
    while($row = mysqli_fetch_array($result))
    { ?>
...
<?php } ?>
}

Here's an example from w3 schools: http://www.w3schools.com/php/func_mysqli_num_rows.asp

Upvotes: 1

Related Questions