PHP / MySQL:带有插入/更新查询的动态预处理语句

时间:2012-07-14 12:38:06

标签: php mysql dynamic

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

并且它非常适合将它放在一个单独的php文件中,我的其他文件使用查询作为参数调用它。

是否可以与其他查询(如插入和更新)进行类似的操作?

1 个答案:

答案 0 :(得分:1)

这是更新的例子:

$ 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();
    }