Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

php - Inserting values into multiple MySQL tables at once

I've created mini content management system. Now got afew questions

I'm filtering posts with following function

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;
}

And the PHP code looks like that

$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);           
    }

And that's how my tables look like

Table named "pages" enter image description here

And "menu"

enter image description here

My questions are followings:


  1. I'm trying to get autoincremented id value from menu table after ('$parent', '$name', '$switch'") insertion and set this id in pages table while inserting ($title, $content). How to do it? Is it possible with single query?

  2. $content's value is the text with HTML tags. I'm using html purifier. May I filter it's value too before inserting into db table? Any suggestion/advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Should be

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

Filtering using real_escape_string( ) should be safe. Is there something else that you want to filter?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...