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

问题描述:

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

它的工作非常好,它是分开的我的其他文件调用的php文件与查询作为参数。

and it works really good to have it in a seperate php file which my other files calls to with a query as argument.

是否可以与其他查询类似,如插入和更新?

Is it possible to make something similar with other queries like insert and update?

这是更新的例子:

This is the updated example:

$ params是一个数组。

$params is an array.

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