简体   繁体   中英

php mysqli not working

I am making a chat application and this is the part that checks for new additions.

<?php
$servername = "*";
$username = "*";
$password = "****";
$dbname = "*"; 

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
    die("Connection failed: " . mysqli_connect_error($conn));
} 
$id = $_GET['id'];
$sql = "SELECT position, user, comment,time FROM chat WHERE position > $id";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows() > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username=".$row['user']));
        $userImage = $row2["avatar"];
        echo "<div class='container-fluid well'><p class='left'>"."<img class='img-circle zoom' src='/profile_images/".
        $userImage
        ."' style='width:32px;height:32px;'>".$row["user"]. ": " . $row["comment"]. "</p><h4><small class='right'> at ".$row['time']."</small></h4></div>";
    }
}
mysqli_close($conn);
?>

it was working until I changed the line

$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username=".$row['user']));

Help would be appreciated.


this is my html: There is more. but this is the most important

<div id='newchat'></div>
<script>
$(document).ready(function(){
    getChat();
    var id = <?php echo $id ?>;
    function getChat(){
        setTimeout(getChat,1000);
        $.get("getChat.php?id="+id,function( text ) {
            if (text != ""){
                id ++;
                $( "#newchat" ).prepend( text );
            }
        });
    }
});
</script>

you forget 2 '

$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE
username='".$row['user']."'"));

Try this query :

$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM login WHERE username='{$row['user']}'"));

Side note : Your query is unsafe. Read this How can I prevent SQL injection in PHP? .

Simply use this query:

"SELECT * FROM login WHERE username='".$row['user']."'"

instead of

"SELECT * FROM login WHERE username=".$row['user']

and if you want a simple query then use:

$usr = $row['user'];
$row2 = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM 
login WHERE username=$usr"));

It'll definitely work.

Write your query as below:-

$sql = "SELECT * FROM login WHERE username='{$row['user']}'";

mysqli_fetch_assoc(mysqli_query($conn,$sql));

Hope it will help you :)

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