mysql: store a DEFAULT value as a variable - php

I am wondering how to store the value of a primary key, auto-incremented by "DEFAULT" so that I can insert it as a value in another table row.
So far I have:
$sql = "INSERT INTO sales (
sale_id,
sale_amt,
sale_date)
VALUES (
DEFAULT, # <--- how to store the resulting value of this?
'$amt',
'$date'
)";
I need the specific value created by "DEFAULT" to be stored, so that I can insert it into another table's row. How do I do this with either PHP or MySQL?

You don't. You use last_insert_id() to retrieve it AFTER you've performed the first insert.
INSERT INTO foo (bar) VALUES (baz)
SELECT #id := last_insert_id();
INSERT INTO other (id, parent) VALUES (null, #id)
INSERT INTO yetanother (id, parent) VALUES (null, #id)
Note that last_insert_id() is not smart and will return the id of the LAST insert you did. If you do two inserts, and then try to get the ids, you'll get the id of the second (last) insert.

MySQL:
You can find this in MySQL by using the LAST_INSERT_ID() function, as the last insert ID will be returned that you inserted for an AUTO_INCREMENT value.
$sql = "INSERT INTO sales (
sale_id,
sale_amt,
sale_date)
VALUES (
DEFAULT, # <--- how to store the resulting value of this?
'$amt',
'$date'
)";
sql2 = "INSERT INTO records (
sale_id,
customer_name,
other_info)
VALUES (
LAST_INSERT_ID(), <-------- correct sales_id
'$name',
'$info');

Related

How to replace some values if a user already exists?

I don't know how to replace some data if a "user" already exists.
I've tried ON DUPLICATE KEY UPDATE but I came to realize that this will probably not work. Because the only value that isn't updated is 'user' in my code but the other 3 values are constantly updated every 5 minutes.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES ('$Name'), world = VALUES ('$World'), status = VALUES ('$status')
The idea is if, for example, user "bob" already exists update his other 3 values bot, world, status, instead of creating a new line and so on.
Edit: this is how I have it setup in Mysql
The argument to VALUES() should be the name of a column, not a string. You put the name of the column that you would have inserted into.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES (bot), world = VALUES (world), status = VALUES (status)

MYSQL - append or insert value into a column depending on whether it's empty or not

As title says, im trying to append a string to a VARCHAR column in my table.
The string is something like " //string ", forward slashes will be used later to explode the string to an array in PHP.
I was wondering if there's a way in MYSQL to perform a CONCAT(columnname, "//string") if the column is empty, otherwise perform a normal UPDATE ... SET ... WHERE . In this way, i will avoid the first value of my future exploded string to be a "//string" with forward slahes.
also, above I 've used bold characters for "in MYSQL" because I know i could first query the DB (to check if the column is empty) with something like:
$q = $conn->dbh->prepare('SELECT columnname FROM tablename WHERE username=:user');
$q->bindParam(':user', $username);
$q->execute();
$check = $q->fetchColumn();
and then leave PHP decide which operation perform:
if ($check != '') { // PERFORM A CONCAT }
else { // PERFORM AN UPDATE }
but this would mean a waste of time/resources due to 2x database calls and more PHP code.
thanks.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
That means in your case:
INSERT INTO tablename (id,columnname) VALUES (1,'//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
http://sqlfiddle.com/#!9/bd0f4/1
UPDATE Just to show you your options:
http://sqlfiddle.com/#!9/8e61c/1
INSERT INTO tablename (id, columnname) VALUES (1, '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES (1, '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE columnname='blahblah'), '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE id=2), '//string')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//string');
INSERT INTO tablename (id, columnname) VALUES ((SELECT id FROM tablename t WHERE columnname='newone'), '//newone')
ON DUPLICATE KEY UPDATE columnname=CONCAT(columnname,'//newone');
If what you want is this:
first string: column will contain 'firststring'
second string: column will contain 'firststring//secondstring'
then do the update like this:
UPDATE tablename SET columnname = CONCAT( IF(IFNULL(columnname,'')='','',CONCAT(columnname,'//')), :string) WHERE username=:user

PHP Assosiative array Insert into if data doesnt exist in table

I have an assosiative array in PHP which is inserting data into a table
foreach($array as $key => $value){
$query = "INSERT INTO live_list (file_id, date) SELECT ('$key', '$value') FROM dual WHERE NOT EXISTS (SELECT * FROM live_list WHERE file_id = '$key')";
mysqli_query($link, $query) or die('Query failed: ' . mysqli_error($link));
}
However as I have moved from an indexed array to an assosiative array, I can't figure out how to insert this data ONLY if the data in my array does not exist in my table.
Query failed: Operand should contain 1 column(s)
Now I am recieving this error
Any help will be great!
Why the use of a sub-query?
Assuming file_id is a unique field (i.e. no duplicates in the whole table), make it a unique index on the table if it isn't already:
ALTER TABLE live_list
ADD UNIQUE (file_id)
and change your query to
INSERT INTO live_list (file_id, date)
VALUES ('$key', '$value')
ON DUPLICATE KEY UPDATE date = date;
This means that it will simple "update" the value of date to what it already is if it encounters a duplicate key.
Although you should look to bind your parameters to protect against sql injection.
You could do this:
INSERT INTO live_list (file_id, date)
SELECT '$key', '$value'
FROM dual
WHERE NOT EXISTS (SELECT * FROM live_list WHERE file_id = '$key')
DUAL is a dummy table. The logic is that if the sub query does not exist, the dummy table returns one row with the desiered input.

Insert multiple rows with same unique ID

I am inserting multiple rows using one query and, obviously, the ID column auto increments each row. I want to create another ID column and have the ID remain the same for all rows inserted during the query. So if I insert 10 rows during one query, I want all 10 rows to have the id "1". How can this be done? Thanks for any help
If I understood your question correctly, you want to supply an ID for the specific group of INSERT statements.
Assumming you have this schema
CREATE TABLE TableName
(
RecordID INT AUTO_INCREMENT PRIMARY KEY,
OtherColumn VARCHAR(25) NOT NULL,
GroupID INT NOT NULL
)
You can have two statements for this:
1.) Getting the last GroupID and increment it by 1.
SELECT COALESCE(MAX(GroupID), 0) + 1 AS newGroupID FROM TableName
2.) once you have executed it, store the value in a variable. Use this variable for all the insert statement,
$groupID = row['newGroupID'];
$insert1 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('a', $groupID)";
$insert2 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('b', $groupID)";
$insert3 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('c', $groupID)";
UPDATE 1
SQLFiddle Demo

mysql transaction - mixing insert & select to attain last_insert_id?

I'm performing a transaction (using PDO), however I need to grab the insert id of the first element in the transaction, for example:
BEGIN
INSERT INTO user (field1,field2) values (value1,value2)
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
COMMIT;
Then do the pdo stuff:
[...]
$pdo->execute();
$foo = $pdo->lastInsertId(); // This needs to be the id from the FIRST insert
Is there a way to get the last insert id from the first element in a transaction? Perhaps using something like the following:
BEGIN
INSERT INTO user (field1,field2) values (value1,value2)
SELECT id AS user_id FROM user WHERE id=LAST_INSERT_ID()
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
COMMIT;
$pdo->execute();
$fooArray = $pdo->fetchAll();
$lastId = $fooArray[0]['user_id'];
Am I completely out to lunch with ^ ? Is there a better way to do this?
EDIT 1
Based on suggestion, i've updated the query to use variables... however, i don't know how to retrieve the variable values using PDO. Using $stmt->fetchAll() just returns an empty array;
BEGIN
DECLARE User_ID int
DECLARE Option_ID int
INSERT INTO user (field1,field2) values (value1,value2);
set User_ID = select LAST_INSERT_ID();
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
set Option_ID = select LAST_INSERT_ID();
select User_ID, Option_ID
COMMIT;
You can do it this way, put the value into variable then just select it
BEGIN
DECLARE User_ID int
DECLARE Option_ID int
INSERT INTO user (field1,field2) values (value1,value2);
set User_ID = select LAST_INSERT_ID();
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
set Option_ID = select LAST_INSERT_ID();
select User_ID, Option_ID
COMMIT;

Categories