user2948911
user2948911

Reputation: 133

MYSQL PHP : update query results in a syntax error

I'm trying to update the content of a database (specifically the post content of one of the posts database's records).

So here's my PHP code :

$update_sql = "UPDATE wp_posts SET post_content='$new_content' WHERE ID=602";

if (mysqli_query($conn, $update_sql)) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . mysqli_error($conn);
}

This is what I get:

Error updating record: 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 'attention�sur 
les plats eux-m�mes, le service est lui aussi tout en 
simplicit' at line 1

I don't know what I'm doing wrong. All I know is that $new_content contains a very long string (an entire wordpress post's content, complete with various HTML tags).

What should I do for it to accept my update query ?

Thanks for your help

Upvotes: 2

Views: 170

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

From the MySQL manual describing VARCHAR:

A variable-length string. Note: Trailing spaces are removed when the value is stored (this differs from the ANSI SQL specification) The range of Length is 1 to 255 characters. VARCHAR values are sorted and compared in case-insensitive fashion unless the BINARY keyword is given.

You are trying to INSERT a string which is too long for the post_content column. Try using a MEDIUMTEXT instead, which can store about 16 million characters.

Upvotes: 0

prasanth prem
prasanth prem

Reputation: 464

I think the problem is that you are trying to insert some special characters. like ``. You need to escape it
Use this function `

function clean($str)
{
    $str = @trim($str);
    if (get_magic_quotes_gpc()){
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}

In your code use like this
$update_sql = "UPDATE wp_posts SET post_content=clean('$new_content') WHERE ID=602";

Upvotes: 1

user1358298
user1358298

Reputation:

You need to escape the string before inserting it into the database

$update_sql = "UPDATE wp_posts SET post_content='" . mysqli_real_escape_string($new_content) . "' WHERE ID=602";

if (mysqli_query($conn, $update_sql)) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . mysqli_error($conn);
}

Upvotes: 1

Related Questions