PHP/MySQL - SQL syntax error?

后端 未结 3 1860
予麋鹿
予麋鹿 2021-01-27 16:11

Now when I submit the character \' I get the following error listed below other then that everything is okay when I submit words. I am using htmlentities()

3条回答
  •  误落风尘
    2021-01-27 16:35

    You have to escape the strings, using the appropriate method. You didn't mention what PHP functions you used so it's hard to guess. You should post the relevant snippet of PHP, but here's a couple of examples:

    $text = "x'x";
    
    // MySQL extension
    mysql_query($db, "INSERT INTO table VALUES ('" . mysql_real_escape_string($text, $db) . "')");
    
    // MySQLi extension
    $db->query("INSERT INTO table VALUES ('" . $db->mysql_real_escape_string($text) . "')");
    
    // PDO's prepared statement
    $stmt = $pdo->prepare('INSERT INTO table VALUES (:myvalue)');
    $stmt->execute(array(
        'myvalue' => $text
    ));
    
    // Another example
    $stmt = $pdo->prepare(
        'SELECT *
           FROM users
          WHERE first_name = :first
            AND last_name  = :last'
    );
    
    $stmt->execute(array(
        'first' => 'John',
        'last'  => 'Smith'
    ));
    
    foreach ($stmt as $row)
    {
        echo $row['user_id'];
    }
    

    I strongly recommend using PDO's prepared statements, it's shorter to type and easier to use in the long run.

提交回复
热议问题