multiple rows update or insert mysql - php

I've created a table like this,
id | option_name | value | user_id
----------------------------------------------
1 | name | Joe | 1
----------------------------------------------
2 | age | 30 | 1
----------------------------------------------
3 | sex | male | 1
----------------------------------------------
4 | name | Jane | 2
----------------------------------------------
5 | age | 28 | 2
----------------------------------------------
6 | sex | female | 2
----------------------------------------------
I want to update all rows corresponding of user_id and option_name.
If user_id == 3, when i submit form with option_name (name,sex,age) as fields, if there is no rows with user_id == 3 then insert rows but if rows exist i want to update those row with new values for value field.
Please check my code: http://pastebin.com/THQdYpix
I want to reduce query steps in my code, any idea?

First check if it updates or note if the mysql_query() returns false then you can use insert query and execute the query.

Use INSERT ... ON DUPLICATE KEY UPDATE.If you want to do this in a single statement, I would recommend using the INSERT ... ON DUPLICATE KEY UPDATE syntax, as follows:
INSERT INTO table (id, someothervalue) VALUES (1, 'hi mom') ON DUPLICATE KEY UPDATE someothervalue = 'hi mom';
The initial INSERT statement will execute if there is no existing record with the specified key value (either primary key or unique). If a record already exists, the following UPDATE statement (someothervalue = 3) is executed.

Below query will work.
REPLACE INTO `table1`
( `name`,`sex`,`age` )
VALUES
( 'Mark', '29', 'male' )
ON DUPLICATE KEY UPDATE user_id=3;

Related

Rewrite of counter by partition

I use mysql and php with phpmyadmin. I have major problem with a partition based counter that I wan't to improve but my knowledge on sql prevents me from doing that. Im struggling very much with this.
I want the duplicated data in my table to have a counter that adds a number after a value if this value gets a duplicated value and then restarts from 1 until a new value is met and so on. Here is what the final result should look like
---------------------------
1 | Josh-1
---------------------------
2 | Josh-2
--------------------------
3 | Josh-3
--------------------------
4 | Josh-4
--------------------------
5 | Fred-1
--------------------------
6 | Fred-2
--------------------------
7 | Fred-3
-------------------------
I had gotten help with this counter here before but it's not working as I wan't it to. Also when I have pressed the insert button in my form the table looks like this in phpmyadmin after I reload it
---------------------------
1 | Josh-1-1-1
---------------------------
2 | Josh-2
--------------------------
3 | Josh-3
--------------------------
4 | Josh-4
--------------------------
5 | Fred-1
--------------------------
6 | Fred-2
--------------------------
7 | Fred
-------------------------
Whats going on here? The code that I seek help with rewriting is this
UPDATE usermeta u1,
(SELECT
u1.`id`, CONCAT(u1.`name`,'-',ROW_NUMBER() OVER(PARTITION BY u1.`name` ORDER BY u1.`id`)) newname
FROM
usermeta u1 JOIN (SELECT `name` , COUNT(*) FROM usermeta GROUP BY `name` HAVING COUNT(*) > 1) u2
ON u1.`name` = u2.`name` ) u3
SET u1.`name` = u3.`newname`
WHERE u1.`id` = u3.`id`
Could this code be rewritten so it creates a table of numbered names and duplicates that looks like the first table example and work like it should in phpmyadmin ? All help is very much appreciated. Keep in mind that I am a struggling moderate sql user.
Possible solution - BEFORE INSERT trigger and additional MyISAM table with secondary autoincrement:
Working table
CREATE TABLE user (id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(127));
Additional table
CREATE TABLE user_index (id INT AUTO_INCREMENT,
name VARCHAR(127),
PRIMARY KEY (name, id)) ENGINE=MyISAM;
Trigger
CREATE TRIGGER insert_user_index
BEFORE INSERT ON user
FOR EACH ROW
BEGIN
DECLARE new_index INT;
INSERT INTO user_index (name) VALUES (NEW.name);
SET new_index = LAST_INSERT_ID();
DELETE FROM user_index WHERE name = NEW.name AND id < new_index;
SET NEW.name = CONCAT_WS('-', NEW.name, new_index);
END
Insert rows - the AI index is added to the name. Check the result.
INSERT INTO user (name) VALUES
('Josh'),
('Josh'),
('Fred'),
('Josh'),
('Fred'),
('Fred'),
('Josh');
SELECT * FROM user;
id | name
-: | :-----
1 | Josh-1
2 | Josh-2
3 | Fred-1
4 | Josh-3
5 | Fred-2
6 | Fred-3
7 | Josh-4
Look what is stored in additional table now.
SELECT * FROM user_index;
id | name
-: | :---
3 | Fred
4 | Josh
db<>fiddle here
If your working table user exists already, and it contains some data, then you'd create additional table and fill it with data using, for example,
CREATE TABLE user_index (id INT AUTO_INCREMENT,
name VARCHAR(127),
PRIMARY KEY (name, id)) ENGINE=MyISAM
SELECT MAX(SUBSTRING_INDEX(name, '-', -1) + 0) id,
SUBSTRING_INDEX(name, '-', 1) name
FROM user
GROUP BY 2;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=38f028cfe1c9e85188ab0454463dcd78

Submit form to fill up the last recent ID row [MySQL] [duplicate]

This question already has an answer here:
MySQL Set AutoIncrement "Ad Hoc"
(1 answer)
Closed 3 years ago.
Lets say I have this table:
------------------
ID | Car |
------------------
25 | Honda |
.. | ... |
.. | ... |
.. | ... |
123 | Toyota |
------------------
How to start fill in at row 124 instead of filling up row 1 til row 24 first? Assuming the ID is auto-incremental value.
Actual problem: my form method post fill up row with ID = 1 instead of ID = 124
If you want preserve the id from 1 to 123 for reserved use and start insert new value for 124, you could set the initial value for AUTO_INCREMENT
ALTER TABLE your_table AUTO_INCREMENT=123;
or directly in your create table
CREATE TABLE your_table () AUTO_INCREMENT = 123;
then if you insert a value with a null value for id, the auto increment should be 124
insert into your_table (car) values ('my_124 car');

Insert Several Similar Rows with One Query in MySQL

Consider a table with 2 fields:
tbl(Id int primary key,Name varchar(100))
Assume that this table contains one row with Id=3 and some unknown Name.
Id | Name
---------------
3 | *****
I have an array of Ids, for example: array(4,6,7,10)
How to put these Ids with the Name of row with Id=3 into this table with one query, So that the resulted table would be:
Id | Name
---------------
3 | *****
----------------
4 | *****
----------------
6 | *****
----------------
7 | *****
----------------
10 | *****
I can not use the Name's value in the query.
I am thinking of a query like this:
insert into tbl(Id,Name) select (4,6,7,10),Name from tbl
You need 2 queries, 1st get the name and 2nd do the insert with multi row insert
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

How to find last inserted varchar value in a table using MySQL query

I have a table student, table structure is follow
student_id | name | class|
-------------------------
2-12-2013 | test | 3 |
-------------------------
2-13-2013 |test2 | 5 |
-------------------------
in this table i want add new record, its student_id become 2-14-2013. For that i want to get the last inserted student_id. how can i get it by MySQL query. Am alredy use mysql_insert_id() But its not working, How to solve this issue?
Define Your student table like below:-
student_id | add_date | name | class|
--------------------------------------
1 | 2013-12-2 | test | 3 |
--------------------------------------
2 | 2013-13-2 |test2 | 5 |
--------------------------------------
student_id would be int auto increamented primary key
then execute Query like below to get last inserted id:-
select student_id from student order by student_id desc limit 1;
Hi You has to set primary key to your table as integer auto-increment then you can use this last inserted id
$con = mysql_connect("localhost", "root", "", "chirag2");
$sql = "INSERT INTO test_student ( student_id,name,class)values('3-12-2013','test1','3' )";
$res = mysql_query($con, $sql);
echo mysql_insert_id($con);
die;
Note: you need to truncate table before alter it and set new primary key to it so take backup before this

Sql – Insert value in first empty cell of column and show ID

I have an sql statement that will insert a value to the first empty cell. And if I ran the php script again, then it inserts into the next null cell etc.
Problem: I also want to find out the ID of that row, and value of another column in that row. In the Mysql table below, I want a value inserted in the first ‘null’ of COLUMN A, and also know the id and value in COLUMN B corresponding to that (ie id=3 and COLUMN B= 11).
My_TABLE
+---------+--------------+-------------+
| ID | COLUMN A | COLUMN B |
+---------+--------------+-------------+
| 1 | 6 | 78 |
| 2 | 7 | 90 |
| 3 | NULL | 11 |
| 4 | NULL | 5 |
| 5 | NULL | 123 |
+---------+--------------+-------------+
The following sql statement in PHP script will make it possible to insert value to the first empty cell in COLUMN A:
UPDATE My_TABLE
SET COLUMN A = 83
WHERE COLUMN A IS NULL
LIMIT 1;
Result will be:
+----+----------+------------+
| ID | COLUMN A | COLUMN B |
+----+----------+------------+
| 1 | 6 | 78 |
| 2 | 7 | 90 |
| 3 | 83 | 11 |
| 4 | NULL | 5 |
| 5 | NULL | 123 |
+----+----------+------------+
I also want to have an sql script that will print within PHP (echo) the values of ID and COLUMN B values corresponding to the first COLUMN A null value (ie ID= 3; COLUMN B= 11).
fetch the row by condition in this case you will have ID and COLUMN B
select *
from My_TABLE
where COLUMN A IS NULL
order by id
limit 1
Update by ID the selected row:
update My_TABLE
set COLUMN A = :SOME_VALUE
where ID = :ID_FROM_FETCH
Not sure if this case will fit what you are questioning.
mysqli_insert_id
From this function I'm pretty sure you will able to write the script for what you need.
Note* If it fits what you need, please read the warning as I'm not
sure if it will deprecated from the latest PHP version. Kindly take
note.

Categories