将序列化数据转义和插入到 MySQL [英] Escaping and Inserting Serialized Data to MySQL

查看:27
本文介绍了将序列化数据转义和插入到 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以以下数据为例:

$a = addslashes('hello\'s');
$b = serialize($a);

// As you know, $b looks like this s:8:"hello\'s";

现在,当我将 $b 插入 MySQL 时,数据现在看起来像这样 s:8:"hello's" 在 MySQL 中.MySQL 删除了 \,现在我有一个无效的序列化数据.

Now when I insert $b to MySQL, the data now looks like this s:8:"hello's" inside MySQL. MySQL removes the \ and now I have an invalid serialized data.

解决此问题的最佳方法是什么?谢谢

What's the best way to fix this? Thanks

推荐答案

首先序列化你想要的值然后使用mysql_real_escape_string.毕竟,这就是您要放入数据库的字符串.尽量避免加斜杠...

First serialize the value you want and then use the mysql_real_escape_string. That's the string you are going to put in the database after all. Try to avoid addslashes...

如果你当时不想有活动连接,试试这个功能:

If you don't want to have an active connection at the time, try this function:

function mysql_escape_no_conn( $input ) { 

    if( is_array( $input ) ) {
        return array_map( __METHOD__, $input ); 
    }
    if( !empty( $input ) && is_string( $input ) ) { 
        return str_replace( array( '\\', "\0", "\n", "\r", "'", '"', "\x1a" ), 
                            array( '\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z' ),
                            $input ); 
} 

return $input; 

}

这篇关于将序列化数据转义和插入到 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆