2

我有以下查询:

INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(0, 'hope', 'thisworks@gmail.com', 'i hope', 'this works')

我收到以下 MySQL 错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1

这是我的表架构:

在此处输入图像描述

这是我的主要 PHP 代码:

<?php
    require 'lib/class.Database.php';
    require 'lib/class.Messages.php';

    $messageDatabase = new Database('ipi2');
    $messageDatabase->newDatabaseUsers([
                                        ['Query','ipi_query','k2QvHmtxGhVN'],
                                        ['admin','ipi_admin','r0HHRsQ76kS2']
                                        ]);
    $messageDatabase->makeConnection('admin');

    var_dump($_POST);

    if(array_key_exists('sendMessage', $_POST)){
        // $query = "INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(?,?,?,?,?)";
        // $result = $messageDatabase->query($query, $_POST['to'], $_POST['fromName'], $_POST['fromEmail'], $_POST['subject'], $_POST['message']);

        $messages = new Messages($messageDatabase);
        $messages->postMessage([
                                'Message_userID' => (int)$_POST['to'],
                                'Message_fromName' => $_POST['fromName'],
                                'Message_fromEmail' => $_POST['fromEmail'],
                                'Message_subject' => $_POST['subject'],
                                'Message_body' => $_POST['message']
                                ]);
    }

    if(array_key_exists('getMessages', $_POST)){
        $query_get = "SELECT * FROM ipi_messages WHERE Message_userID = ?";
        $result_get = $messageDatabase->query($query_get, $_POST['user']);
    }
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Messages</title>
    <style type="text/css">h5, h6{margin: 0;padding: 0;}</style>
</head>
<body>
    <h3>Send Message</h3>
    <form name="sendMessage" method="post" action="">
        <h5>To:</h5>
        <select name="to">
            <option value=""></option>
            <option value="0">Fillip Peyton</option>
            <option value="1">Fillswitch</option>
        </select>
        <br/>

        <h5>Name:</h5>
        <input type="text" name="fromName">
        <h5>Email:</h5>
        <input type="text" name="fromEmail">
        <h5>Subject:</h5>
        <input type="text" name="subject">
        <h5>Message:</h5>
        <textarea name="message"></textarea>
        <br/>

        <input type="submit" name="sendMessage" value="Send">
    </form>

    <h3>Your Messages:</h3>
    <form name="getMessages" method="post" action="">
        <select name="user">
            <option value=""></option>
            <option value="0">Fillip Peyton</option>
            <option value="1">Fillswitch</option>
        </select>
        <input type="submit" name="getMessages" value="Get Messages">
        <?php
            if (isset($result_get)) {
                foreach ($result_get as $result) {
        ?>
                    <p>
                        <b><?php echo $result['Message_fromName']; ?></b><br/>
                        <?php echo $result['Message_fromEmail']; ?><br/>
                        <i><?php echo $result['Message_subject']; ?></i><br/>
                        <?php echo $result['Message_body']; ?>
                    </p><hr>
        <?php
                }
            }
        ?>
    </form>
</body>
</html>

类.Messages.php:

<?php
require_once 'lib/classFunctions.php';

class Messages
{
    protected $database;
    protected $userID = -1;

    public function __construct(Database $messageDatabase) {
        $this->database = $messageDatabase;
    }

    public function getMessages($userID = null){

    }

    public function postMessage(Array $columnsValues){
        // $query = "INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(?,?,?,?,?)";

        $columns = '';
        $values = '';
        $queryParams = array();

        foreach ($columnsValues as $column => $value) {
            $columns .= "$column, ";
            $values .= is_int($value) ? "$value, " : "'$value', ";
            $queryParams[] = $value;
        }

        $columns = substr($columns, 0, strlen($columns) - 2);
        $values = substr($values, 0, strlen($values) - 2);

        $query = "INSERT INTO ipi_messages ($columns) VALUES($values)";

        // array_unshift($queryParams, $query);

        // $result = $messageDatabase->query($query, $_POST['to'], $_POST['fromName'], $_POST['fromEmail'], $_POST['subject'], $_POST['message']);
        echo $query . '<br/>';
        return $result = call_user_func_array(array($this->database,'query'), refValues($queryParams));
    }

    public function deleteMessage(){}
}

类.Database.php:

<?php
require_once 'lib/classFunctions.php';

class Database
{
    protected $DATABASE = 'database';
    protected $SERVER = 'localhost';
    protected $DATABASEUSERS;
    protected $CONNECTION;


    public function __construct($database, $server = 'localhost'){
        $this->DATABASE = $database;
        $this->SERVER = $server;
    }

    public function makeConnection($userType){
        $user = $this->DATABASEUSERS[strtolower($userType)];
        $this->CONNECTION = new mysqli($this->SERVER, $user->getUsername(), $user->getPassword(), $this->DATABASE) or die('Cannot make connection to database...');
    }

    public function escapeSpecialChars($string){
        return $this->CONNECTION->real_escape_string($string);
    }

    public function newDatabaseUser($userType, $username, $password){
        $userType = strtolower($userType);
        $this->DATABASEUSERS[$userType] = new DatabaseUser($userType, $username, $password);
    }

    public function newDatabaseUsers($usersCollection){
        foreach ($usersCollection as $user) {
            $userType = strtolower($user[0]);
            $username = $user[1];
            $password = $user[2];       

            $this->DATABASEUSERS[$userType] = new DatabaseUser($userType, $username, $password);
        }
    }

    public function closeConnection(){
        if($this->CONNECTION)
            $this->CONNECTION->close();
        else
            throw new Exception("No connection available.", 1);
    }

    public function query($query, $vars = null){
        $stmt = $this->CONNECTION->stmt_init();

        $args = func_get_args();
        if($stmt->prepare($query)){

            if($vars != null){
                $queryParams = array();
                $queryTypes = '';
                $argsCount = count($args);

                for( $i = 1 ; $i < $argsCount ; $i++ ){
                    $var = $args[$i];
                    $varType = gettype($var);
                    switch ($varType) {
                        case 'string':
                            $queryTypes .= 's';
                            break;
                        case 'integer':
                            $queryTypes .= 'i';
                            break;
                        case 'double':
                            $queryTypes .= 'd';
                            break;
                        case 'blob':
                            $queryTypes .= 'b';
                            break;

                        default:
                            throw new Exception("Could not bind parameter of type: " . $varType, 1);                        
                            break;
                    }
                } 
                $queryParams[] = $queryTypes;

                for( $i = 1 ; $i < $argsCount ; $i++ )
                    $queryParams[] = $args[$i];

                // $stmt->bind_param($queryParams);
                call_user_func_array(array($stmt,'bind_param'), refValues($queryParams));
            }

            $isExecuted = $stmt->execute();
            if($isExecuted)
                return $result = $stmt->get_result();
            else
                die("Could not execute query($query):" . $this->CONNECTION->error);

        }else{
            die("Could not prepare statement: " . $this->CONNECTION->error);
        }

        $stmt->reset();
    }
}

class DatabaseUser
{
    protected $USERTYPE = 'query';
    protected $USERNAME = 'username';
    protected $PASSWORD = 'password';

    public function __construct($userType, $username, $password) {
        $this->USERTYPE = $userType;
        $this->USERNAME = $username;
        $this->PASSWORD = $password;
    }

    public function getUserType(){ return $this->USERTYPE; }
    public function getUsername(){ return $this->USERNAME; }
    public function getPassword(){ return $this->PASSWORD; }
}

类函数.php:

<?php
function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}

编辑:我添加了我正在使用的 PHP 类和脚本,并更新了我的 SQL 查询以使 0 成为 int 而不是字符串。

为什么我在准备 mysqli 语句时收到 SQL 错误?我尝试只使用 SQL 查询并在数据库上运行它,插入的行就好了。

4

3 回答 3

2

我重新创建了您的架构并使用您的查询插入了两行,一行来自 MySQL 命令行,另一行来自 PhpMyAdmin。截图在这里:示例截图。您的查询似乎是有效的,所以问题出在其他地方(可能在您的 PHP 代码中)。

这不是您的问题,但正如其他人所提到的,Message_userID 的数据类型是 INT 并且引号中有 0 表示字符串。

于 2013-06-07T09:02:51.867 回答
2
  1. 错误不在引用的部分,而是它之前。因此,尽管有很多评论,但“0”本身并没有错。
  2. 一眼看不到任何错误 - 因此,您必须调试代码。
    • 首先,您必须确保引用的查询是同一个有错误的查询。您必须始终将文件名和行号与错误消息一起放置。要做到这一点,而不是通常的无用die($mysqli->error)它必须是trigger_error($myqli->error."[$sql]")
    • 将查询拆分为多行以使错误消息更具信息性也是一个好主意。
于 2013-06-07T09:04:22.280 回答
2

我终于弄清楚我做错了什么。我收到该错误是因为我将实际值放入VALUES()我的 sql 部分。这样,当我的bind_param方法尝试绑定值时,它没有?要绑定的标记,而是看到了实际值。

我的新 class.Messages.php 看起来像:

<?php
require_once 'lib/classFunctions.php';

class Messages
{
    protected $database;
    protected $userID = -1;

    public function __construct(Database $messageDatabase) {
        $this->database = $messageDatabase;
    }

    public function getMessages($userID = null){

    }

    public function postMessage(Array $columnsValues){
        $columns = '';
        $values = '';
        $queryParams = array();

        foreach ($columnsValues as $column => $value) {
            $columns .= "$column, ";
            $values .= "?, ";
            $queryParams[] = $value;
        }

        $columns = substr($columns, 0, strlen($columns) - 2);
        $values = substr($values, 0, strlen($values) - 2);

        $query = "INSERT INTO ipi_messages ($columns) VALUES($values)";

        array_unshift($queryParams, $query);

        return $result = call_user_func_array(array($this->database,'query'), refValues($queryParams));
    }

    public function deleteMessage(){}
}

感谢大家的帮助!

于 2013-06-08T07:45:20.647 回答