phpmysqlmysqliinsertmysql-insert-id

Cannot insert the value in database using php


As i'm trying to insert the value in database through php code but it didn't work and also it didn't give any error. Here is the code that i'd tried to execute but not succeeded.

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

Solution

  • In your code $mysqli variable store your connection object and you are executing your query two time. $db is nothing in your code just remove it

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

    UPDATED

    Change your query to

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