Mysql同时插入两个表

时间:2014-03-22 14:41:58

标签: php mysql

我需要将内容保存到两个表中。我有这个代码,但它只保存到桌面游戏中。我需要将所有内容保存到游戏中并归档到文章的ID,标题和日期。

任何帮助?

非常感谢

 <?php
include("../includes/connect.php");

if(isset($_POST['submit']))
{
$games_date = date('y-m-d-h');
$games_title = $_POST['title'];
$games_author = $_POST['author'];
$games_keywords = $_POST['keywords'];
$games_link = $_POST['download_link'];
$games_image = $_FILES['image']['name'];
$games_tmp = $_FILES['image']['tmp_name'];
$games_content = $_POST['content'];

if($games_title=="" or $games_author=="" or $games_keywords=="" or $games_content=="" or $games_download_link="")
{
    echo"<script>alert('any field is empty')</script>";
    exit();
}
else 
{
move_uploaded_file($games_tmp,"../uploaded_images/$games_image");
$games_query = "insert into games (games_title,games_date,games_author,games_image,games_keywords,games_link,games_content) values ('$games_title','$games_date','$games_author','$games_image','$games_keywords','$games_link','$games_content')";
$last_id = mysqli_insert_id($connect);
$archive_query = "insert into archive (title, pub_date) values ('$games_title','$games_date',)";
}
   if(mysqli_query($connect,$games_query))
{
    echo "<center><h1>Post published seccesfuly!</h1></center>";
  }
}
?>

2 个答案:

答案 0 :(得分:2)

正如您所说,您需要插入 ID ,我更愿意采用这种方式

....
if(mysqli_query($connect,$games_query)){
    $last_id = mysqli_insert_id($connect);
    $archive_query = "insert into archive (id, title, pub_date) values ('$last_id', '$games_title','$games_date')";
    mysqli_query($connect,$archive_query); // execute the archive query here
    echo "<center><h1>Post published seccesfuly!</h1></center>";
  }
}

答案 1 :(得分:1)

您可以使用mysqli::multi_query

$query  = "insert into games (games_title,games_date,games_author,games_image,games_keywords,games_link,games_content) values ('$games_title','$games_date','$games_author','$games_image','$games_keywords','$games_link','$games_content');";
$query .= "insert into archive (title, pub_date) values ('$games_title','$games_date')";

if (mysqli_multi_query($connect, $query)) {

    echo "Data in two tables successfully inserted.";
}