douke3335 2014-01-06 20:55
浏览 22
已采纳

如何使用pdo php在数据库中存储带有命名空间的序列化对象

When i try to store serialized object with namespace i cant do that beacuse i got error unterminated quoted string at or near "'O:22:"protect\classes\Router". Code:

$router = new protect\classes\Router();
$tmp = serialize($router);

$dsn = 'pgsql:dbname=system;host=127.0.0.1';
$user = 'postgres';
$password = 'mypassword';
$pdo = new PDO($dsn, $user, $password, $options);
$pdo->exec('SET search_path = temporary');
$pdo->query("SELECT replace_value('protect\classes\Router','$tmp','serialized_classes')");  // this is my function it`s work fine

If i use php function addslashes before query executed for exampe

  $tmp = addslashes(serialize($router));

the query is successful executed. Unfortunately serialized object with additional slashes is disorder.

I will grateful for help with this topic.

  • 写回答

2条回答 默认 最新

  • douxu2081 2014-01-07 00:22
    关注

    There are several things wrong here, but the biggest is that you aren't using query parameters.

    Don't use addslashes. If you find yourself using that, you should think "oops, I need to go fix the query so I use parameters instead".

    In this case, you should be writing something like:

    $sth = $pdo->prepare('SELECT replace_value(?, ?, ?)');
    $sth->execute(array('protect\classes\Router', $tmp, 'serialized_classes'));
    

    You haven't mentioned what the data type of the argument you pass the serialized data to is. The above will only work if it is text or varchar or similar.

    If it's bytea like it should be for serialized object data, you must tell PHP that the parameter is a binary field:

    $sth = $pdo->prepare('SELECT replace_value(:router, :serialbytes, :mode)');
    $sth->bindParam(':router', 'protect\classes\Router');
    $sth->bindParam(':mode', 'serialized_classes');
    $sth->bindParam(':serialbytes', $tmp, PDO::PARAM_LOB);
    $sth->execute();
    

    Note the use of PDO::PARAM_LOB to tlel PDO that $tmp contains binary data to be passed to PostgreSQL as bytea.

    (It's fine to put constants like 'protect\classes\Router' directly into your queries, btw, so long as you split them out into params if they ever become variables. I mostly separated them because I find it more readable in a query like this.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题