从一个表中获取值并放入另一个表中

时间:2015-07-09 16:26:15

标签: php

我需要从一个表中获取一些值并将它们保存到另一个表中。 用户(id,first_name,last_name)和汽车(id,制造商,型号)到第三个表的值。我尝试了一些东西,但我总是得到错误:你的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的''附近使用正确的语法

这是我的代码:

<?php
include "db_connection.php";
session_start();

$res=mysql_query("SELECT * FROM users WHERE id_user=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);

if(isset($_POST["btn"]))
{
    $maker=$_POST["maker"];
    $model=$_POST["model"];
    $year=$_POST["year"];
    $fuel=$_POST["fuel"];
    $power=$_POST["power"];


    $sql2="insert into models values (0,'$maker','$model','$year','$fuel','$power')";
    $query2=mysql_query($sql2);


    $query = ("SELECT id_user, f_name, l_name FROM users WHERE id_user=".$_SESSION['user']); 
    $result = mysql_query($query); 
    if(!$result) { die($query."<br />".mysql_error()); } 

    while($row = mysql_fetch_assoc($result)) 
    { 
         $data[]=$row; 
    } 

     if (!mysql_select_db("car")) { die(mysql_error()); } 

     foreach($data as $row) 
     { 
         $query  = "INSERT INTO evidencija (id_k,ime,prezime,'$maker','$model') VALUES ('"; 
         $query .= mysql_real_escape_string($row['id_user'])."','"; 
         $query .= mysql_real_escape_string($row['f_name'])."','"; 
         $query .= mysql_real_escape_string($row['l_name'])."'"; 

         if(!mysql_query($query)) { die($query."<br />".mysql_error()); } 
      } 
}
include "header.php";
?>

1 个答案:

答案 0 :(得分:0)

请将$ query更改为:

    $query  = "INSERT INTO evidencija (id_k,ime,prezime,maker,model) VALUES ('"; 
     $query .= mysql_real_escape_string($row['id_user'])."','"; 
     $query .= mysql_real_escape_string($row['f_name'])."','"; 
     $query .= mysql_real_escape_string($row['l_name'])."','"; 
     $query .= mysql_real_escape_string($maker)."','"; 
     $query .= mysql_real_escape_string($model)."')";