How to create a secure mysql prepared statement in php?

前端 未结 6 468
夕颜
夕颜 2020-11-22 03:29

I am new to using prepared statements in mysql with php. I need some help creating a prepared statement to retrieve columns.

I need to get information from different

6条回答
  •  死守一世寂寞
    2020-11-22 04:10

    Here's an example using mysqli (object-syntax - fairly easy to translate to function syntax if you desire):

    $db = new mysqli("host","user","pw","database");
    $stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
    $stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));
    $stmt->execute();
    
    $stmt->store_result();
    $stmt->bind_result($column1, $column2, $column3);
    
    while($stmt->fetch())
    {
        echo "col1=$column1, col2=$column2, col3=$column3 \n";
    }
    
    $stmt->close();
    

    Also, if you want an easy way to grab associative arrays (for use with SELECT *) instead of having to specify exactly what variables to bind to, here's a handy function:

    function stmt_bind_assoc (&$stmt, &$out) {
        $data = mysqli_stmt_result_metadata($stmt);
        $fields = array();
        $out = array();
    
        $fields[0] = $stmt;
        $count = 1;
    
        while($field = mysqli_fetch_field($data)) {
            $fields[$count] = &$out[$field->name];
            $count++;
        }
        call_user_func_array(mysqli_stmt_bind_result, $fields);
    }
    

    To use it, just invoke it instead of calling bind_result:

    $stmt->store_result();
    
    $resultrow = array();
    stmt_bind_assoc($stmt, $resultrow);
    
    while($stmt->fetch())
    {
        print_r($resultrow);
    }
    

提交回复
热议问题