I am running a query every 15 minutes to retrieve new data from an API and store this data in my database.
So every 15 minutes I would like to store the new data in the table and get rid of the all old data in that table.
I am currently using the following method:
$sql = "DELETE FROM self_user_follower
INSERT INTO self_user_follower (username, profile_picture, full_name, user_id, last_updated)
VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id, :query_last_updated)";
But it gives me the following error:
Array
(
[0] => 42000
[1] => 1064
[2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO self_user_follower (username, profile_picture, full_name, user_id, l' at line 2
)
query_error
Is this the best way to do it or is there a nicer and cleaner way to do this?
If you want to put two SQL queries into one statement string, you have to
separate them with a semi-colon (;)
use the function mysqli_multi_query which supports multiple queries.
Unless you have a very good reason, modify your code so that it executes each query separately. MySQLi offers transaction support if you need that.*
The reason why you need a separate function is instructive; as mentioned in the docs:
An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
*: Actually, I'm not even sure the multi_query will execute both queries in the same transaction - I'm just guessing for your reason to use a multi-query.
Multiple statements should be terminated by semi colon
Try this
$sql = "DELETE FROM self_user_follower;
INSERT INTO self_user_follower
(username, profile_picture, full_name, user_id, last_updated)
VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id,
:query_last_updated)";
Related
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.
I am using PHP and SQL and trying to insert user data into two tables upon registration. First in the user_table and second into the character_table. I'm using an automatically generating user_id to link the tables and need to get the value of the user_id from the first INSERT (into user_table) then add it to a column in the character_table.
I tried a few methods and here is where I ended ($username, $email, $password and $character are defined above);
$sql = "INSERT INTO
user_table (id, username, email, password)
VALUES ('NULL', '".$username."', '".$email."', '".$password."')
INSERT INTO
character_table (name, id)
VALUES ('".$character."', 'LAST_INSERT_ID()')";"
I want "id" from user_table to match with "id" inserted into character_table.
When I run the above, nothing seems to be happening. Previous attempts I always ended with id = 0. What is the correct way I can get the ID from the first INSERT?
Run your statements seperately. You run your insertion into your user_table, then grab the id then run your insertion into your character_table
You can grab the id using mysql_insert_id after running the insert. Note that on the php webpage detailing the mysql_insert_id function that it is deprecated as is all mysql* functions. Which leads to...
For the love of everything holy don't concatenate your variables directly to your INSERT statement. Switch to mysqli* functions or PDO if you haven't already and use prepared statements (parameterizing the query). If you build an application using mysql it means you are not parameterizing your queries which means you are at a huge risk for a sql injection attack.
If/when you switch over to mysqli or PDO functions you will find an equivalent mysqli_insert_id() (or PDO::lastInsertID()) function
How do I join these two queries and execute them as a single query to insert values in two tables:
$sql = mysql_real_escape_string('INSERT INTO admin_export(datetime, product_name, item_code,quantity,subject,export_no) VALUES').implode(',', $row_data);
$sql2 = "insert into `itflower_exportno` (admin_exportno) values('$exportno1')";
You need to separate your two INSERT statements with a semicolon into the single variable.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
You can however use transactions as following example.
BEGIN;
INSERT INTO users (username, password)
VALUES('test', 'test');
INSERT INTO profiles (userid, bio, homepage)
VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com');
COMMIT;
What you have in the code are two different inserts.
MySQL doesn't allow for multiple inserts to be run in the same query so you will have to do one first and then the other.
However you can insert multiple rows in the same table in just one query, basically you are restricted to do all the insert you want in one table at a time.
You can't do this.
If you want to do it because you are afraid of the integrity of the data, use transaction .
Second, use suitable transaction isolation level, to ensure that data are reading correctly.
I'm working on a site in which I have to insert values in different table. so keeping this need in view, is it possible for me that can I use multiple query in single mysql_query in php or not.
for example:
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'); insert into tableB (xxx, xxx, xxx) values ('value1','value2','value3')")
I want to run multiple queries in single statement. Please suggest some solution.
No, it is not possible. The obsolete mysql_* API only allows for one query to be executed at a time. To do this you need to use the mysqli API and mysqli_multi_query().
A single MySQL "INSERT" statement can support multiple VALUE tuples if they're for the same table.
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'), ('yyy','yyy')")
However, what you're trying to do is not possible with the mysql_* functions.
Although the mysqli_* API allows you to run multiple queries at once, I recommend you AGAINST doing that for at least 2 reasons:
It's always a good (actually, great) idea to use prepared statements, for security reasons. Prepared statements can be used with the MySQLi API as well as with PDO.
As you can see from the docs for mysqli_multi_query(), getting errors from that function can be cumbersome. The function, indeed, returns only "false" if the first query fails; to get results for other queries you need to call another function.
In general, why would you need to combine multiple queries together? Eventually, the time you'd save would be minimal.
Instead, if your goal is having more than one query executed together, and having the whole set of queries fail if one fails, you can use transactions (which also can speed up inserts in some cases). Both MySQLi and PDO support transactions: see examples here for PDO http://php.net/manual/en/pdo.transactions.php
PS: in general, it's a good idea to avoid using mysql_* functions entirely, as those APIs are deprecated.
Welcome to PDO:
With PDO am able to do something like:
$sql = "
insert into tableA (e_mail, name) values (:e_mail, :name);
insert into tableB (xxx1, xxx2, xxx3) values (:xxx1, :xxx2, :xxx3)
";
Just have the Query Prepared first then VOILA!!
OR Using the Transaction method:
$con->beginTransaction();
$sql1 = "insert into tableA (e_mail, name) values (:e_mail, :name)";
$sql2 = "insert into tableB (xxx, fff) values (:xxx, :fff)";
$sql3 = "insert into tableC (qqq, bbb) values (:qqq, :bbb)";
$con->commit();
I'm having some trouble with a SQL transaction using PHP and mySQL. Here is my statement:
START TRANSACTION;
INSERT INTO listings (title, price, seller, description, time, featured)
VALUES (?, ?, ?, ?, ?, 0);
SELECT #listingid:=LAST_INSERT_ID();
INSERT INTO pictures (listid, primarypic)
VALUES (#listingid, 1);
COMMIT;
While this statement works fine when I put it in directly using phpMyAdmin (substituting the ? marks), it seems to fail when I call
$stmt = $mysqli->prepare("statement");
Replace "statement" with the above statement. The fact that it fails before getting to the bind_param of the $stmt leaves me to believe that it is not a problem with the parameters, but rather the query.
Here is the exact error, if it helps:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO listings (title, price, seller, description, time, featured) ' at line 2
Thanks in advance for your help!
I don't think mysqli can handle compound statements like that (especially since there is a separate commit() function). Instead of START TRANSACTION; at the beginning and COMMIT; at the end, you'd do $mysqli->autocommit(false); before the query and $mysqli->commit(); when you're done.
The problem is that you can only "prepare" a single SQL statement -- you are trying to prepare five SQL statements here.
One way to do what you want is to create a stored procedure.
From mysqli_prepare() documentation:
Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.