繁体   English   中英

MySQLi准备好的语句在插入时执行两次

[英]MySQLi prepared statement executes twice on insert

我通常不发布代码的详细版本; 但是,在这种情况下,可能有必要找出问题所在。 我有一个无法停止执行两次的类方法。 我在MySQLi预备语句上缺少任何特定信息吗? 我读过类似的问题,但都问同样无济于事。

之前,我曾问过一个问题,即按照惯例和最佳做法,如何在准备好的语句中使用eval进行动态查询。 有人告诉我使用call_user_func_array(),它工作得很好。 但是,我没有注意到该语句每次执行两次,即使使用旧的eval()代码也是如此。 因此,我整理了一段ACTUAL代码,该代码应该可以通过我的注释进行自我解释

    function insert($table, $query)
    {
        /**
         *
         * This code assumes you have a MySQLi connection stored in variable $db
         * USAGE: insert(table, array('field' => 'value');
         * 
        **/

        // Sets the beginning of the strings for the prepared statements

        $fields = $values = "(";
        $types = "";
        $params = array();

        foreach($query as $key => $val)
        {               
            // array keys = fields, and array values = values;
            $fields.= $key;

            // concatenate the question marks for statement
            $values.= "?";

            // concatenate the type chars
            $types.= is_string($val) ? "s" : (is_int($val) ? "i" : (is_double($val) ? "d" : "b"));

            // pass variables to array params by reference for call_user_func_array();
            $params[] = &$query[$key];

            if($val == end($query))
            {
                $fields .= ")";
                $values .= ")";
                array_unshift($params, $types);
            }
            else
            {
                $fields .= ", ";
                $values .= ", ";
            }
        }
        $str = "INSERT INTO {$table} {$fields} VALUES {$values}";
        if($stmt = $db->prepare($str))
        {
            call_user_func_array(array($stmt, 'bind_param'), $params);

            /**
             *
             * This is where I am pulling my hair out of my head and being 3
             * nothces away from banging my own head into the screen and
             * being without a computer at all.
             *
             * I have tried everything I can think of. I gotta be missing
             * something
             *
             * IT JUST KEEPS SENDING 2 ROWS DANG IT!
             *
             **/


            /////////////////////
            $stmt->execute();//// <---Help is needed here
            /////////////////////

            //-- Close connection;
            $stmt->close();
        }
        else
        {
            //-- Send a nice readable error msg
            die("<center><h3>FAULTY QUERY STRING</h3><h4>Please check query string</h4><p>{$str}</p>");
        }
    }

将代码格式从OOP更改为常规功能以进行测试,而无需创建类。

这是个老问题,但人们还是会偶然发现,我做到了。

我认为mysqli_query函数主要用于检索数据,我遇到了同样的问题,并通过在插入和更新查询中使用mysqli_real_query进行了修复。

暂无
暂无

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

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