MySQLi insert into prepare error

2019-08-01 06:31发布

问题:

Hi I inserted a lot of stuff into a mysql databse.

But now I get an error in the prepare statement. I see Database prepare error. What am I doing wrong?

This is my Code:

$sql = "INSERT INTO
                Contact (IP,To,Name,Email,Subject,Text)
            VALUES 
                ( ?, ?, ?, ?, ?, ? )
           ";

    if (!$stmt = $db->prepare($sql)) {
        echo 'Database prepare error';
        exit;
    }

    $stmt->bind_param('ssssss', $ip_contact, $to_contact, $name_contact, $email_contact, $subject_contact, $text_contact);

    if (!$stmt->execute()) {
        echo 'Database execute error';
        exit;
    }

    $stmt->close();

My SQL table looks like this:

Contact:
- ID    int(11)    auto_increment    primary key
- IP    varchar(15)
- To    varchar(5)
- Name    varchar(20)
- Email    varchar(20)
- Subject    varchar(20)
- Text    varchar(600)

回答1:

For example to is a reserved word in mysql, you should change your code to:

$sql = "INSERT INTO
            `Contact` (`IP`,`To`,`Name`,`Email`,`Subject`,`Text`)
        VALUES 
            ( ?, ?, ?, ?, ?, ? )
       ";


回答2:

Firstly To is a reserved word in mysql, so you need to use it using quotes as defined here.

Secondly you need to set the values of variables before calling execute method.

$sql = "INSERT INTO
            Contact (IP,'To',Name,Email,Subject,Text)
        VALUES 
            ( ?, ?, ?, ?, ?, ? )
       ";

if (!$stmt = $db->prepare($sql)) {
    echo 'Database prepare error';
    exit;
}

$stmt->bind_param('ssssss', $ip_contact, $to_contact, $name_contact, $email_contact, $subject_contact, $text_contact);

$ip_contact = '123456';
$to_contact = '123456';
$name_contact = '12345';
$email_contact = '1111';
$subject_contact = 'test';
$text_contact = 'test';


if (!$stmt->execute()) {
    echo 'Database execute error';
    exit;
}

$stmt->close();

Now check, it should work now.



回答3:

To is a reserved word in MySQL. You must add backticks around it:

Contact (IP,`To`,Name,Email


标签: php mysqli