mercredi 1 novembre 2017

while($result= $sql->fetch_array()) not returning all rows from database

I am trying to return all messages to or from a user, not including the user and display the names, not including the user's name. For example, I sent a message to John, he sent a message back. I want to display the names of the people I sent a message to or someone sent to me, but without echoing my name.

If you still don't understand, here is my code:

$user = $_SESSION['name'];

$sql = $mysqli->query("SELECT * FROM `messages` WHERE `user_to` = '$user' OR `user_from` = '$user'");
            // if there are, display them
            if ($sql->num_rows > 0) {
                ?>
                <div id="messages">
                <?php
                while ($result = $sql->fetch_array()) { 
                    $user_from = $result['user_from'];
                    $user_to = $result['user_to'];

                    if ($user_from === $user) { // make sure the message isn't from the user
                        echo "<div id='from_" . $user_from . ">";
                        echo "<a href='/" . $user_to . "'>";
                        echo "</div>";
                    } else {
                        echo '';
                    }
                }
                ?>
                </div>

Here is what my database looks like:

id | message | user_to | user_from |

1 | hello | Alex Chang | John Doe |

2 | hey! | John Doe | Alex Chang |

The code is returning nothing, meaning the else statement was called. I would be expecting the name John Doe to return. Why isn't it?

I hope you can understand, as english isn't my first language.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire