无法使用 php 在数据库中插入值
Cannot insert the value in database using 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'))");
}
}
}
}
?>
在您的代码中 $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';
因为我试图通过 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'))");
}
}
}
}
?>
在您的代码中 $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';