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

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.

Related

Insert into table search_index in Prestashop fails

I have absolutely no idea whats going on.
I'm trying INSERT into table ps_search_index like this:
$sql = 'INSERT INTO ps_search_index (id_product,id_word,weight)
VALUES ('.$id_product.','.$getID.',9)';
Db::getInstance()->Execute($sql);
and it doesn't work if there is $id_product.
But its working when i write eg. 1234. id_product is of course INT and any other value in this place working.
Of course no other errors.
Whats should i do?
Try this:
Db::getInstance()->execute('
INSERT INTO '._DB_PREFIX_.'search_index (id_product, id_word, weight)
VALUES ('.(int)$id_product.', '.(int)$getID.', 9)
ON DUPLICATE KEY UPDATE weight = weight + VALUES(weight)', false
);
I always recommend to cast the var. In this case you have to add ON DUPLICATE..., like is do in the Search class.
I've done this using tutorial:
http://blog.belvg.com/developer-tips-how-prestashop-search-works.html
In ps_search_index database table of PrestaShop, the combination of id_product and id_word is the primary key of the table.
Since the primary key of any database table has to be unique, your query is failing as the combination that you are adding in your query must already be existing in the table. In order to fix this, you can apply a check before inserting any new row.

INSERT query not working in mysqli

I have a table named user_data which contains 5 rows-id(primary key),name,address,phone,sex.When I try to insert values into the table via this query
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
it doesnt work.But When I tried this one,it works.
mysqli_query($con,"INSERT INTO user_data (name,address,phone,sex) VALUES ('Peter_Gregory', 'Griffin door',35897,'male')");
I didnt understand what is the real issue behind this.I am using PHP 5.4.7 and XAMPP 1.8.1.
instead of this:
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
Use this when the field is set as NOT NULL
mysqli_query($con,"INSERT INTO user_data VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male')");
Or use this when the field is set as NULL
mysqli_query($con,"INSERT INTO user_data VALUES (0, 'Peter_malik', 'Griffin door',35897,'male')")
See the mysql manual: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
It does not insert in the first query since it assumes the first value i.e. 'Peter_malik' is for your primary key and it fails.
When you specify the column names in the query it knows which value is for which column.
I addition in the first case i.e.
'Peter_malik', 'Griffin door',35897,'male'
will refer to
id(pk),name,address,phone
So u need to pass the first value as NULL so that id gets auto incremented. So the first query should be as
VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male')
If your table has 5 columns id, name, address, phone and sex your staement has to provide 5 values, one for each column. Since your stament provides only 4 values, you need a column list to tell MySQL which values you do provide.
If your id column is a auto_increment column, you can provide null in your values clause.
So you have to say:
INSERT INTO user_data VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male');
OR
INSERT INTO user_data (name,address,phone,sex) VALUES
('Peter_malik', 'Griffin door',35897,'male')
You need to include the id column on your insert statement:
mysqli_query($con,"INSERT INTO user_data VALUES (null, 'Peter_malik', 'Griffin door',35897,'male')");
, provided that your id field is set to autoincrement! ;)
If you provide the ID also in your first query, it will work without any problem.
Assuming that id=1
mysqli_query($con,"INSERT INTO user_data VALUES (1,'Peter_malik', 'Griffin door',35897,'male')");
As others said when you have not explicitly mentioned your column names in a query, you have to provide all the values.
when you are trying the following query then...
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
In this query you only inserting 4 values in the table but the table has 5 field so it is causing problem because in the above query the value is inserting form first field & the sequence or datatype mismatching in the database because of this this query causing problem .
If u want insert wuthout specifing field then you may use the following query....
mysqli_query($con,"INSERT INTO user_data VALUES (0,'Peter_malik', 'Griffin door',35897,'male')");<br><br>
It Will work properly.
and in the your second query you also specifying the field name & corresponding their values so that's query not causing any problem.

PHP - MYSQL - insert on duplicate key AND(?)

Is it possible to connect the duplicate key to another statement.
I just picked some integers (4=4) for the example. In the actuall code I am trying to compare two dates and only if the date in the database row is bigger than the php generated date AND duplicated key it should update unj to 7.
from this:
$sql="INSERT INTO mutable (hid, xsn, unj, for, datetime)
VALUES ('$hid', '$xsn', '$unj', '$for', now()) ON DUPLICATE KEY UPDATE unj=7";
to this:
$sql="INSERT INTO mutable (hid, xsn, unj, for, datetime)
VALUES ('$hid', '$xsn', '$unj', '$for', now()) ON 4=4 AND DUPLICATE KEY UPDATE unj=7";
( ON 4=4 AND ) added.
But this is not working. Is there any way to archive this?
Thank you.
edit: I know I could archive this with using SELECT and then INPUT or UPDATE but I need more efficient code.
INSERT INTO mutable (hid, xsn, unj, `for`, datetime)
VALUES ('$hid', '$xsn', '$unj', '$for', now())
ON DUPLICATE KEY UPDATE unj = IF(datetime > VALUES(datetime), 7, unj)
I tested this and it works.
The VALUES(datetime) refers to the value you tried to insert into the datetime column. It's a convenient way to repeat the value in your ON DUPLICATE KEY UPDATE clause without having to write it twice in the query.
If the condition in IF() returns false, then the default is to set unj = unj which means a no-op.
PS: for is a MySQL reserved word, so it needs to be delimited. It would be simpler to avoid that column name.

auto increment id not inserted

I am using simple MySQL code to insert data from a form with auto_increment id, it works fine on local host but not on server.
this is the code I am using
$myvar=$_POST['var'];
//Insert data into mysql table
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
in local host phpmyadmin data is inserted in table but on server phpmyadmin data is not inserted in table. In my localhost I am using XAMPP whereas phpmyadmin on IIS server.
What setting should I do in phpmyadmin on server so that id is automatically inserted with auto increment, I know I can use mysql_insert_id() to insert id but in lots of file i have used this type of code which I cannot change. I want the same setting as XAMPP that can take this type of code easily.
You as inserting '' into auto-increment id. just insert other fields and MySQL handles the auto-increment column.
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
should be
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
if still you are getting the error
first check, in the server your id column must marked as auto_increment.data type should be int.
if it is ok then
insert into mytable(myvar) values('test');
and try to use prepared statements to avoid the sql injection. Thanks.
hope this may usefull for you.
If you want the last of all the rows in the table, then this is finally the time where MAX(id) is the right answer! :) kind of.
SELECT fields FROM mytable BY id DESC LIMIT 1;
will get the last id then increment it to 1 // add this value to id in insert statement
or
if you have a autoincrement column change it to
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
to
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
auto increment inserts id itself so you don't need to pass it through code
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
or you can do this
$sql="INSERT INTO mytable(id,myvar) VALUES (NULL,'$myvar')";
if you want want to manually insert id for some reason
$sql="INSERT INTO mytable(id,myvar) VALUES (10,'$myvar')";
First check your table Structure Property by applying query:
desc mytable (or) show create table mytable.
Check auto increment property been set for column id.
If yes means don't need to pass id in insert query.
Just write a query as :-
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";

Check with sql if two tables are unique PHP

How can I check in MYSQL PHP if two columns are unique then not insert again, else if just one column is unique then insert, is that even possible to do in php?
EDIT:
Lets say I have a table like this,
userId | codeId
And I I send a query like this,
$query = $pdo->prepare('insert into table (userId, codeId) values (?,?)');
So now I want to check if userId and codeId are added already once do not insert again, and if just one is added, then do insert the entire query,
I hope its more understanding.
Set up a unique key for those columns, then the mysql query will FAIL when you try to insert.
Use REPLACE INTO instead of INSERT INTO ... ?
Do something like the code below (where TEXT_ID and TEXT_CATEGORY, are keys of table):
INSERT INTO
table_texts
SET
text_id = 174,
text_category = "pam_texto"
ON DUPLICATE KEY UPDATE
text_id = 174,
text_category = "pam_texto";
The above code tries to insert, but if the keys are duplicated performs an update on the line.

Categories