简体   繁体   中英

Query works in phpMyAdmin but not PHP

In phpMyAdmin I have a simple query:

SELECT * FROM `recent` WHERE datediff(now(), `timestamp`) > 1

BUT when I try to do this in my clear_recent.php:

<?php $result = $conn->query("SELECT * FROM `recent` WHERE datediff(now(), `timestamp`) > 1"); ?>
    <?php foreach ($result->fetch_assoc() as $row): ?>
    <?php while($row = $result->fetch_assoc()) { ?>
    <tr>
        <td><?php echo($title = $row["id"]); ?></td>
        <td><?php echo($title = $row["pid"]); ?></td>
        <td><?php echo($title = $row["user_id"]); ?></td>
        <td><?php echo($title = $row["timestamp"]); ?></td>
    </tr>
    <?php } ?>
<?php endforeach; ?>

I get an error:

Invalid argument supplied for foreach() in /database/chron/clear_recent.php

Cannot for the life of my figure out what's wrong!!!! Please help!

您收到此错误是因为此查询没有返回任何行。

You should check if the query returns any row. try the following code.

<?php 
    $result = $conn->query("SELECT * FROM `recent` WHERE datediff(now(), `timestamp`) > 1");
    $rows = $result->fetch_assoc();

    //check if some rows available.
    if (count($rows) > 0) {
        foreach ($rows as $row) {
            while ($row = $rows) {
?>
        <tr>
            <td><?php echo($title = $row["id"]); ?></td>
            <td><?php echo($title = $row["pid"]); ?></td>
            <td><?php echo($title = $row["user_id"]); ?></td>
            <td><?php echo($title = $row["timestamp"]); ?></td>
        </tr>
<?php 
            }
        } 
    } 
?>

additional question: why you use while loop under the foreach loop? is it right?

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