Learning SELECT FROM WHERE prepared statements

后端 未结 4 1916
清歌不尽
清歌不尽 2020-12-04 04:07

Can someone re-write the below code as a prepared statement?

result = mysqli_query($con,\"SELECT * FROM note_system WHERE note = \'$cnote\'\") 
or die(\"Erro         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 04:46

    This is one way to do it with PDO:

    $sel = $db->prepare("SELECT * FROM note_system WHERE note=:note");
    $sel->execute(array(':note' => $_POST['note']));
    $notes = $sel->fetchAll(PDO::FETCH_ASSOC);
    

    See the placeholder :note in the query in line 1, which is bound to $_POST['note'] (or any other variable for that matter) in line 2.

    If I want to run that query again, with a different value as :note, I'll just call lines 2 and 3.

    Displaying the results:

    foreach ($notes as $note) {
    
        echo $note['id'] . ": " . $note['text'] . "
    "; }

提交回复
热议问题