I was searching for a way to insert data into two database tables in a single query in such a way that if one failed, neither saved (I don't want orphaned data). I came across a Stack Overflow question that showed me how to use BEGIN...COMMIT to accomplish this, but it simply is not working.
Here's the query I've set up:
$query = "BEGIN;
INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer');
INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort');
COMMIT;";
mysql_query($query) or die (mysql_error());
I get the following error:
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 content_subpages (title, url_referer) VALUES ('TESTING','testing'); ' at line 2
This is my first time using BEGIN...COMMIT, so it's reasonable that I might be doing something wrong, but I followed the syntax of the SQL Fiddle example given by the selected answer to the Stack Overflow question I mentioned (http://stackoverflow.com/questions/12649706/mysql-insert-into-multiple-tables-in-same-query-with-begincommit), but it still won't work.
If I can easily achieve the "all-or-nothing" multiple INSERT result without BEGIN...COMMIT, that would be an acceptable solution.
Thanks in advance
Try breaking the lines into multiple php statements:
$query = "BEGIN";
mysql_query($query) or die (mysql_error());
$query = "INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer')";
mysql_query($query) or die (mysql_error());
$query = "INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort')";
mysql_query($query) or die (mysql_error())
$query = "COMMIT";
mysql_query($query) or die (mysql_error());
you need to use multi_query instead.
http://php.net/manual/en/mysqli.multi-query.php
Make sure you're using an InnoDB table and not a MyISAM table, as MyISAM is not transactional.
To use an InnoDB table, when you create it, after the closing paren, add ENGINE=InnoDB. By default, MyISAM is used.
Try:
$dbh->beginTransaction();
$query = "INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer');
INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort')";
$dbh->exec($query);
$dbh->commit();
Btw, Simon Germain got a good point, Transaction will work with tables using InnoDB engine.
Related
I am attempting to add data across multiple tables using foreign keys. I am using SQL transaction for the first time because I've read good things about it.
I have the below SQL query that works great in phpmyadmin:
BEGIN;
INSERT INTO `webInfo` (`id`, `webItem`, `webDescription`, `webText`)
VALUES(NULL,'tagheuer Watch','Watch','Watch');
INSERT INTO `valuationNotepad` (`id` ,`valuationNotepad1`, `valuationNotepad2`, `valuationNotepad3`, `valuationNotepad4`)
VALUES(LAST_INSERT_ID(),'Watch', 'Watch', 'Watch', 'Watch');
INSERT INTO stock (`id`,`listCost`,`productName`,`totalCost`,`rsp`,`rspDate`,`rspPrev1`,`rspPrev1Date`,`rspPrev2`,`rspPrev2Date`,`rspPrev3`,`rspPrev3Date`,`rspPrev4`,`rspPrev4Date`,`webID`,`valuationNotepadID`,`ringSizeID`,`addedBy`,`dateAdded`,`stockLevel`) VALUES (NULL,30000,'Tagheur Watch',3000,4000,'2020-04-15',50000,'2020-04-15',50000,'2020-04-15',60000,'2020-04-15',65000,'2020-04-15',LAST_INSERT_ID(),LAST_INSERT_ID(),2,'JD',CURRENT_TIMESTAMP,60);
COMMIT;
As said previously, this works great in phpmyadmin. However, when I try to use it with PHP and with PHP variables the query fails. The query with PHP variables is seen below.
$addStock = "BEGIN;
INSERT INTO `webInfo` (`id`, `webItem`, `webDescription`, `webText`)
VALUES(NULL,'$webItem','$webDescription','$webText');
INSERT INTO `valuationNotepad` (`id` ,`valuationNotepad1`, `valuationNotepad2`, `valuationNotepad3`, `valuationNotepad4`)
VALUES(LAST_INSERT_ID(),'$valuationNotepad1', '$valuationNotepad2', '$valuationNotepad3', '$valuationNotepad4');
INSERT INTO stock (`id`,`listCost`,`productName`,`totalCost`,`rsp`,`rspDate`,`rspPrev1`,`rspPrev1Date`,`rspPrev2`,`rspPrev2Date`,`rspPrev3`,`rspPrev3Date`,`rspPrev4`,`rspPrev4Date`,`webID`,`valuationNotepadID`,`ringSizeID`,`addedBy`,`dateAdded`,`stockLevel`) VALUES (NULL,$listCost,$productName,$totalCost,$rsp,$rspDate,$prevRSP1,$prevRSP1Date,$prevRSP2,$prevRSP2Date,$prevRSP3,$prevRSP3Date,$prevRSP4,$prevRSP4Date,LAST_INSERT_ID(),LAST_INSERT_ID(),2,'JD',CURRENT_TIMESTAMP,$stockAdded);
COMMIT;";
$stockAddedResult = mysqli_query($conn, $addStock);
I get the error check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO webInfo in my browser.
I've been trying to solve the error on the basis that it is some kind of SQL keyword error in my query, but now I am unconvinced that this is the issue.
If anyone has any thoughts on what the issue might be please let me know.
Thanks
mysqli_query does not support multiple query
You should either use mysqli_mutli_query() function or change your implementation to explicitly open a transaction , send your 3 inserts and commit it at the end or rollback if one query fails
Example :
<?php
$link = mysqli_connect("localhost", "user1", "datasoft123", "hr");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_ONLY);
mysqli_query($link, "SELECT first_name, last_name FROM actor LIMIT 1");
mysqli_commit($link);
mysqli_close($link);
The error message I'm getting:
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 accounts(balance, interest)
VALUES(0, 1.5)' at line 4 in INSERT INTO accounts(id_user, interest)
VALUES(73, 'Savings');
INSERT INTO balance(balance, interest)
VALUES(0, 1.5)
My PHP code is:
$query = "INSERT INTO accounts(`id_user`, `type`)
VALUES($userid, '$type');
INSERT INTO balance(`balance`, `interest`)
VALUES(0, $interest)";
My first guess that something was wrong with my query, so I tried to run the exact same query in phpMyAdmin and it worked perfectly.
Any suggestions on what might be wrong ?
Gordon Linoff is correct.
From the great manual in the sky.
"mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier. "
http://php.net/manual/en/function.mysql-query.php
change
$query = "INSERT INTO accounts(`id_user`, `type`)
VALUES($userid, '$type');
INSERT INTO balance(`balance`, `interest`)
VALUES(0, $interest)";
to
$query = "INSERT INTO accounts(`id_user`, `type`)
VALUES($userid, '$type');";
result = mysql_query($query);
$query="INSERT INTO balance(`balance`, `interest`)
VALUES(0, $interest)";
result = mysql_query($query);
Are you using mysqli to run this ? I suspect you are running two queries in a single statement, you need to use mysqli_multi_query function to execute multiple queries at the same time.
Mysqli Manual page on multi_query
I'm slowly progressing through PHP and SQL and have stumbled upon a small error, when trying to send a string into an SQL database. What I'm trying to do is insert a users's detail into one table (which currently works) and send the user name along with 5 blank entries into another table. The table examscore fields are username, exam, exam1, exam2, exam3, exam4 (it is these exam fields that I require blank for now).
The problem is that I receive the following message:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\xampp\htdocs\E-LearningWebsite\addcustomertodb.php on line 11 (which line that starts $query1)
If possible could anyone explain what this error means and what i have done wrong?
<?php
require "dbconn.php";
$username = $_GET['username'];
$email = $_GET['email'];
$pass = $_GET['password'];
$query = "INSERT INTO customer VALUES ('".$username."','".$email."','".$pass."')";
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
$results = mysql_query($query) or die (mysql_error());
$results1 = mysql_query($query1) or die (mysql_error());
?>
Kind regards Andy
change
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
to
$query1 = "INSERT INTO examscores VALUES ('".$username."','','','','','')";
ps. you are inviting SQL injections but that is a different story...
The goggles! They do nothing! The sql injection vulnerabilities! And it's only Monday!
Why not just
$query ="INSERT INTO customer VALUES ('$username', '$email', '$pass');";
$query1 = "INSERT INTO examscores VALUES ('$username', '', '', '', etc...);";
PHP will happily replace $vars inside "" quoted strings for you. There's absolutely not need for all the concatentation you're doing. Any decent code editor will still highlight the vars for you.
you are missing dots to concatenate your strings
$query1 = "INSERT INTO examscores VALUES ('".$username."','"."','"."','"."','"."','"."')";
furthermore you dont need to have different strings
and still further more you dont need to include every column if you are not inserting them
Your immediate problem causing the errors is the missing .s from query1 from between the double-doublequotes, (or you should just delete the double-doublequotes altogether. Or even the unneeded columns...).
But there are way bigger issues in your code:
SQL injection: your code is vulnerable. You should at least escape th variables coming from the user...
mysql_* deprecation: as of PHP 5.5, these functions will be deprecated. Use either Mysqli or even ebtter PDO.
I'm having problems with an INSERT statement, and the error only says:
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 '' at line 1
It's not helpful at all.
The version I have tried so far and failed is:
mysql_query("INSET INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
[needless to say that the two variables when printed show the right values]
I've also tried versions with nothing around the table name, with ` or ', a million combinations really and nothing works. Not even with constants or into different tables. It just won't insert anything ever. I've checked the privileges (I'm logging into it with root), and it's all on.
I've tried similar stuff on two different machines with the same server (XAMPP 1.7.7) and it works. I'm completely baffled! What can it be?
Thank you for your time!
First and foremost, just type INSERT correctly.
Using _GET like that really opens you up to SQL INJECTIONS...
Do take a look into MySQL prepared statements.
It is also considered good practice to name the columns that you're inserting data into. That allows you to, latter on, insert extra-columns and keep application logic.
INSERT INTO cos(rowName1, rowName2) VALUES(?, ?)
Where ? would be prepared statements.
Correct:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
Have you tried passing the $link to mysql_query ?
Like:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')", $link);
EDIT:
And of course you must take some security measures before inserting anything into the database, maybe mysql_real_escape_string() or even prepared statements.
You are doing it wrong. Why aren't you escaping the values?
Php.net documentation is providing some good and safe working examples:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
So adapted to your code:
$query = sprintf("INSERT INTO `cos` VALUES (%s, %s);",
mysql_real_escape_string($_GET['prod']),
mysql_real_escape_string($_GET['page']));
$result = mysql_query($query);
Please, always escape your values. And use INSERT, not INSET :)
first this is you are using INSET make it correct with INSERT like
$pro = mysql_real_escape_string($_GET['prod']);
$page = mysql_real_escape_string($_GET['page']);
mysql_query("INSERT INTO `cos` (column1, column2)
VALUES ('$pro', '$page')" );
you forget to set the column names...
Try this:
$prod = $_GET['prod'];
$page = $_GET['page'];
mysql_insert("INSERT INTO 'cos' VALUES('$prod','$page)");
This should very well do it :)
basically, I have 3 tables; users and projects, then I have 'users_projects' to allow the one-to-many formation. When a user adds a project, I need the project information stored and then the 'userid' and 'projectid' stored in the usersprojects table. It sounds like its really straight forward but I'm having problems with the syntax I think!?
As it stands, I have this as my INSERT queries (values going into 2 different tables):
$projectid = $_POST['projectid'];
$pname = $_POST['pname'];
$pdeadline = $_POST['pdeadline'];
$pdetails = $_POST['pdetails'];
$userid = $_POST['userid'];
$sql = "INSERT INTO projects (projectid, pname, pdeadline, pdetails) VALUES
('{$projectid}','{$pname}','{$pdeadline}','{$pdetails}')";
$sql = "INSERT INTO users_projects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: frontview.php");
exit();
You simply forgot to execute the sql between each query. Add the
mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
between each query and you are supposed to be fine.
b.t.w (1) it always helpful to test with a console open with tail -f on the sql log (under /var/log/mysql/ )
b.t.w.(2) You are having heavy security issues in your code.
b.t.w (3) You might want to consider using PDO/Mysqli and not the old mysql extension.
b.t.w (4) It would make your life simpler to use some kind of wrapper (a good class) to approach the DB and not do it directly everywhere in your code.
Yeah, two things I would check would be
1) are the queries being executed? Like the other poster mentiond, are you executing the SQL queries in between setting the SQL?
2) if you print/debug/display somehow the variables that you are inserting, are they getting populated? If you're seeing things get inserted, but some of the data is blank then something might be blowing up before that and those variables would be blank.
I may be misunderstanding but are you putting header("Location: main.php"); in the middle of you script?
$projectid=mysql_insert_id($connection);
I called this after my first query, this will get the AutoIncrement value from your projects table and store it in $projectid, then the second query will use it.
so after execution of my first query, I put the above code there, without changing anything else!!
You seem to be trying to execute mysql_query() only once. You have two queries, so it needs to be used twice, once on each query:
$sql = "INSERT INTO projects (projectid, projectname, projectdeadline, projectdetails) VALUES
('{$projectid}','{$projectname}','{$projectdeadline}','{$projectdetails}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
$sql = "INSERT INTO usersprojects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
Alternatively, you could use mysqli_multi_query(), but that might require a significant rewrite of your code to use the mysqli interface.