如何在mysql数据库中插入php代码段

如何在mysql数据库中插入php代码段

问题描述:

我有一个如下的php代码段:

function is_ancestor_of( $page_name = null, $post ) {

if(is_null($page_name))
return false;

// does it have a parent?
if (!isset( $post->post_parent ) OR $post->post_parent <= 0 )
return false;

//Get parent page
$parent = wp_get_single_post($post->post_parent);

 if ( $parent->post_name == $page_name ){
echo $parent->post_name.' - '.$page_name;
return true;
} else {
is_ancestor_of( $page_name, $parent );
}
}

我只想将整个代码插入mysql数据库表中,然后再次在页面上以相同的格式重新检索它.当我仅使用INSERT INTO查询将此代码插入数据库时​​,由于代码因特殊字符而中断了sql查询,因此会发生mysql语法错误.有什么办法吗?

I just want to insert this whole code in mysql database table and again retriew it with this same formatting on the page again. When I simply insert this code in database using INSERT INTO query then the mysql syntax error occurs because the code breaks sql query because of special characters. Is there any way to do this??

谢谢.

是的,您可以这样做.多种方式:

Yeah, you can do this. Multiple ways:

  1. PDO-实际上,这是最佳选择.在PHP手册中研究此主题,因为它不仅可以保护PHP中的MySQL查询不受破坏,还可以提供更多帮助.
  2. addslashes()-添加斜杠以转义字符.这肯定不会破坏您的MySQL查询.
  3. mysql_real_escape_string()
  4. mysql_escape_string()

已编辑 与该答案的先前版本相比,强调了PDO,因为PDO比其他选项安全得多,并且在使用PHP和MySQL时可以使用更多的功能.

EDITED Emphasized PDO as compared to the previous version of this answer as PDO is far more safer than the other options and there is a lot more to it which can be used while working with PHP and MySQL.