使用PHP为SQL数据库准备HTML表单输入(Preparing HTML Form Input for SQL Database using PHP)

我目前正在测试一个通过php发送数据到sql数据库的html表单。 我面临的问题是特殊字符打破形式,不更新数据库。 我没有测试过所有的特殊字符,但主要是`和'是罪魁祸首。 我试过mysql_escape_string,preg_replace和add_slashes没有成功。 我错过了什么?

$description = preg_replace('/[^A-Za-z0-9\ %&$=+*?()!.-]/', ' ', $_POST['description']); $description = preg_replace("/[\n\r]/"," ",$description); // Items Insert foreach ($item as $index=>$value) { $sqlItems .= " INSERT INTO quote_items (quote_id, item, description, amount, gst) VALUES ('$last_id', '$item[$index]', '$description[$index]', '$amount[$index]', '$gst[$index]'); "; }

提前致谢!

I'm currently testing a html form which sends the data through php to the sql database. The problem I'm facing is special characters break the form and don't update the database. I haven't tested all the special characters but mainly ` and ' are the culprits. I've tried mysql_escape_string, preg_replace and add_slashes with no success. What am I missing?

$description = preg_replace('/[^A-Za-z0-9\ %&$=+*?()!.-]/', ' ', $_POST['description']); $description = preg_replace("/[\n\r]/"," ",$description); // Items Insert foreach ($item as $index=>$value) { $sqlItems .= " INSERT INTO quote_items (quote_id, item, description, amount, gst) VALUES ('$last_id', '$item[$index]', '$description[$index]', '$amount[$index]', '$gst[$index]'); "; }

Thanks in advance!

最满意答案

你可以尝试这个(有点肮脏),但它应该允许这2个字符被保存

$sqlItems .= ' INSERT INTO `quote_items` (quote_id, item, description, amount, gst) VALUES ("'.$last_id.'", "'.$item[$index].'", "'.$description[$index].'", "'.$amount[$index].'", "'.$gst[$index].'"); ';

编辑:对不起有报价倒过来

you can try this (a little dirty) but it should allow those 2 characters to be saved

$sqlItems .= ' INSERT INTO `quote_items` (quote_id, item, description, amount, gst) VALUES ("'.$last_id.'", "'.$item[$index].'", "'.$description[$index].'", "'.$amount[$index].'", "'.$gst[$index].'"); ';

EDIT: sorry had the quotes reversed

更多推荐