简体   繁体   中英

What can't I UPDATE my table with PHP?

I'm trying to update a MySQL table with some simple PHP, but every time I run this command, I get my error message: "Site is offline, please check back later!" The string I'm inputting is only one simple paragraph but it's got some HTML code in it. What kind of sanitizing is it going to take to get this thing to work? Here's the code:

if (!empty($_POST) && $_SESSION['logged'] == 1)
{
    $title = $_POST['title1'];
    $body = $_POST['body1'];
    $query = "UPDATE pages SET title = '$title', body = '$body' WHERE id = '$id'";
    $do_query = mysql_query($query) or die ("Site is offline, please check back later!");
}

And the paragraph I'm trying to update with:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. <br /><br />Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <br /><br />Please visit <a href="http://lipsum.com">Lipsum's website</a> for more info.

To directly answer your question, your SQL query is failing because the text you're inserting contains a single-quote, ' , and you're not escaping it.

To fix this, you can use mysql_real_escape_string() to sanitize your data:

$title = mysql_real_escape_string($_POST['title1']);
$body = mysql_real_escape_string($_POST['body1']);

However, I would highly recommend you take the time now to stop using the older mysql_ functions and switch to a more-supported MySQLi or PDO library; these will allow you to use prepared statements to prevent this issue altogether.

An example with MySQLi:

$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare('UPDATE pages SET title = ?, body = ? WHERE id = ?');
$stmt->bind_param("s", $_POST['title1']);
$stmt->bind_param("s", $_POST['body1']);
$stmt->bind_param("i", $id);
$stmt->execute();

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