Duplicate entry for key 'PRIMARY' in mysql code - php

I keep getting this error, whenever I want to insert something into the database
I have looked around stack, but the answers are so complicated.
the error is :
Order Error:
Duplicate entry '936791155' for key 'PRIMARY'
$orderID = rand();
$orderQuery = "INSERT INTO Orders (OrderID, PersonID, ProductID, Quantity, Price,
OrderDate)
VALUES(".$orderID.",".$customerID.",".$productID.",".$selectedQuantity.",".$totalPrice.",'".$today."'";
if(mysqli_query($conn, $sqlQuery))
{
echo "Order has been Successfull!";
} else {
echo "Order Error: ".$sql. "<br>" . mysqli_error($conn);
}
HERE IS MY SET UP CODE FOR MYSQL:
CREATE TABLE IF NOT EXISTS Orders (
OrderID int(11) AUTO_INCREMENT, -- Connects to table 'Customer' and ID
PersonID int(11) NOT NULL, -- Connects to table 'Orders' and OrderUserID
ProductID int(11) NOT NULL,
Quantity int(11) NOT NULL,
Price int(11) NOT NULL,
OrderDate DATETIME,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Customers(PersonID),
FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
);
EDIT . I think its a problem with $customerID
$customerID = rand();
$sqlQuery = "INSERT INTO Customers (PersonID, FirstName, Address, Phone)
VALUES (".$customerID.",'".$userName."','".$address."','".$phone."')";
if(mysqli_query($conn, $sqlQuery)) {
echo "Member verified, in database";
} else{
echo "Member Error: " . $sql . "<br>" . mysqli_error($conn);
}

OrderID is an auto increment column, you don't have to set its value in the insert statement, use this instert instead:
$orderQuery = "INSERT INTO Orders (PersonID, ProductID, Quantity, Price,
OrderDate)
VALUES(".$customerID.",".$productID.",".$selectedQuantity.",".$totalPrice.",'".$today."')";
Just get rid of the ".$orderID.", from the insert.
I also recommend you to use sql parameters to pass the values to the query, and don't use string concatenation.

I know there is an answer for this but just let me show you how to use prepared statements this makes your SQL much secure.
$stmt = $conn -> prepare("INSERT INTO Orders (PersonID, ProductID, Quantity, Price, OrderDate) VALUES (?,?,?,?,?)");
$stmt -> bind_param("iiiss", $customerID, $productID, $selectedQuantity, $totalPrice, $today);
if($stmt -> execute()){
echo "Order has been Successfull!";
}else {
echo "Order Error: ".$sql. "<br>" . mysqli_error($conn);
}

Related

How to insert data into table with foreign key using html form and php?

Situation: user is logged in and wants to save their favorite color through html form. But in phpMyAdmin I can see that the foreign key and the primary key (which are columns 'user_id' in two separate tables) do not match. The foreign key shows NULL in the rows with data, while the primary key shows numbers (e.g. 3) in the rows with data.
As mentioned, there are 2 tables: (users & colors)
The following sql is used to create table colors:
CREATE TABLE colors (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
favorite_color TEXT NOT NULL,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
The following sql is used to create table users:
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
From the page where users insert data is welcome.php and it contains the following code:
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login");
exit;
}
?>
The html form:
<form action="welcome.php" method="post">
<label>My favorite color:
<input type="text" name="favorite_color">
</label>
<input type="submit" value="Save">
</form>
And the php code to insert data:
<?php
$link = mysqli_connect("localhost", "root", "", "my_db");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO colors (id, favorite_color, user_id) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "sss", $id, $favorite_color, $user_id);
$id = $_REQUEST['id'];
$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_REQUEST['user_id'];
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>
What am I doing wrong? Any suggestion is welcome. Thanks.
I have been able to solve the problem.
Here's what I did:
I changed:
$sql = "INSERT INTO colors (id, favorite_color, user_id) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "sss", $id, $favorite_color, $user_id);
into:
$sql = "INSERT INTO colors (favorite_color, user_id) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "si", $favorite_color, $user_id);
As you can see I removed 'id' and changed "sss" into "si".
And I changed:
$id = $_REQUEST['id'];
$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_REQUEST['user_id'];
into:
$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_SESSION['user_id'];
I removed 'id' entirely and I replaced REQUEST with SESSION for the column 'user_id'.
It is now showing matching numbers under 'user_id' in table colors.

How to get values from stores and insert into products table?

I am new to statements, so please come slowly on me. I have checked questions asked by others but didnt see a solution to solve my issue.
I am trying to create a userpage with prepared statements so they can add products to their stores.
I would like to get store_id from stores and insert into produtcs on an insert product form.
I have tried several methods but they didnt work.
Here are my attempts:
Connection
$mysqli = new mysqli(host, dbase, username, password);
First method prepare statements: I have tried this method without bind_result too.
if ($stmt = $mysqli->prepare("INSERT INTO products (user_id, cat_id, store_id, item_name, item_code, item_description, item_qtty, item_price, item_seo_url, item_image, item_date) SELECT store_id FROM stores WHERE user_id = ?")) {
$stmt->bind_param("i", $user_id);
$user_id = filterString($_SESSION['id']);
$stmt->execute();
$stmt->bind_result($store_id);
if($stmt->fetch()){
echo " Records created successfully. Redirect to landing page";
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
$stmt->close();
Second method sql prepare statements: I have tried this too but didnt work:
$sql = "INSERT INTO products (user_id, cat_id, store_id, item_name, item_code, item_description, item_qtty, item_price, item_seo_url, item_image, item_date) SELECT ?, store_id FROM stores WHERE user_id = ?";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param("iiisiisiisss", $user_id, $cat_id, $store_id, $item_name, $item_code, $item_description, $item_qtty, $item_price, $item_seo_url, $item_image, $item_date);
$user_id = $_SESSION['id'];
$cat_id = $cat_id;
$store_id = $store_id;
$item_name = $item_name;
$item_code = $item_code;
$item_description = $item_description;
$item_qtty = $item_qtty;
$item_price = $item_price;
$store_seo_url = seo_url($item_name);
$item_image = $vtyol;
$item_date = $date;
if($stmt->execute()){
echo " Records created successfully. Redirect to landing page";
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
$stmt->close();
Didnt have a chance to get store_id from stores, I echo store ID in page to see if I get it, its empty.
how can I make it work ?
Do I need to declare all values in bind_param in first method ? (I tried and didnt work).
if so, how to add clause $stmt->bind_param("i", $user_id);.
I really dont know what else to try, need your advice and helps.
Gtg to hospital now be back in 1 hour, will answer your questions and answers.
Thank you all
Last example I tried with the code from #Michael Eugene Yuen it keep saying something went wrong, because of cant get $store_id from stores table.
My codes were to long so I shortened them and tried getting same result.
Here is last example not wroking:
$sql = "INSERT INTO products (
user_id, store_id, name, salary
)
SELECT ?, ?, ?, ?,
`store_id` FROM stores WHERE user_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("iisii", $user_id, $store_id, $name, $salary, $user_id);
$user_id = $user_id;
$store_id = $store_id;
$name = $name;
$salary = $salary;
if($stmt->execute()){
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
$stmt->close();
Database struckter for both tables:
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(100) NOT NULL,
`store_id` varchar(100) NOT NULL,
`name` varchar(255) NOT NULL,
`salary` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `stores` (
`store_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(100) NOT NULL,
`name` varchar(255) NOT NULL,
`salary` int(10) NOT NULL,
PRIMARY KEY (`store_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
INSERT INTO `stores` (`store_id`, `user_id`, `name`, `salary`) VALUES
(1, '12', 'aaaaaaaaaaad', 12),
(2, '12', 'sada', 1234656);
Your were trying to insert data into 11 columns but only 1 value was passed into your statements
Your statement should look like this:
$sql = "INSERT INTO products (
user_id, cat_id, item_name, item_code, item_description,
item_qtty, item_price, item_seo_url, item_image, item_date,
store_id
)
SELECT ?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
`store_id` FROM stores WHERE user_id = ?";
$stmt = $mysqli->prepare($sql);
Bind your $user_id twice. The first one is for your first placeholder and the last one is for your sub-select statement (bind_param)
$stmt->bind_param("iisisiisssi", $user_id, $cat_id, $item_name, $item_code, $item_description, $item_qtty, $item_price, $item_seo_url, $item_image, $item_date, $user_id);
$user_id = $_SESSION['id'];
$cat_id = $cat_id;
$item_name = $item_name;
$item_code = $item_code;
$item_description = $item_description;
$item_qtty = $item_qtty;
$item_price = $item_price;
$store_seo_url = seo_url($item_name);
$item_image = $vtyol;
$item_date = $date;
if($stmt->execute()){
echo " Records created successfully. Redirect to landing page";
$stmt->close();
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
And based on your newly added Example 2, the number of columns, placeholders mismatch the number of bind_param again. Also, when you look at your stores table, you have two records under the same user_id. So which store_id you expect to insert to your store table?
I have used LIMIT 1 for now but certainly this is not the correct approach.
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT ?, ?, ?, `store_id` FROM stores WHERE user_id = ? LIMIT 1";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("isii", $user_id, $name, $salary, $user_id);
$user_id = 12;
$name = 'john';
$salary = 1200;
if($stmt->execute()){
header("location: index.php");
exit();
} else {
echo "Something went wrong. Please try again later.";
}
$stmt->close();
This is an sql statement with hardcoded values:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT 12, 'john', 1200,
`store_id` FROM stores WHERE user_id = 12 LIMIT 1";
This is same statement with variables:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT $user_id, $name, $salary,
`store_id` FROM stores WHERE user_id = $user_id LIMIT 1";
This is same statement with placeholders:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT ?, ?, ?,
`store_id` FROM stores WHERE user_id = ? LIMIT 1";
$stmt->bind_param("isii", $user_id, $name, $salary, $user_id);
$user_id = 12;
$name = 'john';
$salary = 1200;

Insert into MYSQL Database if not exists

I'm trying to add a customer to the MySQL database I created.
Whenever somebody orders an item on the online store, the customer is added to the database (I dont want duplicates). Here is my php code:
$sqlInsert = "INSERT INTO Customers (FirstName, Address, Phone)
VALUES (".$userName.",".$address.",".$phone.")";
if(mysqli_query($conn, $sqlInsert)) {
echo "new member registered successfully!";
} else {
echo "Error: " . $sqlInsert . "<br>" . $mysqli_error($conn);
}
I have looked into queries such as INSERT INTO... WHERE NOT EXISTS. But I don't understand the syntax for my case, and don't know if it would work.
here is my MYSQL customer table code:
CREATE TABLE IF NOT EXISTS Customers (
PersonID INT(11) NOT NULL AUTO_INCREMENT,
Email VARCHAR(100),
FirstName VARCHAR(100) NOT NULL,
LastName VARCHAR(100),
City VARCHAR(90),
Zip INT(10),
CustomerState VARCHAR(50),
Address VARCHAR(200),
Country VARCHAR(20),
Phone VARCHAR(50) NOT NULL,
PRIMARY KEY (PersonID)
);
INSERT INTO Customers (FirstName, Address, Phone)
SELECT * FROM (SELECT '$firstName', '$address', '$phone') AS tmp
WHERE NOT EXISTS (
SELECT FirstName from Customers WHERE FirstName= '$firstName'
) LIMIT 1;
This will prevent based on the first name, you may use all these columns for checking, I assume the matching column should be email, you can use that.
I just added the parameters within the query for you to get an idea, use parameter binding to avoid sql injection.
OR
select * from customers where .... //
Get the size of result set and if size > 0 that means there is a row already, so do not insert it.
Sql statement taken from MySQL: Insert record if not exists in table and modified.
Try select query before insert and check the rows...Try to use Mysqli Prepared statement. I do this code for your way...
<?php
$sqlselect = "SELECT * FROM Customers WHERE FirstName = ".$userName." AND Address = ".$address." AND Phone = ".$phone;
$exqry = mysqli_query($conn, $sqlselect);
$cnt = count($exqry);
if($cnt == 0){
$sqlInsert = "INSERT INTO Customers (FirstName, Address, Phone)
VALUES (".$userName.",".$address.",".$phone.")";
if(mysqli_query($conn, $sqlInsert)) {
echo "new member registered successfully!";
} else {
echo "Error: " . $sqlInsert . "<br>" . $mysqli_error($conn);
}
}else{
echo "Member already in table.";
//do your update or other stuff.
}
?>

Define UNIQUE key constraint for the table

I have implemented this code to insert and update the data in my database but when I try it a new row's data is always being inserted in the table and it is not being updated How can I define the unique key in my case to get it to work? I have the primary key id.
<?php
$json = '{"latitude":53.86898451,"longitude":10.66561387,"route":4}';
$data = json_decode ( $json );
$route = "route_" . $data->{'route'};
$latitude = $data->{'latitude'};
$longitude = $data->{'longitude'};
require 'connection.php';
// check whether route's table exist.
$results = $con->query ( "SHOW TABLES LIKE'" . $route . "'" ) or die ( mysqli_error () );
if (($results->num_rows) == 1) {
//"UPDATE MyGuests SET lastname='Doe' WHERE id=2"
$sql = "INSERT INTO ".$route."(latitude, longitude, created_at)
VALUES( ? , ? , NOW() )
ON DUPLICATE KEY
UPDATE latitude = VALUES(latitude)
, longitude = VALUES(longitude)";
$stmt = $con->prepare($sql) or die ( $con->error );
$stmt->bind_param("ss",$latitude,$longitude);
$stmt->execute();
$stmt->close();
echo "Table exist";
} else {
$create = "CREATE TABLE " . $route . "
(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY UNIQUE,
latitude FLOAT(10,6) NOT NULL,
longitude FLOAT(10,6) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" ;
$stmt = $con->prepare($create) or die ( $con->error );
$stmt->execute();
$stmt->close();
echo "table was craeted";
}
UPDATE
This is what I'm trying now
$sql = "INSERT INTO ".$route."(id, latitude, longitude, created_at)
VALUES( id, ? , ? , NOW() )
ON DUPLICATE KEY
UPDATE latitude = VALUES(latitude)
, longitude = VALUES(longitude)";
Which variable should I add in the VALUES braces for id?
You are not specifying a value for id in your INSERT INTO statement, so there will never be a duplicate key.
Instead, it is auto-generating the next available ID.
To solve this, specify the value of the pre-existing ID (if any).

issues with mysqli prepare

I have issues with $mysqli->prepare with the following code:
if (!($stmt = $mysqli->prepare("INSERT INTO `Orders` (OrderID,IP.Email.File,Cat,Price,Discount,Size,Scaleby,Emailed,Downloaded,Payment,DateTime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
Current code:
if (!($stmt = $mysqli->prepare("INSERT INTO `Orders` (OrderID,IP,Email,File,Cat,Price,Discount,Size,Scaleby,Emailed,Downloaded,Payment,DateTime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
Error message:
Prepare failed: (1136) Column count doesn't match value count at row 1
code used to make table:
if ($mysqli->query('CREATE TABLE IF NOT EXISTS `Orders` (
ID BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
OrderID CHAR(40),
IP CHAR(40),
Email VARCHAR(254),
File VARCHAR(30),
Cat VARCHAR(30),
Price DEC(5,2),
Discount DEC(3,2),
Size VARCHAR(30),
Scaleby DEC(3,2),
Emailed BOOL,
Downloaded BOOL,
Payment VARCHAR(30),
DateTime DATETIME)') === False){
printf("Error: %s\n", $mysqli->error);
}
I have tried removing (...) from INSERT INTO... in an attempt to fix the error but that did not work. I also tried simplifying it to 3 ? marks but it still did not work.
The ? marks are placeholders in a prepared statement
The problem isn't the number of columns in the table, it's that there's a typo in the insert statement. You've got "IP.Email.File" instead of "IP,Email,File", so the DB engine thinks you have a different number of columns than literals specified in the insert statement.
INSERT INTO `Orders`
-- 11 columns here, because "IP.Email.File" parses as one column
(OrderID,IP.Email.File,Cat,Price,Discount,Size,Scaleby,Emailed,Downloaded,Payment,DateTime)
-- 13 values here
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)

Categories