2011-09-30 49 views
0

我创建了迷你内容管理系统。现在得到了当场打死问题一次向多个MySQL表中插入值

我用下面的函数

function filter($data, $db) 
{ 
    $data = trim(htmlentities(strip_tags($data))); 
    if (get_magic_quotes_gpc()) 
    $data = stripslashes($data); 
    $data = $db->escape_string($data); 
    return $data; 
} 

而且PHP代码过滤帖子看起来像

$name=filter($_POST['name'], $db); 
$title=filter($_POST['title'], $db); 
$parent=filter($_POST['parent'],$db); 
$switch=filter($_POST['switch'], $db); 
    if($switch=''){ 
     echo "Return back and select an option"; 
     die(); 
    } 
$parentcheck=filter($_POST['parentcheck'],$db); 
    if($parentcheck=='0') 
    { 
     $parent=$parentcheck; 
    } 
$purifier = new HTMLPurifier(); 
$content = $db->real_escape_string($purifier->purify($_POST['content'])); 

if(isset($_POST['submit'])&&$_POST['submit']=='Ok'){ 
    $result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$switch'") or die($db->error); 
    $result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('<what?>', '$title', '$content'") or die($db->error);   
    } 

这就是我的表看起来怎么样命名

表“pages” enter image description here

和 “菜单”

enter image description here

我的问题是如下:


  1. 我试图让自动递增id值从menu表后 ('$parent', '$name', '$switch'")插入并将此id in pages表 插入时($ title,$ content)。怎么做?是否可以使用单个 查询?

  2. $content的值是带有HTML标签的文本。我正在使用html净化器。 我可以在插入数据库表之前过滤它的值吗?任何 建议/建议?

+0

你在寻找mysql_insert_id()函数吗? –

回答

1

应该使用real_escape_string是

$result2=$db->query("INSERT INTO pages (id, title, content) VALUES (LAST_INSERT_ID(), '$title', '$content'") or die($db->error); 

过滤()应该是安全的。是否还有其他要过滤的内容?

1

看起来您使用的是mysqli作为数据库库,因此您可以使用$db->insert_id()来检索由该特定DB句柄的插入操作创建的最后一个ID。所以,你的查询会变成:

$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$switch'") or die($db->error); 
$new_id = $db->insert_id(); 
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ($new_id, '$title', '$content'") or die($db->error);   
                    ^^^^^^^ 

你真的不能做一个单一的查询,如MySQL不使其可用于INSERT_ID功能的ID值后直到查询完成。所以你必须在3个步骤中做到这一点:插入,获取ID,再次插入。

数据库过滤规则(更好地称为转义)是转义用户提供的任何东西。这甚至包括您在其他数据库查询中检索并重新插入的数据。转义并不是真正的安全措施 - 它确保无论您将哪些内容放入查询字符串中,都不会导致查询失败。防止SQL注入攻击只是一个副作用。

+0

你读过我的'filter'函数的代码了吗? $ content的值是带有HTML标签的文本。我也想过滤'$ content'。任何关于将html标记插入db的建议? – demonoid

+0

Purifier与将HTML插入数据库无关。净化器只是清理html。您想如何存储数据以及之后将要使用的数据取决于您。但净化器本身不足以使某些任意的html安全地用于数据库使用。他们是两种完全不同的使用情况。比较苹果和长颈鹿。 –

+0

在将html插入数据库表之前,你会建议做什么? – demonoid