PHP/MySQL:带有插入/更新查询的动态准备语句


PHP/MySQL: Dynamic prepared statement with insert/update query

我发现了这个http://net.tutsplus.com/tutorials/php/the-problem-with-phps-prepared-statements/

把它放在一个单独的php文件中非常好,我的其他文件用一个查询作为参数调用这个文件。

是否可以对插入和更新等其他查询进行类似的处理?

这是更新后的示例:

$params是一个数组。

 function insertToDB($params, $db) { //Pass array and db
        $fields = array();
        $conn = new mysqli('localhost', 'root', 'root', 'db') or die('XXX');     
        $stmt =  $conn->stmt_init();
        $stmt->prepare("SELECT * FROM ".$db); 
        $stmt->execute();
        $meta =  $stmt->result_metadata();
        while ($field = $meta->fetch_field()) { 
             $fields[] = $field->name;   
        }
        $fields = implode(", ", $fields);

        $placeholders = implode(',', array_fill(0, count($params), '?'));
        $types = '';
        foreach($params as $value) {
            $types.= substr(strtolower(gettype($value)), 0, 1); 
        }
        $ins = "INSERT INTO MYDB (".$fields.") VALUES (".$placeholders.")"; 
        $bind_names[] = $types; 
        for ($i = 0; $i < count($params); $i++) { 
            $bind_name = 'bind' . $i;
            $$bind_name = $params[$i];
            $bind_names[] = &$$bind_name;
        }
        if ($stmt->prepare($ins)) {
                call_user_func_array(array($stmt,'bind_param'),$bind_names); 
                $insresult = $stmt->execute(); 
        }
        return $insresult;
        $stmt->close();
    }