Simple ON DUPLICATE KEY UPDATE? - php

I'm trying to store a one-to-many relationship in my mySQL database and I want to avoid duplicate entries if at all possible.
I read on the internet and saw that 'ON DUPLICATE KEY UPDATE' is an option. Would this work for my situation?
CODE:
function insert_options($uid, $array) {
if(!is_array($array)) {
return false;
}
$db = db_connect();
foreach($array as $a) {
$sql = 'INSERT INTO newsletter_coupon_codes_options (uid, option_name, value) VALUES (?, ?, ?)';
$stmt = $db->prepare($sql);
if($stmt === false) {
echo "Prepare failed: (" . $db->errno . ") " . $db->error;
}
$stmt->bind_param('iss', $uid, $a, $value);
$value = '1';
$stmt->execute();
}
}
TABLE
UID(INT11), OPTION_NAME(varchar(255)), VALUE(INT(11))
I tried to add ON DUPLICATE KEY UPDATE value = 1 to the $sql statement, but it didn't seem to do anything. Basically I want to make sure when I'm inserting the data if the uid and option_name exist, it just sets the value to 1 and doesn't make a new entry.
I do not have a unique key set up, only a primary key on uid. I wasn't sure what to make unique. I can't make the uid unique, as there will be multiple entries per uid. I also cannot make the option_name unique as there will be the same option_name for multiple uid's
What is the best way to accomplish this?

Change your query to
INSERT INTO newsletter_coupon_codes_options (uid, option_name, value)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE value = VALUES(value)
Here is SQLFiddle demo
And make sure that you have a UNIQIE or PRIMARY KEY constraint on (uid, option_name), e.g.
ALTER TABLE newsletter_coupon_codes_options
ADD UNIQUE (uid, option_name);

Please change your query like this and use mysqli_query function execute this kindof queries and use mysqli_real_escape_string function to avoid SQL injections
$sql = 'INSERT INTO newsletter_coupon_codes_options
(uid, option_name, value) VALUES ("'.$uid.'", "'.$option_name.'", "'.$value.'")
ON DUPLICATE KEY UPDATE value = "'.$value.'"';

Related

Mysql MAX ID+1 incriment with insert query

Please help in manually incrementing id filed with insert query and PDO
(note: No primary key set in table)
if ($valid) {
$max="SELECT MAX(id)+1 from class";
$sql = "INSERT INTO class (id,Class,Notes) values(?,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($max,$Class, $Notes));
header("Location: class_create.php");
}
This insert not incrementing id, Please help
INSERT INTO class (id, Class, Notes)
SELECT MAX(id)+1, ?, ?
FROM class
and
$q->execute(array($Class, $Notes));
Be ready to duplicated values due to parallel execution interference.

Multiple MySqli insert using same ID [duplicate]

I have the following code. The mysqli_insert_id() (in this case "$last_row"), which is supposed to return the last row of the table, is always returning 0. Why is it so?
<?php
include 'connect-db.php';
$last_row = mysqli_insert_id($connection);
if ($content != '') {
$sql = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}
echo $last_row;
mysqli_close($connection);
}
mysqli_insert_id does not return the ID of the last row of the table. From the docs, it:
...returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
(My emphasis)
That is, if you were to run it immediately after an insert that auto-generated an ID, on the same connection you did the insert with, it would return the ID generated for that insert.
This is illustrated by the example in the docs linked above:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
To get the result, you should place the
$last_row = mysqli_insert_id($connection);
after your INSERT query
Maybe you tried INSERT IGNORE INTO and you have a UNIQUE value that was already inserted. In that case, this id is zero.
Also, you'll get "zero" if MySQL runs out of connections.
As you probably know PHP “mysql” extension supported persistent
connections but they were disabled in new “mysqli” extension
--Peter Zaitsev
Another gotcha with this function -- if you're doing:
INSERT INTO table (col1, col2) VALUES (1, 2) ON DUPLICATE KEY UPDATE col2=3
and insert doesn't happen because of a duplicate key and for the UPDATE, like in my case, if col2 was already set to 3, then mysqli_insert_id will also return 0.

conditional insert column values

i am having a problem with inserting records to my tables as i want to insert values into specific columns if only the value is not null, my query goes like this
i have tried:
INSERT INTO users(id,name,phone,address) VALUES($userId,$userName,$userPhone,$userAddress);
but it gives me error if on client side one of the parameters is not sent not all the time the client side send all the parameters (id,name,phone,address) i want to have some kind of condition instead of the handle all combinations to the query to go over this problem
You should be using prepared queries, but your immediate problem is that you aren't quoting anything:
$query = "INSERT INTO users(id,name,phone,address) VALUES('$userId', '$userName', '$userPhone', '$userAddress')";
Now, assuming you're doing this properly using a PDO connection, this is how you should be doing it to protect your database:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$query = "INSERT INTO users (id, name, phone, address) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$result = $stmt->execute(array($userId,$userName,$userPhone,$userAddress));
if ($result) {
//success
} else {
//failure
}
Put ' inside VALUES () like '$userId'.
INSERT INTO users(id,name,phone,address) VALUES('$userId','$userName','$userPhone','$userAddress');
If parameter are not coming, then let it Insert Null in DB Table column. (Allow Null). And, if you don't want to insert NULL in DB Table column, then assign any default value before inserting.

Why is mysqli_insert_id() always returning 0?

I have the following code. The mysqli_insert_id() (in this case "$last_row"), which is supposed to return the last row of the table, is always returning 0. Why is it so?
<?php
include 'connect-db.php';
$last_row = mysqli_insert_id($connection);
if ($content != '') {
$sql = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}
echo $last_row;
mysqli_close($connection);
}
mysqli_insert_id does not return the ID of the last row of the table. From the docs, it:
...returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
(My emphasis)
That is, if you were to run it immediately after an insert that auto-generated an ID, on the same connection you did the insert with, it would return the ID generated for that insert.
This is illustrated by the example in the docs linked above:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
To get the result, you should place the
$last_row = mysqli_insert_id($connection);
after your INSERT query
Maybe you tried INSERT IGNORE INTO and you have a UNIQUE value that was already inserted. In that case, this id is zero.
Also, you'll get "zero" if MySQL runs out of connections.
As you probably know PHP “mysql” extension supported persistent
connections but they were disabled in new “mysqli” extension
--Peter Zaitsev
Another gotcha with this function -- if you're doing:
INSERT INTO table (col1, col2) VALUES (1, 2) ON DUPLICATE KEY UPDATE col2=3
and insert doesn't happen because of a duplicate key and for the UPDATE, like in my case, if col2 was already set to 3, then mysqli_insert_id will also return 0.

Where is the error in my sql code

$fname = addslashes($fname);
$lname = addslashes($lname);
$dob = addslashes($dob);
$email = $_POST['email'];
$sql =
"INSERT INTO subscriber
(fname, lname, dob)
VALUES
('".$fname."', '".$lname."', '".$dob."')
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");
I am getting error in sql query "insertion error". Query is inserting data into DB after removing WHERE statement. What is the error.
You can't use where in an insert statement. You might be thinking of an update instead?
$sql = "update subscriber set fname='".$fname."', lname = '".$lname."', dob = '".$dob."' WHERE email='".$email."'";
If your email is a unique value, you can also combine an insert with an update like this:
insert into
subscriber (fname, lname, dob, email)
values ('".$fname."', '".$lname."', '".$dob."', '".$email."')
on duplicate key update set fname='".$fname."', lname='".$lname."', dob='".$dob."'
This second syntax will insert a row if there isn't one with a matching email (again, this has to be set to a unique constraint on the table) and if there is one there already, it will update the data to the values you passed it.
Basically INSERT statement cannot have where. The only time INSERT statement can have where is when using INSERT INTO...SELECT is used.
The only syntax for select statement are
INSERT INTO TableName VALUES (val1, val2, ..., colN)
and
INSERT INTO TableName (col1, col2) VALUES (val1, val2)
The other one is the
INSERT INTO tableName (col1, col2)
SELECT col1, col2
FROM tableX
WHERE ....
basically what it does is all the records that were selected will be inserted on another table (can be the same table also).
One more thing, Use PDO or MYSQLI
Example of using PDO extension:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
?>
this will allow you to insert records with single quotes.
Oops !!!! You cannot use a WHERE clause with INSERT statement ..
If you are targeting a particular row then please use UPDATE
$sql = "Update subscriber set fname = '".$fname."' , lname = '".$lname."' , dob = '".$dob."'
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");

Categories