Search code examples
phpmysqlsqlpdobindparam

SQL bindParam not Working


I have problem with my code, I can't show data from my database I am using bindParam() and bindValue() it's still not working.

This is my code:

$id = $_GET['id'];
try{
    $database = new Connection();
    $db = $database->openConnection();

    $sql = "SELECT users.username, users.user_id, topic.*, post.* 
            FROM users INNER JOIN post
            ON users.user_id = post.user_id
            INNER JOIN topic
            ON topic.topic_id = post.topic_id
            WHERE topic.topic_id = :id";

    $stm = $db->prepare($sql);
    $stm->bindValue(":id", $id);
    $stm->execute();
    $row = $stm->fetch();

    foreach($db->query($sql) as $row){
        echo "<td>". $row['content'] . "</td>";
    }

}catch(PDOException $e){
    echo 'Connection Problem: '. $e->getMessage();
}

i am get this error:

 Connection Problem: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':id' at line 6 

but when i am use

$sql = "SELECT users.username, users.user_id, topic.*, post.* 
            FROM users INNER JOIN post
            ON users.user_id = post.user_id
            INNER JOIN topic
            ON topic.topic_id = post.topic_id
            WHERE topic.topic_id = ". $id;

$stm = $db->prepare($sql);
$stm->execute();

It worked perfectly

Thanks in advance


Solution

  • In the bindValue() code, your loop is wrong. You should be looping over the array $row It should be

    foreach($row as $value){
       echo "<td>". $value['content'] . "</td>";
    }