2014-01-19 58 views
0

我正在與帖子的博客工作。 我想插入3個表試圖插入到兩個表使用PHP和mysqli

帖子,類別和Post_categories(顯示爲一個職位的合適的類別)

我什麼都試過使用的mysqli如:

$titel = $_POST['titel']; 
$post = $_POST['post-text']; 

$sql= 
"INSERT INTO posts (titel, post) 
VALUES ('$titel', '$post') 
INSERT INTO post_categories (idposts) 
VALUES ('". $mysqli->insert_id() ."') 
"; 

if (!mysqli_query($link,$sql)) 
    { 
    die('Error: ' . mysqli_error($link)); 
    } 
echo "1 record added"; 
mysqli_close($link); 

但這沒沒有工作。我現在堅持了兩個小時,我幾乎放棄了這一點。 我真的不知道如何在Mysqli中做到這一點。我知道它是如何在Mysql中起作用的。

希望有人能幫助我解決這個問題。

我的表結構是這樣的:

帖子

idposts
Titel的

添加

分類

idcategor IES
類別

post_categories

ID
idposts
idcategories

+0

在谷歌上搜索「mysql insert into multiple tables」。有幾個像這樣的例子:http://stackoverflow.com/questions/10043887/sql-insert-into-multiple-tables 基本上,如果你不做一個「存儲過程」,它不會成爲可能。您需要插入第一個,然後是第二個等。 – mogosselin

回答

0

既然你插入到多個表中嘗試使用交易也。在執行查詢之前,您也無法獲取mysql_insert_id()。

mysqli_autocommit($link, FALSE); 
$sql = "INSERT INTO posts (titel, post) VALUES ('".$titel."', '".$post."')"; 
if (mysqli_query($link, $sql) === TRUE) { 
    $postId = mysqli_insert_id($link); 
    $sql1 = "INSERT INTO post_categories (idposts) VALUES ('".$postId."')"; 
    mysqli_query($link, $sql1); 
} 
if (!mysqli_commit($link)) { //commit transaction 
    print("Table saving failed"); 
    exit(); 
} 
+0

這工作就像一個魅力!謝謝先生。我對Mysqli相當陌生,因爲我最後一個'大'項目是用舊的低級mysql。 –

0

使用mysqli_query不能執行在同一時間兩個查詢,而不是你應該使用mysqli_multi_query,如果你真的想這樣做所以

+0

這是插入兩個表的最佳方式嗎?我不確定。 –