Insert into MYSQL Database if not exists - php

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.
}
?>

Related

Duplicate entry for key 'PRIMARY' in mysql code

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

PHP/MYSQL Selecting a MAX value and using it as an inserted value

I have a small database project using HTML forms and PHP code. It is working perfectly except the last part. Basically, I have my database connection setup and working in my PHP, and upon hitting the Add button it should insert values from the form to the database. My instructor said that due to table constraints it has to be inserted in a certain order, basically address table first and then staff table. IF I comment out the staff part of code, my successful confirmation page appears and the address appears in the database every time with an auto incremented address_id. The issue is that I'm supposed to query for a MAX(Address_id) and use that for inserting the staff part, as it uses address_id as a foreign key. When I do that, I get a foreign key constraint error on update cascade. If I completely pull out the INSERT staff code, and put a 'debug' to print the MAX(address_id), it prints correctly. I just can't get it to insert to the staff table correctly so that everything from my form creates a staff record. Here is the code:
$userQuery = "INSERT INTO address (address, district, city_id, postal_code, phone)
VALUES ('$address', '$district', '$city', '$postal_code', '$phone') ";
$addressResult = mysqli_query($connect, $userQuery);
if (!$addressResult)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
$maxQuery = "SELECT MAX(address_id) FROM address";
$result = mysqli_query($connect, $maxQuery);
$row = mysqli_fetch_assoc($result);
if (!$result)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
/**else
{
print ("<p>Average hourly wage:".$row['MAX(address_id)']."</p>");
}**/
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id)
VALUES ('$first_name', '$last_name', '$row', '$email', '$store_id')";
$staffResult = mysqli_query($connect, $userQuery1);
if (!$staffResult)
{
die("Could not successfully run query ($userQuery1) from $db: " .
mysqli_error($connect) );
}
else
{
print(" <h1>New Staff Record Added!</h1>");
print ("<p>The following record was added:</p>");
print("<table border='0'>
<tr><td>First Name</td><td>$first_name</td></tr>
<tr><td>Last Name</td><td>$last_name</td></tr>
<tr><td>Email</td><td>$email</td></tr>
<tr><td>Store ID</td><td>$store_id</td></tr>
<tr><td>Address</td><td>$address</td></tr>
<tr><td>City</td><td>$city</td></tr>
<tr><td>District</td><td>$district</td></tr>
<tr><td>Postal Code</td><td>$postal_code</td></tr>
<tr><td>Phone</td><td>$phone</td></tr>
</table>");
}
You are not calling the correct associative index. You are just calling the array:
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id) VALUES ('$first_name', '$last_name', '{$row['MAX(address_id)']}', '$email', '$store_id')";

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 (?,?,?,?,?,?,?,?,?,?,?,?,?)

MySQL autoincrement value jumps by 2, when I add a transcaction im my php code

I have a table with patients info and another one for their telephone numbers.
The relationship between them, is 1:N (1 to many). I put one restriction: I want all patients have at least one telephone number. So, I put a transaction in my code like this.
// Beggining of transaction
mysqli_query($dbc,'begin');
$sql1 = " INSERT INTO `dental_clinic`.`patient` (`idpatient` ,`surname` ,`name` ,`middle_name` ,`address` , `town`, `birth_date` , `occupation` , `email` ,`p_comments`) VALUES (NULL , '$surname', '$name', '$middle_name', '$address', '$town', '$birth_date', '$occupation', '$email', '$other');
";
$execute_sql1 = mysqli_query($dbc, $sql1);
$last_id = mysqli_insert_id($dbc);
// Put some variables to the insert queries of telephone.
$sql2_1 = " INSERT INTO `dental_clinic`.`telephone`(`patient_idpatient`, `phone`) VALUES ('$last_id', '$phone') ";
$sql2_2 = "INSERT INTO `dental_clinic`.`telephone`(`patient_idpatient`, `phone`) VALUES ('$last_id', '$phone2')";
$sql2_3 = "INSERT INTO `dental_clinic`.`telephone`(`patient_idpatient`, `phone`) VALUES ('$last_id', '$phone3')";
// Checking the first field of telephone
if (!empty($phone)){
$execute_sql2_1 = mysqli_query($dbc, $sql2_1);
} else {
$execute_sql2_1 = false;
}
// Checking the second field of telephone
if (!empty($phone2)){
$execute_sql2_2 = mysqli_query($dbc, $sql2_2);
} else {
$execute_sql2_2 = true;
}
// Checking the third field of telephone
if (!empty($phone3)){
$execute_sql2_3 = mysqli_query($dbc, $sql2_3);
} else {
$execute_sql2_3 = true;
}
// Checking the insert commands to execute toggether
if ($execute_sql1 && $execute_sql2_1){
if ($execute_sql2_1 && $execute_sql2_2){
if ($execute_sql2_1 && $execute_sql2_3){
mysqli_query($dbc, 'commit');
echo 'The patient personal details inserted succesfully!';
echo 'The primary telephone inserted succesfully! ';
header("Location: new_medical_history.php");
} else {
mysqli_query($dbc, 'rollback');
echo 'Error, on 3rd phone! ';
}
} else {
mysqli_query($dbc, 'rollback');
echo 'Error, on 2nd phone! ';
}
} else {
mysqli_query($dbc, 'rollback');
echo 'Error, on patient personal details or on primary telephone! ';
}
// Ending connection
mysqli_close($dbc);
Both tables, patient and telephone are in the same form.
When I add succesfully a new patient, the autocrement idpatient value, jumps by two (1,3,5,7 and so on.) But when I comment out the transaction,
// mysqli_query($dbc,'begin);
// mysqli_query($dbc, 'commit');
// mysqli_query($dbc, 'rollback');
then the autoincrement value goes normal by one (7,8,9,10, .. etc.).
Could you please tell why this happening? Is it something wrong in my code? I want to keep the transaction, so noone of patients will be added without the primary telephone number.
I find your logic hard to follow, so I have rewritten your code using a try-catch, I believe it satisfies the same requirements and is easier to follow. Does this still cause a jump-by-2?
// fixme: consider using prepared statements to avoid sql injection attacks
mysqli_query($dbc,'begin');
try {
if(!mysqli_query($dbc, "INSERT INTO `dental_clinic`.`patient` (`idpatient` ,`surname` ,`name` ,`middle_name` ,`address` , `town`, `birth_date` , `occupation` , `email` ,`p_comments`) VALUES (NULL, '$surname', '$name', '$middle_name', '$address', '$town', '$birth_date', '$occupation', '$email', '$other')")) throw new Exception('Error, on patient personal details!');
$last_id = mysqli_insert_id($dbc);
if(empty($phone)) throw new Exception('Error, primary phone required!');
if(!empty($phone) && !mysqli_query($dbc, "INSERT INTO `dental_clinic`.`telephone`(`patient_idpatient`, `phone`) VALUES ('$last_id', '$phone')")) throw new Exception('Error, on primary telephone!');
if(!empty($phone2) && !mysqli_query($dbc, "INSERT INTO `dental_clinic`.`telephone`(`patient_idpatient`, `phone`) VALUES ('$last_id', '$phone2')")) throw new Exception('Error, on 2nd phone!');
if(!empty($phone3) && !mysqli_query($dbc, "INSERT INTO `dental_clinic`.`telephone`(`patient_idpatient`, `phone`) VALUES ('$last_id', '$phone3')")) throw new Exception('Error, on 3rd phone!');
mysqli_query($dbc, 'commit');
// these will not be seen if you immediately redirect
//echo 'The patient personal details inserted succesfully!';
//echo 'The primary telephone inserted succesfully! ';
header("Location: new_medical_history.php");
} catch(Exception $e) {
mysqli_query($dbc, 'rollback');
echo $e->getMessage();
}
// Ending connection
mysqli_close($dbc);

PHP, Error 1136 : Column count doesn't match value count at row 1 [duplicate]

This question already has answers here:
PHP, MySQL error: Column count doesn't match value count at row 1
(3 answers)
Closed 9 years ago.
I get this Exception:
Error 1136 : Column count doesn't match value count at row 1
Structure of the table :
create table gb_entries (
id int(4) not null auto_increment,
username varchar(40) not null,
name varchar(40),
gender varchar(40),
dob int(40),
email varchar(40),
primary key (id)
);
With this PHP code:
// Add a new entry to the database
function addEntry($username, $name, $gender, $dob, $email) {
$connection = mysql_open();
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
$result = # mysql_query ($insert, $connection)
or showerror();
mysql_close($connection)
or showerror();
}
// Return an array of database entries that contain $name anad $email
function getEntries($username,$name,$gender,$dob,$email) {
// Sanitise user input to prevent SQL injection attacks
$username = mysql_escape_string($username);
$name = mysql_escape_string($name);
$gender = mysql_escape_string($gender);
$dob = mysql_escape_string($dob);
$email = mysql_escape_string($email);
// Open connection and select database
$connection = mysql_open();
// Construct query
$query =
"select username, name, gender, dob, email from gb_entries where 0=0 ";
if (! empty($username)) {
$query .= "AND username LIKE '%$username%' ";
}
if (! empty($name)) {
$query .= "AND name LIKE '%$name%' ";
}
if (! empty($gender)) {
$query .= "AND gender LIKE '%$gender%' ";
}
if (! empty($dob)) {
$query .= "AND dob LIKE '%$dob%' ";
}
if (! empty($email)) {
$query .= "AND email LIKE '%$email%' ";
}
$query .= "ORDER BY id";
// echo $query;
// Execute query
$result = # mysql_query($query, $connection)
or showerror();
// Transform the result set to an array (for Smarty)
$entries = array();
while ($row = mysql_fetch_array($result)) {
$entries[] = $row;
}
mysql_close($connection)
or showerror();
return $entries;
}
What does the Exception mean?
As it says, the column count doesn't match the value count. You're providing five values on a six column table. Since you're not providing a value for id, as it's auto increment, it errors out - you need to specify the specific columns you're inserting into:
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')"
Also, I really hate that WHERE 0=0 line. I know why you're doing it that way, but I personally find it cleaner to do something like this (warning: air code!):
$query = "select username, name, gender, dob, email from gb_entries ";
$where = array();
if (! empty($username)) {
$where[] = "username LIKE '%$username%'"; // add each condition to an array
// repeat for other conditions
// create WHERE clause by combining where clauses,
// adding ' AND ' between conditions,
// and append this to the query if there are any conditions
if (count($where) > 0) {
$query .= "WHERE " . implode($where, " AND ");
}
This is personal preference, as the query optimizer would surely strip out the 0=0 on it's own and so it wouldn't have a performance impact, but I just like my SQL to have as few hacks as possible.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the id column -- for which you didn't specify a value.
Basically, instead of this :
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
Use something like that :
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
I had a similar problem. The column count was correct. the problem was that i was trying to save a String (the value had quotes around it) in an INT field. So your problem is probably coming from the single quotes you have around the '$dob'. I know, the mysql error generated doesn't make sense..
funny thing, I had the same problem again.. and found my own answer here (quite embarrassingly)
It's an UNEXPECTED Data problem (sounds like better error msg to me). I really think, that error message should be looked at again
Does modifying this line help?
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";

Categories