How to create a secure mysql prepared statement in php?

前端 未结 6 575
夕颜
夕颜 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:14

    Quite late, but this might help someone:

    /**
    * Execute query method. Executes a user defined query
    *
    * @param string $query the query statement
    * @param array(Indexed) $col_vars the column variables to replace parameters. The count value should equal the number of supplied parameters
    *
    * Note: Use parameters in the query then supply the respective replacement variables in the second method parameter. e.g. 'SELECT COUNT(*) as count FROM foo WHERE bar = ?'
    *
    * @return array
    */
    function read_sql($query, $col_vars=null) {
        $conn = new mysqli('hostname', 'username', 'user_pass', 'dbname');
        $types = $variables = array();
        if (isset($col_vars)) {
            for ($x=0; $xprepare($query);
            $sql -> bind_param($types, ...$variables);
            $sql -> execute();
            $results = $sql -> get_result();
            $sql -> close();
        }else {
            $results = $conn->query($query) or die('Error: '.$conn->error);
        }
        if ($results -> num_rows > 0) {
            while ($row = $results->fetch_assoc()) {
                $result[] = $row;
            }
            return $result;
        }else {
            return null;
        }
    }
    

    You can then invoke the function like so:

    read_sql('SELECT * FROM mytable where userid = ? AND category = ? ORDER BY id DESC', array($_GET['userid'], $_GET['category']));
    

提交回复
热议问题