Jump to content

how to insert variables into mysql query

Recommended Posts

So my question is: how can I insert variables into my mysql queries in php?


This is my code now, I would like to use the $me and the $friend variables to work in the sql query:

function newChat($me, $friend) {
    global $conn;
    $sql = "SELECT id FROM chats
        WHERE (person1 = $me AND person2 = $friend)
        OR (person1 = $friend AND person2 = $me);";
    mysqli_query($conn, $sql) or die('Error querying database.');
    echo "check <br />";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($result);

    while ($row = mysqli_fetch_array($result)) {
        echo $row['id'] . ' - ' . $row['person1'] . ' - ' . $row['person2'] . ' - ' . $row['date'] .'<br />';

newChat('John', 'Marie');

Also if I set $sql to "SELECT * FROM chats" it only gives me one row of my two test rowes in my database.

(it only gives the second row, and just ignores the first one? --> a screenshot of the database is at the end of this post)


Can anyone please help me with this? Thanks already!



Link to post
Share on other sites

You should always use prepared statements whenever you're using data in a query:




it only gives the second row, and just ignores the first one?

You get the first row before the loop but don't do anything with it.
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...