Re: PHP Beginners Help

From: Date: Thu, 03 Jan 2008 04:11:00 +0000
Subject: Re: PHP Beginners Help
References: 1 2 3  Groups: php.db 
Request: Send a blank email to php-db+get-44473@lists.php.net to get a copy of this message
Ben Stones wrote:
Thanks all for your replies. Much appreciated. I have edited the code and took points into account: $con = mysql_connect("localhost","ben_test","removed") or die("con"); $db = mysql_select_db("ben_test") or die("db"); $sql1 = mysql_query("INSERT INTO comments (messages) VALUES ($comments)") or die("insert"); $mysql_query_one = mysql_query("SELECT * FROM comments"); while($rows=mysql_fetch_array($mysql_query_one)) { echo $rows['messages'] . "[br /]"; Okay, the browser outputted "insert" so it has to be something to do with the insert sql syntax I have added. Not sure if its over-riding the same content added as before or something.
It's dieing when you try to insert, probably because of quotes. As the other Ben mentioned you need to escape the data. Try: $query = "INSERT INTO comments(messages) VALUES ('" . mysql_real_escape_string($_POST['comments']) . "')"; $insert_result = mysql_query($query); if (!$insert_result) { echo "Error with insert: ", mysql_error(), "<br/>\n"; echo "Query I tried to run:<br/>\n", $query, "<br/>\n"; exit; } that way mysql will show you the error that occurred when you tried to run the insert, and also you are escaping the comment you typed in so things like quotes will be handled properly. When you print the data out, you should use htmlspecialchars so if someone enters javascript or any other 'bad' data it won't get printed or executed. For example: $query = "SELECT * FROM comments"; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) { echo "Comment was: ", htmlspecialchars($row['messages'], ENT_QUOTES), "<br/>\n"; } There's some good info available here about this sort of stuff: http://phpsec.org/projects/guide/ If something doesn't make sense, send us another email :) -- Postgresql & php tutorials http://www.designmagick.com/

« previous php.db (#44473) next »