Sign in to follow this  
Followers 0
WoHe

how to insert variables into mysql query

2 posts in this topic

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!

 

post-207375-0-52020800-1486850728_thumb.png

Share this post


Link to post
Share on other sites

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

 

http://www.w3schools.com/php/php_mysql_prepared_statements.asp

 

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0