简体   繁体   English

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

[英]PHP/MySQL: Dynamic prepared statement with insert/update query

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

and it works really good to have it in a seperate php file which my other files calls to with a query as argument. 并且将其保存在一个单独的php文件中(它是我的其他文件以查询为参数调用的)确实非常好。

Is it possible to make something similar with other queries like insert and update? 是否可以对其他查询(例如插入和更新)做出类似的处理?

This is the updated example: 这是更新的示例:

$params is an array. $ 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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM