SELECT and INSERT not selecting - php

When I execute
INSERT INTO `survey`
(`id`,`name`,`date_start`,`date_end`)
values
(:id,:name,NULL,DATE_ADD(NOW(), INTERVAL 1 MINUTE))
on duplicate key UPDATE `name`=:name;
SELECT coalesce(:id,LAST_INSERT_ID()) as 'id'
it inserts a new data fine, but doesn't select the id (which is needed later on in my php code)
I've tried this suggestion
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
but this SQL throws errors (due to duplicate parameters)
SELECT ASCII(substr(`perm` FROM floor(:i/8)+1))&(1<<(:i%8))>0 as perm FROM `user` WHERE `id`=:id
I'm in a lose-lose situation, re-writing all my SQL code to not have duplicate parameters would be very messy, doing a separate select straight after inserting may not return the id I want. Any suggestions would be great

You cannot run two queries at the same time, only one at the time.
If you want to do the whole thing at once then create a stored procedure.
Same goes for complex queries, when it gets complicated you want to have your logic in the database.
Here is an example:
DELIMITER //
CREATE PROCEDURE sp_insert_survey(IN `p_id`,
IN `p_name`,
IN `p_date_start`,
IN `p_date_end`)
BEGIN
INSERT INTO `survey`(`id`,`name`,`date_start`,`date_end`)
VALUES (p_id, p_name, p_date_start, p_date_end);
SELECT `id`,`name`,`date_start`,`date_end`
FROM survey WHERE `id` =LAST_INSERT_ID();
END //
DELIMITER ;
Call the sp from PDO:
$stmt = $db->prepare('CALL sp_insert_survey(?, ?, ?, ?)');
then fetch the data as a SELECT query.

Upon typing this up, one of the similar questions that came up on the right getting last inserted row id with PDO (not suitable result) gave a suitable answer in the question itself, although I'm a little dubious considering the method is being questioned itself.
$db->lastInsertId();
Seems to work for me, but in the question linked it isn't working as desired for the questioner, so I'm not entirely settled with this answer. It does seem to be a bit of a hack.

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.

Inserting values into a table under conditions

Im trying to insert two values into a table if one condition is met and another is not met.
I've found a tutorial on the matter but i can't seem to get it to work.
The tutorial explains how to create a simple PHP like button, and has two tables, articles and articles_likes.
articles has two columns: id and title.
articles_likes has three columns: id, user and article.
The code in the tutorial looks like this:
$db->query("
INSERT INTO articles_likes (user, article)
SELECT {$_SESSION['user_id']}, {$id}
FROM articles
WHERE EXISTS (
SELECT id
FROM articles
WHERE id = {$id})
AND NOT EXISTS (
SELECT id
FROM articles_likes
WHERE user = {$_SESSION['user_id']}
AND article = {$id})
LIMIT 1
");
Now first of all, im using PDO with $query = $pdo->prepare(" .. "); and question marks plus bindValue() to avoid SQL injections, and all that is working fine with other SQL statements, but this one does not seem to work.
I've googled the INSERT INTO .. SELECT .. FROM syntax, and W3schools explains it as copying values from one table into another one. So how is this even working in the tutorial? articles has a completely different structure, and he is inserting $variables into the SELECT statement.
Can anyone explain why this works in the first place, and how it would work in PDO?
Edit:
Here is my own code (I've added $value because my code is for a binary rating instead of a like):
global $pdo;
$query = $pdo->prepare("
INSERT INTO quote_ratings (user_ip, quote_id, value)
SELECT ?, ?, ?
FROM posts
WHERE EXISTS (
SELECT id
FROM posts
WHERE id = ?)
AND NOT EXISTS (
SELECT id
FROM quote_ratings
WHERE user_ip = ?
AND quote_id = ?)
LIMIT 1
");
$query->bindValue(1, $user_ip);
$query->bindValue(2, $quote_id);
$query->bindValue(3, $rating);
$query->bindValue(4, $quote_id);
$query->bindValue(5, $user_ip);
$query->bindValue(6, $quote_id);
$query->execute();
Some kind of nested SQL queries did not get bind properly and something is left by the PDO parser during the processing of query. Also there is no way to see if the the final query generated by PDO.
I will recommend to use Mysqli library to use in such scenarios. I usually encounter such issues during complex joins or executions of custom triggers. If you want to go ahead with object oriented code you can use MySQLi Class or also you could use simple procedural approach.
Atul Jindal
I i completely agree that PDO is good choice to avoid sql injections but, you know at such situations you are unable to debug your queries. But if you use mysqli wisely and properly check sql injections when you input, then there will not be a problem.
I've found the problem: PDO, by default, uses unbuffered queries. This for some reason makes the request impossible to parse. So the mode has to be changed for this request:
$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
and everything works fine from then on!

Need an alternate solution instead of calling PHP code from a trigger

I am having two table consider table1 and table2. I need to do a trigger after inserting into table1.
Trigger has to do some thing like retrieving data from two other tables using select query (it retrieves more than one row) do some calculations with the data retrieved and then it need to insert it into table2 as single row.
I think it's not possible to do these with in a trigger, so I decided to call a php file from that trigger which does all those things. But some persons says calling php from a trigger is not practically good and it has some security risk.
A Simple Example will help you out.
$sql="INSERT INTO `table1` (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
$result = mysql_query($sql) ;
if($result)
{
// Record successfully inserted , place your code which needs to be executed after successful insertion
}
else
{
// Insertion failed
}
I assume you would be using mysqli and not mysql becuase mysql_query is deprecated as of PHP 5.5.0 but this is just an example to help you understand the logic.
Ok got you .. In this case you need to create a TRIGGER something like this.
CREATE
TRIGGER `event_name` BEFORE/AFTER INSERT/UPDATE/DELETE
ON `database`.`table`
FOR EACH ROW BEGIN
-- trigger body
-- this code is applied to every
-- inserted/updated/deleted row
END;
This Question has already been answered check the link below.
MySQL trigger On Insert/Update events
Hope this helps.

How to insert data to several tables in MySQL?

I have only just begun learning about joining tables in MySQL. Now, I have a small project where I simply want to let the visitor insert data through a form. The data is then displayed in a HTML table with four rows, joining together two tables in my database. The "problem" is that the data should be submitted into those two different tables in my database.
I tried
$query = "INSERT INTO table1, table2 (col1, col2, col3, col4) VALUES ('value1', 'value2', 'value3', 'value4')";
but that doesn't seem to do it. What is the correct syntax for submitting form data to several database tables? Oh, and I read some similar threads mentioning using transactions. Is this necessary? My tables are run with MyISAM. Thanks!
You can read more about it from the MySQL Manual. In short, you cannot insert into multiple tables at once. This leaves you with three options:
Multiple INSERT statements
Triggers
Stored Procedures
The answer to this question: MySQL Insert into multiple tables? (Database normalization?) suggests using transactions, which will not work with MyISAM, but is a good FYI if you ever switch to InnoDB.
I really recommend you read up on Triggers. They can make your life a lot easier. But if you don't want to use them, look into PHP's mysqli_multi_query, which will allow you to execute two different queries at the same time, for example:
$query = "INSERT INTO table1 (col1,col2) VALUES ('$value1','$value2');";
$query = "INSERT INTO table2 (col3,col4) VALUES ('$value3','$value4');";
$result = mysqli_multi_query($dbcon, $query);
You can perform this by using MySQL Transactions By:
Try:
BEGIN
INSERT INTO table1 (col1, col2...ETC)
VALUES('value1', 'value2'...ETC)
INSERT INTO table2 (col1, col2...ETC)
VALUES('value1', 'value2'...ETC);
COMMIT;
With MyISM you will need to execute the query for each table you want to insert into, I do not believe that in a single query you can add to multiple tables.
In your case you can not use Transactions because they are not supported by your engine.
Your only solution is to use several separate queries, preferably within a transaction. Transactions are necessary if you want to make sure that the data from each query is inserted, in which case you COMMIT the transaction; should one of the queries fail, you can ROLLBACK.
P.S. Use InnoDB. It's better in pretty much any environment where INSERT queries make up at least 5% of all queries (sadly I cannot give the source as I had read it several months ago and no longer remember where).
I may be wrong, but you don't insert into multiple tables at the same time. You split it into two or more commands, each handling the specific insertion, whats the big deal, that one extra line of code (which makes everything clearer) too much of a hassle to type?
Look at it this way, if you write a large script, for instance a routine to process some data, the more you segment the code, the easier it is to debug, and, if necessary, inoculate instructions that are problematic, it will end up saving you time in the long run.
I have this problem before You can use multiple query function
$query = "INSERT INTO table1 (col1,col2) VALUES ('$value1','$value2')";
$query = "INSERT INTO table2 (col3,col4) VALUES ('$value3','$value4')";
$result = mysqli_multi_query($dbcon, $query);

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

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.

Categories