简体   繁体   中英

Mysql insert into two tables at same time

I need to save content into two tables. I have this code, but it save just into table games. I need save into the games all content and into archive just id, title and date of article.

Any help?

Thanks very much

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

As you have mentioned that you need to insert the id , I'd prefer to go with this way

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

You could use 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.";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM