PHP/MySQL - SQL syntax error?

后端 未结 3 1824
予麋鹿
予麋鹿 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.

    0 讨论(0)
  • 2021-01-27 16:42

    You need to escape the strings you are sending in your SQL queries.

    For that, you can use the mysql_real_escape_string function.

    For instance, your code might look like this (not tested, but something like this should do the trick) :

    $str = "abcd'efh";
    $sql_query = "insert into my_table (my_field) values ('" 
      . mysql_real_escape_string($str)
      . "')";
    $result = mysql_query($sql_query);
    


    Another solution (Will require more work, though, as you'll have to change more code) would be to use prepared statements ; either with mysqli_* or PDO -- but not possible with the old mysql_* extension.


    Edit : if this doesn't work, can you edit your question, to give us more informations ? Like the piece of code that causes the error ?

    0 讨论(0)
  • 2021-01-27 16:46

    put your SQL query into a variable e.g.

    $query = "SELECT * FROM table WHERE field= ".mysql_real_escape_string($var)."";
    
    echo $query;
    
    $result = mysql_query($query);
    

    you can then inspect what is actually sent to mysql as the query

    0 讨论(0)
提交回复
热议问题