Getting inserted row on if/-then-else statement - php

When I use an if-then-else to check if a record exists then call the last insert using $pdocon->lastInsertId() it does not return the inserted row. For example:
if exists(
SELECT first_name FROM `my_table`
WHERE first_name = 'adam'
)
then
SELECT * FROM `my_table` WHERE first_name = 'adam'
else
INSERT INTO my_table
(first_name)
values
('adam')
END IF;
This (simplified) code checks to see if a record exists. If it does exist, it grabs the info. If it does not exist it inserts it. That part all works fine, the problem comes in when I try to get the inserted ID from a name the doesn't exist (returns a 0 as lastInsertId).
Is there a practical way around this?

If you want to ensure that names are not duplicated, then you should define a unique index or constraint on the column:
alter table t add unique constraint unq_my_table_first_name unique (first_name);
Then you can use the following trick to get the correct id using last_insert_id():
insert into mytable (first_name)
values ('Adam')
on duplicate key update id = last_insert_id(id);
You can then use:
select last_insert_id()
to get the last insert id regardless of whether the statement was an update or insert.
Here is a db<>fiddle.

First the question should not have PHP tag because PHP doesn't have if-then-else conditional statement that's a Visual Basic conditional statement. Nevertheless an if-else can handle this with you using the right SQL query, SQL already provides a query that solves the issue above i.e. to check for the existence of a record and that should help.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

To anyone looking in the future, another user posted the answer but then deleted it. The correct way to accomplish this is:
if exists(
SELECT first_name FROM `my_table`
WHERE first_name = 'adam'
)
then
SELECT * FROM `my_table` WHERE first_name = 'adam'
else
INSERT INTO my_table
(first_name)
values
('adam');
SELECT LAST_INSERT_ID() as inserted;
END IF;

Related

I want to send multiple value pairs via API and insert them into SQL DB [duplicate]

I have two tables and my goal is to move specific data from the first table into the second table along with a reason for why that data was moved. For instance:
raw_data_table
SELECT * FROM raw_data_table where id IS NULL;
I would want to move this into the second table, which is identical to the first table except for an extra column reason. I tried:
INSERT INTO bad_data_table
(SELECT * FROM raw_data_table WHERE id IS NULL), "The ID is NULL";
But this returns a syntax error. How can I copy the entire row over and add the reason value?
INSERT INTO bad_data_table
SELECT *, 'The ID is NULL' AS Reason
FROM raw_data_table
WHERE id IS NULL;
Try this query:
INSERT INTO bad_data_table VALUES (
(SELECT * FROM raw_data_table WHERE id IS NULL LIMIT 1), "The ID is NULL");
The subquery here needs to have 1 row!

Duplicate records in MySQL. EXISTS check for the same data not working properly?

SELECT EXISTS
(SELECT * FROM table WHERE deleted_at IS NULL and the_date = '$the_date' AND company_name = '$company_name' AND purchase_country = '$p_country' AND lot = '$lot_no') AS numofrecords")
What is wrong with this mysql query?
It is still allowing duplicates inserts (1 out of 1000 records). Around 100 users making entries, so the traffic is not that big, I assume. I do not have access to the database metrics, so I can not be sure.
The EXISTS condition is use in a WHERE clause. In your case, the first select doesn't specify the table and the condition.
One example:
SELECT *
FROM customers
WHERE EXISTS (SELECT *
FROM order_details
WHERE customers.customer_id = order_details.customer_id);
Try to put your statement like this, and if it returns the data duplicated, just use a DISTINCT. (SELECT DISCTINCT * .....)
Another approach for you :
INSERT INTO your_table VALUES (SELECT * FROM table GROUP BY your_column_want_to_dupplicate);
The answer from #Nick gave the clues to solve the issue. Separated EXIST check and INSERT was not the best way. Two users were actually able to do INSERT, if one got 0. A single statement query with INSERT ... ON DUPLICATE KEY UPDATE... was the way to go.

php Mysqli - i want to change id number of some rows to end id

my table has an id field with auto_increment and I want some rows to move to end of the table (changing number id to end number).
Like This:
$query= mysqli_query($con,"UPDATE moshakhasat SET id=<?end table?> WHERE username='$username' ");
sorry about this code. I don't know a lot about PHP
I am tired and really need your help
Thank you.
I'm not sur if you can change that as mysql is handling the auto increment.
But maybe you could insert new row with your data and then delete the old row.
you could use the INSERT... SELECT syntax
INSERT INTO tbl1 (field1, field2, ...)
SELECT tbl1.field1, tbl1.field2
FROM tbl1 WHERE id IN (1,2,3,4);
then
DELETE FROM tbl1 WHERE id IN (1,2,3,4)

Insert distinct records in the table while updating the remaining columns

This is actually a form to update the team members who work for a specific client, When i deselect a member then it's status turns to 0.
I have a table with all unique records. table consists of four columns -
first column is `id` which is unique and auto_incremented.
second column is `client_id`.
third column is `member_id`. (these second and third columns together make the primary key.)
fourth column is `current` which shows the status (default is 1.).
Now i have a form which sends the values of client_id and member_id. But this forms also contains the values that are already in the table BUT NOT ALL.
I need a query which
(i) `INSERT` the values that are not already in the table,
(ii) `UPDATE` the `current` column to value `0` which are in the table but not in the form values.
here is a screenshot of my form.
If (select count(*) from yourtable where client_id = and member_id = ) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
First of all check if the value exists in the table or not, by using a SELECT query.
Then check if the result haven't save value so it will be inserted, else show an error .
This would be a great time to create a database stored procedure that flows something like...
select user
if exists update row
else insert new row
stored procedures don't improve transaction times, but they are a great addition to any piece of software.
If this doesn't solve your problem then a database trigger might help out.
Doing a little research on this matter might open up some great ideas!
Add below logic in your SP
If (select count(*) from yourtable where client_id = <value> and member_id = <value>) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
if you want simple solution then follow this:
*) use select with each entry in selected team.
if select returns a row
then use update sql
else
use insert sql.
In your case member_id & client_id together makes the primary key.
So , you can use sql ON DUPLICATE KEY UPDATE Syntax.
Example:
$sql="INSERT INTO table_name SET
client_id='".$clientId."',
member_id='".$member_id."',
current='".$current."'
ON DUPLICATE KEY
UPDATE
current = '".$current."'
";
In this case when member_id & client_id combination repeats , it will automatically executes update query for that particular row.

Get current auto_increment value

I am doing mysql insert for my table using php.
Autoincrement column name is "link_id"
and "alias" colum is used to make SEO friendly url.
During my insert, I would like to attach link_id value at the end of my alias column.
So I need to know what is the being inserted link_id value.
I do not want to do another query.
mysql_insert_id() does not work, since its using previous query, and not current query.
Thanks
You should use SHOW TABLE STATUS:
$query = mysql_query("SHOW TABLE STATUS LIKE tablename");
$row = mysql_fetch_array($query);
$next_id = $row["Auto_increment"];
It will give you the current status of auto_increment column.
EDITED:
In one query you can do it like this:
INSERT INTO table_schema.table_name(column_name)
VALUES (("SELECT AUTO_INCREMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'table_schema'
AND TABLE_NAME = 'table_name'"))
It will give you the new auto_increment value in the column column_name.
Have you considered a trigger in MySQL? Something like:
DELIMITER //
CREATE TRIGGER `add_alias_id` AFTER INSERT ON `someTable`
FOR EACH ROW BEGIN
UPDATE
`someTable`
SET
`alias` = CONCAT(`alias`,NEW.`link_id`)
WHERE
`link_id` = NEW.`link_id`;
END;
//
DELIMITER ;
EDIT: I was recently working for a company whose flagship software used to assume that max(id) + 1 = next id. The problem is concurrency; it's rare, but two people can get the same id, causing all sorts of chaos. Be extremely careful trying to predict the value.
I handle this type of scenario on the SELECT end.
For Example:
insert into tablename(aliasroot) values('index.php?link_id=');
This would give you for example
In my select I would do 'select concat(aliasroot,link_id) as alias from tablename'
you could use mysql_insert_id() ++, though that won't always be reliable.
what would be better would be to insert the query, then append the current id using CONCAT()

Categories