简体   繁体   English

删除所有不需要的字符

[英]Strip Out All Unwanted Characters

I am using the following code to strip out unwanted characters but it is not stripping out everything and throwing a MySQL error: 我正在使用以下代码来去除不需要的字符,但并没有去除所有内容并引发MySQL错误:

    $commentmessage = strip_tags($commentmessage);
    $commentmessage = htmlentities($commentmessage, ENT_QUOTES);

What code would I use to strip out anything that might cause a MySQL error? 我将使用什么代码清除可能导致MySQL错误的内容?

The message I am receiving is: 我收到的消息是:

Error message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; 错误消息:SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法中有错误;请参见表11。 check the manual that corresponds to your MySQL server version for the right syntax to use near 'omg thats the one". One of the logo's we really liked was 1049859 where the f' at line 2** 请查看与您的MySQL服务器版本相对应的手册以获取正确的语法,以在“ omg thats the one”附近使用。我们真正喜欢的徽标之一是1049859,其中第2行的f是**

Evidently you're building your query like so: 显然,您正在像这样构建查询:

$query = "INSERT INTO foo VALUES ('$bar')";

which is breaking because the text of $bar contains single quotes. 因为$bar的文本包含单引号,所以这很麻烦。 '

No. *hits you with a rolled-up newspaper* Bad developer. 否。 *用卷起的报纸打你* 坏的开发商。

I could just throw you a string escaping function, or I could show you to do it right like: 可以向您抛出一个字符串转义函数,或者可以向您展示如何正确执行该操作:

$bar = "I am a problematic string!'; DROP TABLE USERS -- "
$query = "INSERT INTO foo VALUES (?)";
$stmt = $dbh->prepare($query);
$stmt->execute(array($bar));

Or: 要么:

$bar = "I am a problematic string!'; DROP TABLE USERS -- "
$query = "INSERT INTO foo VALUES (:bar)";
$stmt = $dbh->prepare($query);
$stmt->execute(array('bar'=>$bar));

When you prepare a query like this PHP/PDO/MySQL get together and pre-agree on what types your placeholders are. 当您准备这样的查询时,PHP / PDO / MySQL会聚在一起并就您的占位符类型预先达成一致。 So your strings are treated like strings without the need for escaping characters. 因此,您的字符串被视为字符串,而无需转义字符。 This both prevents rogue single quotes from breaking your query, and help protect you from SQL injection attacks. 这不仅可以防止流氓单引号破坏查询,还可以保护您免受SQL注入攻击。

You can also re-use prepared statements to increase performance: [relative to un-prepared statements since the SQL only needs to be parsed once, rather than once per query] 您还可以重新使用已准备好的语句以提高性能:[相对于未准备好的语句,因为SQL只需要解析一次,而不是每个查询一次]

$query = "INSERT INTO foo VALUES (?)";
$stmt = $dbh->prepare($query);
foreach( $bars as $bar ) {
  $stmt->execute(array($bar));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM