how to use mysql update query and mysql insert query together? - php

this the condition: there is a form in html and php haivng around 120 fields its for a website i am making this form on submitting goes to a php page where i first retrive all the values using $_REQUEST[]and then using insert query insert all of them in their specific coloums in the same table in my mysql database. Now i will have to do all the process again for updating these values. Becuase syntax for insert query and update query are quite different .
I dont want to write another 100 lines of code . Is there any way to use the code i wrote inside my insert query to use to update the data.?

Actually in MySQL there is an alternative syntax for insert that is very similar to the syntax for update. You can write
insert customer set customerid=12345, firstname='Fred', lastname='Jones
etc.
Personally I prefer this syntax because it's easy to see what value is going into each field. This is especially true on records with long lists of fields.
On the minus side, it's not standard SQL, so if you ever decide to port your app to a different database engine, all your inserts would have to be rewritten.
Another option I've occasionally used is to write a little function to create your insert and update statements. Then the syntax of your function can be the same, no matter how different the generated code is.

Another alternative, and depending on requirements and keys, you could use:
replace into tbl (<cols>) values (<vals>)
which will insert if not exist, or replace based on keys (insert/update in one query)
or if you are only inserting and don't want to insert twice, you could use:
insert ignore into tbl (<cols>) values (<vals>)
where if the record is already inserted based on keys, it is gracefully ignored
for more info http://dev.mysql.com/doc/refman/5.0/en/replace.html

There is a quite similar syntax for INSERT and UPDATE:
INSERT INTO <table> SET
column1 = value1,
column2 = value2,
...
;
UPDATE <table> SET
column1 = value1,
column2 = value2,
...
WHERE <condition>
;

INSERT INTO yourtable (field1, field2, field3, ...)
VALUES ($field1, $field2, $field3, ...)
ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), etc...
Details on this construct here.

Related

Alternatives for insert ignore into for SQL server

i just switched over from a Mysql server to SQL server. But i just found out that INSERT INGORE INTO doesn't work with sql server.
Original code:
INSERT IGNORE INTO DATA_EXACT_INVENTORY_LOCATIONS (ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
VALUES ('$inventorylocationID','$inventorylocationsItemCode','$inventoryStorageLocationsCode','$inventorylocationsItemDescription','$inventorylocationsCurrenctStock')
I found out that i can use on duplicate key update, but the problem is that i have sql query's with upto 50 variables. So to use on duplicate key update would be alot of work. So what i was wondering is there a better alternative for INSERT IGNORE INTO that's is just plug and play so i don't have to write all variables again.
You can use not exists:
INSERT DATA_EXACT_INVENTORY_LOCATIONS (ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
SELECT ID, Code, Opslaglocatie, Omschrijving, OpVoorraad
FROM (VALUES ('$inventorylocationID', '$inventorylocationsItemCode', '$inventoryStorageLocationsCode', '$inventorylocationsItemDescription', '$inventorylocationsCurrenctStock')
) V(ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
WHERE NOT EXISTS (SELECT 1
FROM DATA_EXACT_INVENTORY_LOCATIONS deil
WHERE deil.id = v.id -- or whatever column gets the duplicate key
);
Alternatively, you could rewrite the code to use MERGE. The SELECT should work in both databases.
Let me also add that you should learn to use parameters. Munging query strings with constant values exposes your code to SQL injection attacks and to hard-to-debug syntax errors.

how to insert data from primary key column to foregin key

i am inserting data from a form i want when i will insert data so the first column primary id which is using in second column as a foreign key should be increased
i have tried this code but not working
first table code
$this->db->query("insert into af_ads (ad_title,ad_pic,ad_description)
values ('$title','$filepath','$description')");
second table code
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category','ad_id')");
NOTE: i want to insert ad_id into ad_id_fk
Try this:
// Your first query
$this->db->query("insert into af_ads(ad_id, ad_title, ad_pic, ad_description)
values ('', '$title', '$filepath', '$description')");
$ad_id = $this->db->insert_id(); // This returns the id that is automatically assigned to that record
// Use the id as foreign key in your second insert query
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category', $ad_id)");
MySQL provides the LAST_INSERT_ID function as way to retrieve the value generated for an AUTO_INCREMENT column from the immediately preceding INSERT statement.
A lot of client libraries make this conveniently avaiable (e.g. PDO lastInsertId function.)
(I'm not familiar with CodeIgniter or ActiveRecord, so I can't speak to how that's made available.
Your code looks like it's using the PDO interface... but I'm not sure about that.
# either we need to check return from functions for errors
# or we can have PDO do the checks and throw an exception
$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
# attempt insert which will generate AUTO_INCREMENT value
$this->db->query("INSERT (ad_id, ... ) VALUES (NULL, ...)");
# if previous insert successfully inserted a row (or rows)
$ad_id = $this->db->lastInsertId();
You really need to check whether the previous insert was successful or not. If you aren't going to code that check yourself, then PDO does provide a mechanism that performs this checking automatically, and will throw an exception if a MySQL error occurs.
I've avoided copying your original code, which looks like it's vulnerable to SQL Injection. If you're using PDO, you can make effective use of prepared statements with bind placeholders, rather than including values in the SQL text.

How to insert with a where from another database?

How do I insert using sql when my data is on one table and my where is on another. Here is the code:
$sql = "INSERT INTO user_can (online_id) VALUES ('$online') WHERE user.online = 'online'";
mysql_query($sql);
I seem to be getting errors when trying to insert, the insert does not happen. It looks like I am messing up with my where code. Does anybody know how I can insert my data?
You're mixing parts of one statement type with parts of another. The SQL needs to be something like:
INSERT INTO user_can (online_id) SELECT online_id FROM user WHERE online = 'online';
The INSERT ... VALUES ... format is for providing explicit values in the SQL. Further Information about INSERT syntax.

mysql php insert multiple rows with comma delimited values

I have an html page where I collect an array of values from checkboxes to insert in a database. The html page posts to a PHP page that collects the data and then stores in the database.
For each value, there are a few other fields I would like to include that are the same for all the values such as time entered. I can easily convert the captured array into a comma delimited list using implode. I use such a comma delimited list of ids to update and delete records. However, when I want to insert them, MYSQL does not seem to allow you to use a comma delimited list. My question is, what is the easiest way to insert records, one for each value in the c comma delimited list, without using a loop.
html page
<input type="checkbox" name="var[]" value=1>
<input type="checkbox" name="var{}" value=2>
PHP page
$vars = $_POST['var'];
This gives me an array that I can convert to a comma delimited list using implode.
To delete, I can go
$sql = "DELETE * from table WHERE id in '$vars'";
To update I can go
$sql = "UPDATE table, WHERE id in '$vars'";
But there does not seem to be an equivalent for Insert.
Following would work:
$sql = "INSERT into table (var, timeentered) values (1,now()) (2,now())";
However, that's not how I have my data. what I would like to do is something like
$sql = "INSERT into table (var,timeentered) values($vars), now()" but of course that doesn't work.
Do I have to convert my nice comma delimited list that works so well for update and delete into something that looks like (1,now) (2, now()) for inserting or is there an alternative?
Thanks for any suggestions.
Unfortunately you have to build whole query by yourself:
$sql ="insert into table (var, timeentered) values ";
$sql .= "(".implode(", now()), (", $vars).")";
You need to loop through your data set and create the multi-line insert query manually. There is no other alternative if you want to insert multiple rows with a single query. That is outside of using certain DB frameworks which might present a better interface for doing this. Of course at the end of the day, such a DB framework would in essence be building the multi-item insert query manually at some point.
The question might come done to one of how many items are you going to insert. If you are only going to be inserting a few records at a time, then you might want to consider just using prepared statements with individual inserts. However if you are going to be inserting hundreds of records at a time, that would probably not be a good idea.
In your mysql database you can set the default for the column "time_created" to be a TIMESTAMP default CURRENT_TIMESTAMP. This way you don't have to worry about it. Just use the regular insert and it will automatically set the "time_created" column.
For your other issue of multi-line inserts you can create an $update array and use a foreach loop to issue a sql insert command on every row of data.
Two options I can think of.
Build a dynamic insert query like you suggest. However do not call now() each time but just insert a single date ie
$time = gmdate();
$sql = "INSERT into table (var, timeentered) values (1,$time) (2,$time)";
Or use a prepared statement of the single insert below, turn off autocommit, start a transaction and execute the prepared statement in a for loop for the number of inserts needed, then commit the transaction.
$sql = "INSERT into table (var, timeentered) values (?,?)"
Mostly you will have to build your query using some type of looping structure. Convention and best practice aside if you just want to know how to make your array acceptable for a multiple insert statement then why not just do this:
$values = '('.implode('),(', $array).')';
or if already CSV then:
$values = '('.implode('),(', explode(',' $csv)).')';
then you can just use $values in your query using double quotes.

Update a column in SQL, inserting a character at a specific point

I have a SQL table gathering form results. I noticed after about 200 results had been gathered, that instead of the date being in the format of 2011-06-01, that it was in the format of 2011-6-01, skipping the leading zero. This is giving some data processing problems. Is there a way to update all the 2011-6-xx values to make then 2011-06-xx? Solutions in either PHP/MySQL or just MS-SQL statements are acceptable, as the data is collected on a webserver using a PHP/MySQL form, exported to CSV, and then imported into an MS-SQL database on site for data analysis.
UPDATE `table` SET `date_column` = REPLACE(`date_column`, '2011-6-', '2011-06-') WHERE `date_column` LIKE '2011-6-%';
UPDATE Table1
SET field1 = REPLACE(field1, '2011-6-', '2011-06-')
WHERE field1 LIKE '2011-6%'
The where will allow you to use an index and replace much faster than looking through all rows.
Also in strict mode MySQL will not execute UPDATE statements without a where clause.
You talk about MS-SQL and MySQL. If it's MS SQL, then the below should work. I don't know if MySQL uses REPLACE or has an equivalent function.
UPDATE
Some_Table
SET
some_string = REPLACE(some_string, '2011-6-', '2011-06-')
WHERE
some_string LIKE '2011-6%'

Categories