Insert into mysql specific situation - php

I have a strange situation in mysql, So I have table witch have multiple columns, one of it is specific. This columns is specific INT(10) UNSIGNED NOT NULL.
So If I write in sql :
INSERT INTO infos_game (id_game,specific) VALUES (0, 12) ---- doesn't work
If I write :
INSERT INTO infos_game (id_game,``specific``) VALUES (0, 12)----- it works, so if specific is between `` works fine. What is the problem ? Help me please. Thx in advance.
If is a reserved word, how to insert in database from php, I tried :
$o_infos_game_user_registered = new \Entity\Cluster\InfosGame(array(
'id_game' => $game->id_game,
'specific' => $game->specific,
),
);
$o_infos_game_user_registered->save();
But I get the error

It seems that specific is a reserved word. To use a reserved word you need to use back ticks (``) otherwise the query will fail.
Reading Material
MySQL Keywords https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Hit CTRL + F then type specific and it will highlight it.

Executing queries with reserved words can be done in 3 different ways
1) Rename columns into non reserved word
ALTER TABLE "table_name" RENAME COLUMN "column 1" TO "column 2";
2) Use back ticks in queries (``)
INSERT INTO infos_game (`id_game`,`specific`) VALUES (0,12)
3. Use inserts without specifying columns (when u insert data which contains all columns )
//old query
INSERT INTO infos_game (id_game,specific) VALUES (0, 12)
//new query
INSERT INTO infos_game VALUES (0, 12)

Related

How to use 3 conditions in SQL properly which is SUBSTRING, IF ELSE, EXISTS on making a data unique?

So I haven't figured out my problem when it comes to my query, I want to get the first 3 strings of my data and make it unique for example I inputted GTX-2070 if I input another first 3 strings that is GTX-3070 it should not be accepted because the first 3 initial is already used. I tried to do this first in mysQL query.
Here is my code in mySQL
SELECT (CASE WHEN (IF EXISTS(SELECT SUBSTRING(control_no, 1, 3) FROM tools_masterlist BEGIN INSERT IGNORE INTO tools_masterlist (tools_id, tools_name, control_no)
VALUES ('value a', 'value b', 'value c') END) THEN 'Error input' ELSE = 'Okay' END)) FROM tools_masterlist WHERE control_no = 'GTX-2070'
I am still figuring it out because I got errors in mySQL query and can't find the solution. Thank you for the help
One sensisble option here would be to add a prefix column and make it unique:
ALTER TABLE tools_masterlist ADD prefix VARCHAR(3);
ALTER TABLE tools_masterlist ADD CONSTRAINT cnstr_prefix UNIQUE (prefix);
When you insert, now also specify the prefix. Attempting to insert a control_no whose prefix already exists in the table will fail with an error.

PHP MySQL AUTO_INCREMENT with INSERT INTO .. ON DUPLICATE KEY

I have searched for an answer for days, however I can't seem to find the right solution. Therefore, I ask the following question:
Suppose I have a table with a column ID which is an AUTO_INCREMENT field and a column Word which is unique. I run the following queries:
"INSERT IGNORE INTO Table (Word) VALUES('Test')"
"INSERT IGNORE INTO Table (Word) VALUES('Test1')"
"INSERT IGNORE INTO Table (Word) VALUES('Test2')"
"INSERT IGNORE INTO Table (Word) VALUES('Test')" //THIS ONE WILL BE IGNORED
The problem is I can't get the last $mysqli->insert_id from the last query, because it isn't inserting anything. However I need this ID which is already in the DB. therefore, I thought I should use a ON DUPLICATE KEY UPDATE statement, however this leads to the situation where AUTO_INCREMENT is skipping values, because it updates the value but ALSO increments the AUTO_INCREMENT value although this value isn't assigned to any row.
So in the end, I end up with a table like this:
ID |Word
1 |Test
2 |Test1
3 |Test2
//Trying to insert words that where already in the table..
12 |Test3
//Trying to insert words that where already in the table..
17 |Test4
My answer would be to first retrieve the id for the word from the table and only if it fails to insert it. In both cases you have the id ready.
My guess is also that it will be faster this way around since you are not creating any ignored errors in mysql.

MySQL query gone wrong?

another query gone wrong!
I am trying to INSERT INTO anretOrders (order, orderNumber) VALUES ('test', 15)
Now, the anretOrders table has 3 columns, but one is the id so i am leaving that out since it auto-increments. The other is "order" which is a text column, and orderNumber which is an int.
I cannot, for the life of me, figure out what is wrong here? what am i missing?
escape the field names since order is a keyword in mysql
INSERT INTO anretOrders (`order`, `orderNumber`) VALUES ('test', 15)
order is a Reserved Words
So try like this
create table anretOrders (`order` varchar(20),orderNumber int);
INSERT INTO anretOrders (`order`, `orderNumber`) VALUES ('test', 15)
Sql FIDDLE

How to get all last_insert_ids after running a single statement multiple insert query?

I have a 'location' table and a 'location_detail'[for inserting different language data] table. 'location_detail' contains FK of location table
I need to enter multiple location at a time. So what I am doing is:
run a 'for' loop inside that first I enter data into 'location' table get the loc_id then insert into location_detail table[Here in 'location_detail' table if more than one language present, again I want to run the query multiple times].
So if I want to add 3 locations -> Outer 'for' loop will run 3 times
total no of query exec. is 6 [If more than one language is present this will multiple]
==>My aim is to insert all 3(say) locations into 'location' table using multiple insert in a single statement and get all 3 last_insert_ids.
==>Next I can run single statement multiple insert query for adding into 'location_details' table
Here, how will I get this last_insert_ids in an array?
I'll do this in the same transaction/connection :
INSERT INTO location (col1, col2) VALUES (val1a, val2a);
SET #string_ids = LAST_INSERT_ID();
INSERT INTO location (col1, col2) VALUES (val1b, val2b);
SET #string_ids = CONCAT(#string_ids , ",", LAST_INSERT_ID());
INSERT INTO location (col1, col2) VALUES (val1c, val2c);
SET #string_ids = CONCAT(#string_ids , ",", LAST_INSERT_ID());
SELECT #string_ids ;
Then in php, I would explode this variable :
$array_ids = explode (",", $string_ids ).
Then build your request with php :
INSERT INTO location_detail(id, fk_id) VALUES
//foreach loop
(val_id1b, $array_ids[$i] )
(val_id2b, $array_ids[$i] )
(val_id3b, $array_ids[$i] )
I haven't tried the #array_ids but it should work.
Look at this link for more help if you need it.
I hope it fits your needs.
You can use transaction and get last_insert_id and calculate previous id's relate to your AUTO_INCREMENT settings.
Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.
from Last Insert ID documentation.

PHP MYSQL - Insert into without using column names but with autoincrement field

I need to insert a long row with 32 fields into a MySQL table.
I'd like to do something like this:
$sql="insert into tblname values (... 32 fields ...)";
Obviously, it works fine if the fields are in the same order as the MySQL table fields. But, my table has an auto-increment id as it's first field.
What I want is to fill in all table names but the first (id) one.
Suggestions?
Just use NULL as your first value, the autoincrement field will still work as expected:
INSERT INTO tblname VALUES (NULL, ... 32 Fields ... )
Insert NULL into the auto-increment field.
I recommend that unless this is a hack script, you use field names. The rationale is that your code will break if you ever add a field to the table or change their order.
Instead, be explicit with field names, and it will go much better in the future.
Use NULL or 0 to insert an auto-incremented value as shown below:
-- Here
INSERT INTO tblname VALUES (NULL, ... 32 Fields ... )
-- Here
INSERT INTO tblname VALUES (0, ... 32 Fields ... )
We should omit any column values when we try without column name in insert query,
Advise if above information is wrong.
Here's a simple shortcut that I've used:
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.urlencode($value).'\','; }
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$sql='INSERT INTO customer_info ('.$fieldlist.') VALUES ('.$vallist.')';
Please note that this code would be vulnerable to SQL Injection and should be modified to accommodate PDO's, but I felt this simplified script would more directly answer the question with regards to the originally posted code.

Categories