2015-05-02 132 views
1

Screenshot1 Screenshot2如何INSERT INTO JOIN

產品圖片爲數字都包括在內。 我想在product_images中保存[屏幕]照片。 我應該如何保存product_id?

mysql_query("INSERT INTO product_images 
      (image_name = '".$image_name."', 
      created = '".$time."', 
      product_id = '".$id."') 

      (SELECT image_name, created, product_id 
       FROM product_images 
       LEFT JOIN products ON 
         product_images.product_id = products.'".$id."') 
      "); 
+0

**無。 **號碼號碼** 1)'mysql_'接口已棄用,請使用mysqli或PDO接口。 2)將SQL文本生成爲一個變量,因此可以在提交到數據庫之前回顯/ var_dump(用於調試)。 3)對於INSERT語句,SQL語法無效。做這個'INSERT(col1,col2,col3)SELECT ...',不等於列表中的符號或值。 4)代碼似乎很容易受到SQL注入的影響;潛在的不安全值需要被正確地轉義,或者,首選模式是*準備好聲明*和*綁定佔位符*。 5)不允許在INSERT和SELECT中引用相同的表; – spencer7593

+0

使問題變得簡潔 - 應該更容易遵循:-) – kguest

回答

0

暫時忘掉你不應該使用mysql_函數了事實......

你的查詢都是錯誤的:

首先這是一個插入

INSERT INTO product_images 
     (image_name, created, product_id) 
VALUES ('$image_name', '$time', $id) 
語法

其次,您不能通過相同的mysql_query()語句運行2個查詢,因此您需要執行2個單獨的調用並獲取您的選擇查詢語法cor RECT

$sql = "INSERT INTO product_images 
      (image_name, created, product_id) 
     VALUES ('$image_name', '$time', $id)"; 
$result = mysql_query($sql); 

if (! $result) { 
    // the insert failed 
} 

$sql = "SELECT image_name, created, product_id 
     FROM product_images 
      LEFT JOIN products ON 
       product_images.product_id = products.id 
     WHERE 
      products.id = $id"; 
$result = sql_query($sql); 
if (! $result) { 
    // the select failed 
} 

while ($row = mysql_fetch_array($result)) { 
    // process each row returned by the select query 
} 
0

如果(isset($ _ POST)和$ _ SERVER [ 'REQUEST_METHOD'] == 「POST」){

$uploaddir = "public/uploads/"; //a directory inside 
foreach ($_FILES['photos']['name'] as $name => $value) 
{ 

    $filename = stripslashes($_FILES['photos']['name'][$name]); 
    $size=filesize($_FILES['photos']['tmp_name'][$name]); 
    //get the extension of the file in a lower case format 
     $ext = getExtension($filename); 
     $ext = strtolower($ext); 

    if(in_array($ext,$valid_formats)) 
    { 
     if ($size < (MAX_SIZE*1024)) 
     { 
     $image_name=time().$filename; 
     echo "<img src='".$uploaddir.$image_name."' class='imgList'>"; 
     $newname=$uploaddir.$image_name; 

     if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) 
     { 
     $time=time(); 
     $last_ID = mysql_insert_id(); 
     mysql_query("INSERT INTO product_images(image_name,product_id,created) VALUES('$image_name','$session_id','$time')"); 
     } 
     else 
     { 
     echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; 
     } 

     } 
     else 
     { 
     echo '<span class="imgList">You have exceeded the size limit!</span>'; 

     } 

     } 
     else 
    { 
     echo '<span class="imgList">Unknown extension!</span>'; 

    } 

} 

}