2015-11-23 37 views
2

因爲我試圖通過php代碼插入數據庫中的值,但它沒有工作,也沒有給出任何錯誤。這是我試圖執行但沒有成功的代碼。不能在數據庫中插入值使用php

<?php 
$mysqli = new mysqli("localhost", "admin", "password", "project") or die("couldn't connect to the database"); 
error_reporting(0); 
session_start(); 
if (!isset($_SESSION["sess_user"])) { 
    header("location:index.php"); 
} else { 
    $username = $_SESSION['sess_user']; 
    if (isset($_GET['submit'])) { 
     if ($_GET['e1'] == "E-LN3465") { 
      $productname = $mysqli->real_escape_string($_GET['e1']); 
      if ($insert = $db->query("INSERT INTO `cart`(`ID`, `pid`) ((Select `ID` from `users` where `Username`='$username'),(Select `pid` from `product` where `pname`='$productname'))")) { 
       $checkQuery = $mysqli->query("INSERT INTO `cart`(`ID`, `pid`) ((Select `ID` from `users` where `Username`='$username'),(Select `pid` from `product` where `pname`='$productname'))"); 
      } 
     } 
    } 
} 
?> 
+0

執行查詢的兩個時間和'$ db'是沒有在你的代碼只是將其刪除形成你的代碼 – Saty

+1

@Calimero在INSERT SELECT語句中不需要'values' http://dev.mysql.com/doc/refman/5.7/en/insert-select.html – Saty

+0

@Saty你是對的,我的不好,謝謝你的評論。 – Calimero

回答

2

在你的代碼$mysqli變量商店連接對象,你是執行查詢兩次。 $db是沒有在你的代碼只是將其刪除

if ($mysqli->query("INSERT INTO `cart`(`ID`, `pid`) ((Select `ID` from `users` where `Username`='$username'),(Select `pid` from `product` where `pname`='$productname'))")) { 
     echo "INSERT SUCESSFULLY"; 
    } 

修訂

查詢更改爲

INSERT INTO `cart`(`ID`, `pid`) 
SELECT users.ID, product.pid 
    FROM users, product 
    WHERE users.Username='$username' 
    AND product.pname='$productname';