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 (?,?,?,?,?,?,?,?,?,?,?,?,?)
Related
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);
}
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.
}
?>
I am attempting to prepare a statement with mysqli
$stmt = $mysqli->prepare("INSERT HIGH_PRIORITY INTO `user` (`FirstName`, `LastName`, `Department`, `Email`) SELECT * FROM (SELECT ?,?,?,?) AS tmp WHERE NOT EXISTS ( SELECT `Email` FROM `user` WHERE `Email` = ? ) LIMIT 1;");
if (!$stmt) {
printf('errno: %d, error: %s', $mysqli->errno, $mysqli->error);
die;
}
$statementReturnCode = $stmt->bind_param("sssss", $ssoFirstName, $ssoLastName, $ssoDepartment, $ssoEmail, $ssoEmail);
if (!$statementReturnCode) {
printf('errno: %d, error: %s', $stmt->errno, $stmt->error);
}
$stmt->execute();
$stmt->close();
When this is run I receive the following error:
errno: 1060, error: Duplicate column name '?'
I've been able to bind in this fashion in the past, but I've never tried to bind the same column twice in a different location in the query (Email).
How can I use the same value for Email in two different locations, or is this a different issue?
To clarify what is being done with this query:
This query will be run frequently. If the user exists already in the user table, no insert should be attempted. If the user does not exist, the user should be added to the user table.
The user table has a UserID field that auto-increments. If an insert is attempted the user will not be added due to a unique constraint, but the AUTO-INCREMENT will add 1 even though the insert did not occur. This WHERE NOT EXISTS query is an attempt to mitigate this issue.
Example use:
INSERT INTO `user` (
`user`.`FirstName`,
`user`.`LastName`,
`user`.`Department`,
`user`.`Email`)
SELECT * FROM (SELECT 'John', 'Doe', 'Marketing', 'John.Doe#mycorp.com') AS tmp
WHERE NOT EXISTS (
SELECT `user`.`Email`
FROM `user`
WHERE `user`.`Email` = 'John.Doe#mycorp.com'
) LIMIT 1;
I have tested this query and it works as I had expected. The issue I'm having is with properly changing this query into a prepared statement with php.
Column names aren't string literals, you don't bind column names
$stmt = $mysqli->prepare(sprint("INSERT HIGH_PRIORITY INTO `user` (`FirstName`, `LastName`, `Department`, `Email`) SELECT * FROM (SELECT '%s', '%s', '%s', '%s') AS tmp WHERE NOT EXISTS ( SELECT `Email` FROM `user` WHERE `Email` = ? ) LIMIT 1;"), $ssoFirstName, $ssoLastName, $ssoDepartment, $ssoEmail);
if (!$stmt) {
printf('errno: %d, error: %s', $mysqli->errno, $mysqli->error);
die;
}
$statementReturnCode = $stmt->bind_param("s", $ssoEmail);
if (!$statementReturnCode) {
printf('errno: %d, error: %s', $stmt->errno, $stmt->error);
}
This cannot be done. Prepared statements using PHP's mysqli extension cannot be used for several things including:
Table names
Columns in select lists
I was attempting to use a dynamic item in a select list which cannot be done.
https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet#Where_prepared_statements_do_not_work
I am trying to check the database tables for data before entering new data and avoiding the dublicates.
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')
SELECT " . $columnData . " FROM " . $columns . "
WHERE NOT EXISTS (SELECT '" .$columnData . "'
FROM " . $table . " WHERE '" . $columnData . "' = '" . $columnData . "')";
The query does not throw any errors, although the query is not executed as expected.
Thanks in advance
to avoid duplicate entrys just use INSERT IGNORE
If you want to update when it's a duplicate use Insert ... ON DUPLICATE KEY UPDATE...
If you want to avoid duplicates, then create a unique constraint or index on the columns you want to be unique:
create unique index idx_table_cols on table(col1, col2, . . .);
Then the database will prevent duplicates. If you want the insert to fail silently instead of generating an error, you can use insert ignore, but I would recommend insert on duplicate key update:
insert into table(col1, col2, . . .)
select <values>
from . . .
on duplicate key update col1 = values(col1);
I am giving you example with all conditions please check it
First step would be to set a unique key on the table:
ALTER TABLE thetable ADD UNIQUE INDEX(pageid, name);
Then you have to decide what you want to do when there's a duplicate. Should you:
ignore it?
INSERT IGNORE INTO thetable (pageid, name) VALUES (1, "foo"), (1, "foo");
Overwrite the previously entered record?
INSERT INTO thetable (pageid, name, somefield)
VALUES (1, "foo", "first")
ON DUPLICATE KEY UPDATE (somefield = 'first')
INSERT INTO thetable (pageid, name, somefield)
VALUES (1, "foo", "second")
ON DUPLICATE KEY UPDATE (somefield = 'second')
Update some counter?
INSERT INTO thetable (pageid, name)
VALUES (1, "foo"), (1, "foo")
ON DUPLICATE KEY UPDATE (pagecount = pagecount + 1)
function db_insert_article($flag,$url,$sentiment,$category,$title,$time,$rt_count,$tweet_count,$img_url)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$insertQuery1 = "INSERT INTO frrole_popular_article (`url`, `sentiment`, `title` , `time` , `img_url` , `rt_count` , `tweet_count`, `today`) VALUES ('".$url."','".$sentiment."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."','".$today."')";
if (!mysqli_query($con,$insertQuery1))
{
//die('Error: ' . mysqli_error($con));
}
}
TAble structure:
Everything looks alright. Then why it does not insert into table? below this I have other queries which inserts into table successfully. IT also does not show any error.
UPdate1 : This query works fine which is just below above code
$insertQuery2 = "INSERT INTO frrole_article_sentiment (`url`, `sentiment`, `category`, `title` , `time` , `img_url` , `rt_count` , `tweet_count`, `today`) VALUES ('".$url."','".$sentiment."','".$category."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."','".$today."')";
if (!mysqli_query($con,$insertQuery2))
{
//die('Error: ' . mysqli_error($con));
}
UPDATE2
$insertQuery1 = "INSERT INTO frrole_popular_article (`url` , `sentiment`, `img_url` , `title` , `rt_count` , `tweet_count`, `time` , `today`) VALUES ('".$url."','".$sentiment."','".$img_url."','".$title."','".$rt_count."','".$tweet_count."','".$time."','".$today."')";
you are trying to insert with:
$insertQuery2 = "INSERT INTO frrole_article_sentiment
(`url`, `sentiment`, `category`,
`title` , `time` , `img_url` ,
`rt_count` , `tweet_count`, `today`)
VALUES ....
but when you make select * from frrole_article_sentiment; it returned you 8 columns and you are trying to insert in 9 columns, in other words in your state insert into.... you are trying to insert into CATEGORY attribute but it doesn't exist in the table