MySQL 表中的斜线,但使用 PDO 和参数化查询.这是怎么回事?

时间:2023-05-07
本文介绍了MySQL 表中的斜线,但使用 PDO 和参数化查询.这是怎么回事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

好的,所以我更新数据库表的代码具有以下不同的风格:

Alright, so my code to update my database tables is varying flavours of the following:

$query = "
  insert into Comment 
    (Comment, CommentDate, Rating, UserRid) 
  values 
    (:comment, now(), 0, :userrid )" ;

try {           
  $db_conn = new PDO('mysql:host='.$db_server.';dbname='.$db_name, $db_username, $db_password );

  $db_conn->beginTransaction();
  $prep = $db_conn->prepare($query);
  $prep->bindParam(':comment', $comment, PDO::PARAM_STR, 500);
  $prep->bindParam(':userrid', $userrid, PDO::PARAM_INT, 20);
  $prep->execute();

  $db_conn->commit();
} catch (PDOException $e)  {
  $db_conn.rollBack();
  echo "Error!: " . $e->getMessage() . "<br/>";
  die();
}

在上面,评论来自另一个页面的帖子.正在通过函数调用正确设置用户 ID.一切正常,除了斜线被添加到表格中.

In the above, comment comes in via Post from another page. Userrid is being set properly via a function call. Everything works properly, except the slashes get added to the table.

我读过的所有内容都说,为了在有人输入撇号时避免使用斜杠,我应该使用参数化查询.如果我没记错的话,我很确定这就是我正在做的.我错过了什么吗?有人可以让我知道我做错了什么吗?

Everything I've read says that in order to get around having slashes whenever someone types in an apostrophe that I should be using parameterized queries. If I'm not mistaken, I'm pretty sure that's what I'm doing. Am I missing something? Can anybody let me know what I'm not doing right?

提前致谢,迈克尔

推荐答案

可能你已经magic_quotes_gpc() 开启,你需要做这样的事情:

Probably ou've magic_quotes_gpc() turned on, you need to do something like this:

if (get_magic_quotes_gpc() == true)
{
    $comment = stripslashes($comment);
    $userrid = stripslashes($userrid);
}

如果您使用的是 PHP 5.3+,您可以通过将以下代码行放在文件顶部来摆脱所有魔术引用的变量:

If you're using PHP 5.3+ you can get rid of all magic quoted variables by placing the following lines of code on the top of your file:

if (get_magic_quotes_gpc() === 1)
{
    $_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
    $_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
    $_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
    $_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}

如果您运行的是较低版本的 PHP,您应该采取看看这个页面.

If you're running a lower version of PHP you should take a look at this page.

这篇关于MySQL 表中的斜线,但使用 PDO 和参数化查询.这是怎么回事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:PDO 和嵌套获取 下一篇:使用数组键和值创建 sql select 语句

相关文章