MySQL INSERT two fields only - php

I have a table with quite a few columns. The total number of columns is not yet specified, and will change on a regular basis.
In my insert query, I only need to put two values into the table. All other values will be ' '. is there a way to only specify the first fields, without having to include '','','',''...? Please see below for example:
I would like to have this:
$query = mysql_query("INSERT INTO table VALUES('','$id')");
Rather than this:
$query = mysql_query("INSERT INTO table VALUES('','$id','','','','','',''......and on and on...)");
Is there a way to do this? Thanks!

Yes, specify the column names after the table name:
INSERT INTO table (column1, column2) VALUES ('','$id')

I'd prefer
INSERT INTO table SET columnA = 'valueA', columnB = 'valueB'

INSERT INTO table_name (column1, column2) VALUES (value1, value2)
http://www.w3schools.com/php/php_mysql_insert.asp

Just define the fields you will insert,
eg:
INSERT INTO table (fieldA, fieldB) VALUES('','$id')
the missing fields will have the default value for that field

Related

How can I use same button to insert or update data in database using conditions [duplicate]

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.
For example:
INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.
If I use INSERT IGNORE it will ignore the error, but it still won’t update.
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
Check out REPLACE:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
Example:
REPLACE INTO `tablename` (`id`, `name`, `age`) VALUES (1, "A", 19)
When using batch insert use the following syntax:
INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
name = VALUES (name),
...
Any of these solution will work regarding your question:
INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);
or
INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19)
ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;
or
REPLACE INTO table (id, name, age) VALUES(1, "A", 19);
Try this:
INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'
Note:
Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.
Try this out:
INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;
Hope this helps.
In case that you wanted to make a non-primary fields as criteria/condition for ON DUPLICATE, you can make a UNIQUE INDEX key on that table to trigger the DUPLICATE.
ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`);
And in case you want to combine two fields to make it unique on the table, you can achieve this by adding more on the last parameter.
ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`, `age`);
Note, just make sure to delete first all the data that has the same name and age value across the other rows.
DELETE table FROM table AS a, table AS b WHERE a.id < b.id
AND a.name <=> b.name AND a.age <=> b.age;
After that, it should trigger the ON DUPLICATE event.
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name = VALUES(name), age = VALUES(age)
Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):
INSERT live-db.table1
SELECT *
FROM test-db.table1 t
ON DUPLICATE KEY UPDATE
ColToUpdate1 = t.ColToUpdate1,
ColToUpdate2 = t.ColToUpdate2,
...
As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE.
No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.
When using SQLite:
REPLACE into table (id, name, age) values(1, "A", 19)
Provided that id is the primary key. Or else it just inserts another row. See INSERT (SQLite).
In case, you want to keep old field (For ex: name). The query will be:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name=name, age=19;
In my case i created below queries but in the first query if id 1 is already exists and age is already there, after that if you create first query without age than the value of age will be none
REPLACE into table SET `id` = 1, `name` = 'A', `age` = 19
for avoiding above issue create query like below
INSERT INTO table SET `id` = '1', `name` = 'A', `age` = 19 ON DUPLICATE KEY UPDATE `id` = "1", `name` = "A",`age` = 19
may it will help you ...
Following are some of the possible approaches:
Using INSERT INTO
The INSERT statement allows you to insert one or more rows into a table
First, specify the table name and a list of comma-separated columns inside parentheses after the INSERT INTO clause.
Secondly, put a comma-separated list of values of the corresponding columns inside the parentheses following the VALUES keyword.
INSERT INTO table_name(column_name1, column_name2, column_name3) VALUES("col_value_1", "col_value_2", "col_value_3");
Using INSERT INTO with WHERE NOT EXISTS clause
INSERT INTO table_name (column_name_1, column_name_2, column_name_3)
SELECT * FROM (SELECT "col_value_1", "col_value_2","col_value_3") AS tmp_name
WHERE NOT EXISTS (
SELECT column_name2 FROM table_name WHERE column_name = "sample_name"
) LIMIT 1;
Using REPLACE INTO
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
REPLACE INTO table_name(column_name1, column_name2, column_name3) VALUES("col_value_1", "col_value_2", "col_value_3");

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

How to Insert / Update a Row in MySQL / PHP At The Same Time

I want to insert into a MySQL row if the row doesn't exist, or update it if it does exist.
Something like this:
$sqlQuery = "INSERT INTO table (Value1, Value2) VALUES ('$var1', '$var2') WHERE UniqueKey='$id'";
Is something like that possible?
INSERT INTO table (UniqueKey,Value1, Value2) VALUES ('$id','$var1', '$var2')
ON DUPLICATE KEY UPDATE Value1 = '$var1',Value2 = '$var1';
User MySQL's REPLACE command:
$sqlQuery = "REPLACE INTO table (id, Value1, Value2) VALUES ('$id', '$var1', '$var2')";
It works the same as a normal INSERT, but if the primary key (in you case 'id') matches then it will replace all the values specified.
replace into table (UniqueKey,Value1,Value2) values ('$id','$var1','$var2');
replace is similar to insert, however if the unique key exists in table, it will delete first, and than insert.

Return next sequence of A_I when inserting a row?

I'm using PHP/MySql.
If I have two tables (hypothetically) as follows:
id
name
and
parent_id
action
And id in the first table is set to AUTO_INCREMENT, if I wanted to insert data into both tables in as fewer queries as possible without re-structuring the database, how could I go about this? I need the next A_I value that will be given to the name that is inserted into table one to insert as the parent ID for the second table.
Probably a poor example, but it's a problem I'm trying to solve. At the minute I'm having to do the following:
<?php
$mysqli->query("INSERT INTO table_1 (name) VALUES ('Bob');
$names = $mysqli->query("SELECT * FROM table_1 WHERE name = 'Bob'");
while($name = $names->fetch_assoc()) {
$mysqli->query("INSERT INTO table_2 (parent_id, action) VALUES ('".$name['id']."', 'run')");
}
?>
But obviously this method breaks if there are people with the same name.
Thanks.
All you need is http://php.net/manual/en/mysqli.insert-id.php
<?php
$mysqli->query("INSERT INTO table_1 (name) VALUES ('Bob')");
$mysqli->query("INSERT INTO table_2 (parent_id, action) VALUES ($mysqli->insert_id,'run')");
?>
You can use PHP function $mysqli->insert_id or MySQL function last_insert_id()
I would do it this way:
$mysqli->query("INSERT INTO table_1 (name) VALUES ('Bob')");
$mysqli->query("INSERT INTO table_2 (parent_id, action) VALUES (LAST_INSERT_ID(),'run')");

mysql insert handle a lot of values

is there a clean way of INSERT a lot of field entry values without them having to be in order? similar to how you can do with the UPDATE like below. can INSERT be done in that format?
$qstring="UPDATE test SET word = 'something' ,";
$qstring .= " word1 = 'something1',";
...
mysql_query($qstring);
Yupp,
insert into
your_table
set
field_1='Yay!',
field_2='Mmmbop!',
...
You can use the SET syntax:
insert into my_table set col1='value', col2='value'
Or, you can specify column names with a VALUES clause:
insert into my_table (col1, col2, col3) VALUES ('value1', 'value2', 'value3')
Using this later form, the values in the VALUES clause must match the order of the values in the column list that precedes the VALUES clause.
If you turn on "extended inserts" (it's usually on by default), you can use the latter form to insert multiple rows with a single statement:
insert into my_table (col1, col2, col3) VALUES
('value1', 'value2', 'value3'),
('row2value1', 'row2value2', 'row2value3'),
('row3value1', 'row3value2', 'row3value3')
INSERT INTO test SET word = 'something', word1 = 'something1'
yes we can do this also with INSERT
$qstring="Insert into test SET";
$qstring .= "word = 'something' ,";
$qstring .= " word1 = 'something1',";
...
mysql_query($qstring);

Categories