简体   繁体   中英

PHP + MySQL SQL Syntax error

I have the following code

$id_post = mysql_real_escape_string($_POST['id']);
$forumid = (int)mysql_real_escape_string($_POST['forumid']);
$message = mysql_real_escape_string($_POST['message']);

mysql_query("UPDATE forum_reactions SET message = ".$message." WHERE id = ".$id_post." ");

message is the TEXT column

It gives this error

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'staat niet in het woordfilter lol WHERE id = 39' at line 1

You aren't encompassing the string for $message so SQL is attempting to use those as keywords, which they aren't. Try this:

$id_post = mysql_real_escape_string($_POST['id']);
$forumid = (int)mysql_real_escape_string($_POST['forumid']);
$message = mysql_real_escape_string($_POST['message']);

mysql_query("UPDATE forum_reactions SET message = '".$message."' WHERE id = ".$id_post." ");

The mysql_* functions are deprecated and you should move to mysqli_* or PDO.

http://php.net/manual/en/function.mysql-query.php

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

mysqli_query() PDO::query()

PDO Sample Usage:

<?php

try {

    // config
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=utf8';
    $username = 'root';
    $password = '';
    $options = array(
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ); // You should always use these options

    // conncect
    $pdo = new PDO($dsn, $username, $password, $options);

    // check posted values
    if (
        !isset($_POST['id'], $_POST['message']) ||
        !is_string($_POST['id']) ||
        !is_string($_POST['message'])
    ) {
        throw new RuntimeException('invalid parameters');
    }

    // SQL execution
    $stmt = $pdo->prepare('UPDATE forum_reactions SET message = ? WHERE id = ?');
    $stmt->execute(array($_POST['message'], $_POST['id']));

    // check result
    if ($stmt->rowCount()) {
        echo 'successfully updated';
    } else {
        echo 'specified ID not found.';
    }

} catch (Exception $e) {

    echo $e->getMessage();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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