开发者

html insertion in sql table

开发者 https://www.devze.com 2023-02-05 12:45 出处:网络
I\'m trying to insert a value into my sql table that has html in it: like follows <? $story =\"<div class=\'post\'><p class=\'date\'>$mont<b>$day</b></p><h2class=\

I'm trying to insert a value into my sql table that has html in it: like follows

<?
$story ="<div class='post'><p class='date'>$mont<b>$day</b></p><h2    class='title'>lkjljt</h2><p class='meta'><small>Posted $name | $school, $date | Rating</small></p><div class='entry'>$message</div></div>";

$db = mysql_connect("host", "user", "password"); 
mysql_select_db("db", $db); 

 if (!$db)
  {
  die('Could not connect: ' . mysql_error());
  }

 $sql = "INSERT INTO Post VA开发者_如何学GoLUES ('', '$date', '$time', '$story',  '$school','$location', '$sex', '$zipcode', '$name');";

 $result = mysql_query($sql);


 if($result)
 { $success = " Your hookup has been submitted ";}
 else{
  $error = "something went horribly wrong" . mysql_error();}



 ?>

I keep getting a syntax error when I submit this page, and if I comment $story out, the query runs fine. How can I fix this?


The most likely reason is that $story contains single quotes, which will break the query. Protect it using mysql_real_escape_string

In general, this is a bad idea as it is open to SQL injection.

$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story',
       '$school','$location', '$sex', '$zipcode', '$name');";

At least, use mysql_real_escape_string which will protect the input for characters that have special meaning in a MySQL query. Use it on all textual columns.

$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '" .
       mysql_real_escape_string($story) . "','".
       mysql_real_escape_string($school) . "','".
       mysql_real_escape_string($location) . "', '$sex', '$zipcode', '" .
       mysql_real_escape_string($name) ."');";


If you didn't care about SQL Injection ( though I dont know why would you wouldnt ) you could also use htmlspecialchars to fix your problem. mysql_real_escape_string is obviously the better choice though like @cyberkiwi said

0

精彩评论

暂无评论...
验证码 换一张
取 消