473,569 Members | 2,984 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using transactions in MySQL + PHP

Hi there guys,

My doubt is related with MySQL and Transactions (InnoDB) so here it
goes:

I have a query like this:

$query = 'START TRANSACTION; ';
$query .= 'UPDATE sections ';
$query .= 'SET position=positi on-%d ';
$query .= 'WHERE position %d; ';
$query .= 'DELETE FROM sections ';
$query .= 'WHERE id IN %s; ';
$query .= 'COMMIT;';

$result = $db->query(sprintf( $query, count($id), $db-
>result($result ), $ids));
This will perform a query similar to this one:

START TRANSACTION; UPDATE sections SET position=positi on-2 WHERE
position 1; DELETE FROM sections WHERE id IN (15,16); COMMIT;

If I var_dimp $result I will get: bool(false)

So query failed, my doubt is why?

If I copy-paste it and type it on MySQL console or PHPMyAdmin, it will
run with no problems.

Also If I separate $query in four queries, and run them separately,
the script will run too.

Can't this be done like this? If so, what is the correct way of doing
it?

This are maybe simple questions, but thats the first time Im using
transactions, and I didn't found much info on this.

PS: My database is running, and has some data in it.

Thanks for your attention.

Aug 1 '07 #1
9 4799
So query failed, my doubt is why?

After reading PHP manual, I know now that multiple queries are not
suported..
Also If I separate $query in four queries, and run them separately,
the script will run too.
Is this correct? The only way? How should it be done

Aug 1 '07 #2
Rik
On Wed, 01 Aug 2007 14:44:04 +0200, Joćo Morais <jc*******@gmai l.com>
wrote:
My doubt is related with MySQL and Transactions (InnoDB) so here it
goes:

I have a query like this:

$query = 'START TRANSACTION; ';
$query .= 'UPDATE sections ';
$query .= 'SET position=positi on-%d ';
$query .= 'WHERE position %d; ';
$query .= 'DELETE FROM sections ';
$query .= 'WHERE id IN %s; ';
$query .= 'COMMIT;';

$result = $db->query(sprintf( $query, count($id), $db-
>result($result ), $ids));
Before anyone starts complaining, this _is_ imho a PHP question :P.
This will perform a query similar to this one:

START TRANSACTION; UPDATE sections SET position=positi on-2 WHERE
position 1; DELETE FROM sections WHERE id IN (15,16); COMMIT;

If I var_dimp $result I will get: bool(false)

So query failed, my doubt is why?
From the manual:
mysql_query() sends an unique query (multiple queries are not supported)
If I copy-paste it and type it on MySQL console or PHPMyAdmin, it will
run with no problems.
Indeed.
>
Also If I separate $query in four queries, and run them separately,
the script will run too.

Can't this be done like this? If so, what is the correct way of doing
it?
In seperate queries, as you indicate :P. Then again, the main plus of
transactions is IMO the rollback, so test for results and rollback as
needed, which would mean getting the result of the seperate queries,
--
Rik Wasmus
Aug 1 '07 #3
Rik
On Wed, 01 Aug 2007 14:52:13 +0200, Joćo Morais <jc*******@gmai l.com>
wrote:
>So query failed, my doubt is why?

After reading PHP manual, I know now that multiple queries are not
suported..
>Also If I separate $query in four queries, and run them separately,
the script will run too.

Is this correct?
Yes.
The only way?
Nope, but the most usefull one.
How should it be done
Seperate queries, check the return, commit or rollback depending on the
result.
--
Rik Wasmus
Aug 1 '07 #4
Joćo Morais wrote:
Hi there guys,

My doubt is related with MySQL and Transactions (InnoDB) so here it
goes:

I have a query like this:

$query = 'START TRANSACTION; ';
$query .= 'UPDATE sections ';
$query .= 'SET position=positi on-%d ';
$query .= 'WHERE position %d; ';
$query .= 'DELETE FROM sections ';
$query .= 'WHERE id IN %s; ';
$query .= 'COMMIT;';

$result = $db->query(sprintf( $query, count($id), $db-
>result($result ), $ids));

This will perform a query similar to this one:

START TRANSACTION; UPDATE sections SET position=positi on-2 WHERE
position 1; DELETE FROM sections WHERE id IN (15,16); COMMIT;

If I var_dimp $result I will get: bool(false)

So query failed, my doubt is why?

If I copy-paste it and type it on MySQL console or PHPMyAdmin, it will
run with no problems.

Also If I separate $query in four queries, and run them separately,
the script will run too.

Can't this be done like this? If so, what is the correct way of doing
it?

This are maybe simple questions, but thats the first time Im using
transactions, and I didn't found much info on this.

PS: My database is running, and has some data in it.

Thanks for your attention.
You can't do it with mysql_query(), but if you use the improved MySQL
interface you can use mysqli_multi_qu ery (or mysqli->multi_query()) .

However, never having tried it (I don't like multiple queries), I'm not
sure what would happen if one of the queries failed. I agree with Rik -
it's better to use four separate queries and check the results before
rolling back or committing.

And I never claimed this wasn't a PHP question :-)

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Aug 1 '07 #5
On Aug 1, 10:57 am, Jerry Stuckle <jstuck...@attg lobal.netwrote:
Joćo Morais wrote:
Hi there guys,
My doubt is related with MySQL and Transactions (InnoDB) so here it
goes:
I have a query like this:
$query = 'START TRANSACTION; ';
$query .= 'UPDATE sections ';
$query .= 'SET position=positi on-%d ';
$query .= 'WHERE position %d; ';
$query .= 'DELETE FROM sections ';
$query .= 'WHERE id IN %s; ';
$query .= 'COMMIT;';
$result = $db->query(sprintf( $query, count($id), $db-
result($result) , $ids));
This will perform a query similar to this one:
START TRANSACTION; UPDATE sections SET position=positi on-2 WHERE
position 1; DELETE FROM sections WHERE id IN (15,16); COMMIT;
If I var_dimp $result I will get: bool(false)
So query failed, my doubt is why?
If I copy-paste it and type it on MySQL console or PHPMyAdmin, it will
run with no problems.
Also If I separate $query in four queries, and run them separately,
the script will run too.
Can't this be done like this? If so, what is the correct way of doing
it?
This are maybe simple questions, but thats the first time Im using
transactions, and I didn't found much info on this.
PS: My database is running, and has some data in it.
Thanks for your attention.

You can't do it with mysql_query(), but if you use the improved MySQL
interface you can use mysqli_multi_qu ery (or mysqli->multi_query()) .

However, never having tried it (I don't like multiple queries), I'm not
sure what would happen if one of the queries failed. I agree with Rik -
it's better to use four separate queries and check the results before
rolling back or committing.

And I never claimed this wasn't a PHP question :-)

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstuck...@attgl obal.net
=============== ===
Personally, I use pdo_mysql.
$query = 'START TRANSACTION; ';
$query .= 'UPDATE sections ';
$query .= 'SET position=positi on-%d ';
$query .= 'WHERE position %d; ';
$query .= 'DELETE FROM sections ';
$query .= 'WHERE id IN %s; ';
$query .= 'COMMIT;';
becomes

try {
$db = new PDO($dns, $user, $pass)
$db->beginTransacti on();
$up = $db->prepare("UPDAT E sections SET position=? WHERE position
?");
$up->bindParam(1, '$count($id)');
$up->bindParam(2, '$db->result($result )');
$up->execute();
$dl = $db->prepare("delet e from sections where id in ?");
$dl->bindParam(1, '$ids');
$dl->execute();
}
catch (PDOException $e) {
$db->rollback();
echo "Woops: ".$e->getMessage;
}

you probably will want to do something different with you error
handling, but i just wanted to add a rollback as Rik pointed out...is
really the big plus to transactions.

Steve

Aug 1 '07 #6
First, thanks to all for your answers.
Second, lets see..
$query1 = 'START TRANSACTION';
$result1 = $db->query($query1) ;
if (!$result1) die("transactio n failed at step1");

$query2 = 'UPDATE sections SET position=positi on-%d WHERE position >
%d';
$result2 = $db->query(sprintf( $query2, count($id), $db-
>result($result )));
if (!$result2) die("transactio n failed at step2");

$query3 = 'DELETE FROM sections WHERE id IN %s';
$result3 = $db->query(sprintf( $query3, $ids));
if (!$result3) die("transactio n failed at step3");

$query4 = 'COMMIT';
$result4 = $db->query($query4) ;
if (!$result4) die("transactio n failed at step4");
echo 'Done...';

Logic, split main query into 4 queries.
Check one by one if they are made with success, if so proceed,
otherwise report failure.
Since data will only be saved if COMMIT is done, shoud step4 be like
the one above? If one of the first 3 steps fail, script will be
aborted and no data will be commited.
Im not sure this is the right way to use commit/rollback .. any ideias/
comments on this will be appreciated.

Thanks in advance guys.

Aug 1 '07 #7
Joćo Morais wrote:
First, thanks to all for your answers.
Second, lets see..
$query1 = 'START TRANSACTION';
$result1 = $db->query($query1) ;
if (!$result1) die("transactio n failed at step1");

$query2 = 'UPDATE sections SET position=positi on-%d WHERE position >
%d';
$result2 = $db->query(sprintf( $query2, count($id), $db-
>result($result )));
if (!$result2) die("transactio n failed at step2");

$query3 = 'DELETE FROM sections WHERE id IN %s';
$result3 = $db->query(sprintf( $query3, $ids));
if (!$result3) die("transactio n failed at step3");

$query4 = 'COMMIT';
$result4 = $db->query($query4) ;
if (!$result4) die("transactio n failed at step4");
echo 'Done...';

Logic, split main query into 4 queries.
Check one by one if they are made with success, if so proceed,
otherwise report failure.
Since data will only be saved if COMMIT is done, shoud step4 be like
the one above? If one of the first 3 steps fail, script will be
aborted and no data will be commited.
Im not sure this is the right way to use commit/rollback .. any ideias/
comments on this will be appreciated.

Thanks in advance guys.
How to use COMMIT/ROLLBACK is more of a SQL question and belongs in
comp.lang.mysql .

I don't think it's a good idea to use die() - is that what you want your
client to see? Additionally, I'm not sure die() will roll back your
transaction. Rather, you should handle it more gracefully, i.e.

(not tested)

$query1 = 'START TRANSACTION';
$result1 = $db->query($query1) ;
if ($result1) {
$query2 =
'UPDATE sections SET position=positi on-%d WHERE position %d';
$result2 = $db->query(sprintf( $query2, count($id),
$db-result($result) ));
if ($result2) {
$query3 = 'DELETE FROM sections WHERE id IN %s';
$result3 = $db->query(sprintf( $query3, $ids));
if ($result3) {
$query4 = 'COMMIT';
$result4 = $db->query($query4) ;
if ($result4) {
echo 'Done...';
}
else {
$db->query('ROLLBAC K');
echo "COMMIT failed";
}
}
else {
$db->query('ROLLBAC K');
echo "DELETE failed";
}
}
else {
$db->query('ROLLBAC K');
echo "UPDATE failed";
}
}
else {
echo "START TRANSACTION failed";
}
There are shorter ways to do it, but I tried to keep some semblance of
your code.

There are other things you will need to consider with COMMIT and
ROLLBACK. If you're not familiar with them, you need to discuss the
subject in a MySQL newsgroup such as comp.databases. mysql.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Aug 1 '07 #8
How to use COMMIT/ROLLBACK is more of a SQL question and belongs in
comp.lang.mysql .
Sorry but I dont agree.. the question is not how to use commit/
rollback in a general way, but with PHP. If I only used MySQL i
wouldnt have this problem at all.
I don't think it's a good idea to use die() - is that what you want your
client to see?
I just used die as an example of abort/report failure, I wont use this
in my final script.
>Additionally , I'm not sure die() will roll back your transaction.
For what I understood, (and I may be wrong), the data will only be
saved if COMMIT is done. So if one of the first 3 queries fail, no
COMMIT will be done, then no data will be saved.

Same occurs if first 3 queries are made with success, and the last one
fails.

There are other things you will need to consider with COMMIT and
ROLLBACK.
What things?

Aug 2 '07 #9
Joćo Morais wrote:
>How to use COMMIT/ROLLBACK is more of a SQL question and belongs in
comp.lang.mysq l.

Sorry but I dont agree.. the question is not how to use commit/
rollback in a general way, but with PHP. If I only used MySQL i
wouldnt have this problem at all.
Commit/Rollback are SQL commands, not PHP. If you need to learn more
about how to use them, you need a SQL newsgroup. Their use is not
dependent on PHP or any other language. They work the same from the
MySQL command line, for instance.

mysql_query(), etc. are PHP functions, and are appropriate for this group.
>I don't think it's a good idea to use die() - is that what you want your
client to see?

I just used die as an example of abort/report failure, I wont use this
in my final script.
>Additionally , I'm not sure die() will roll back your transaction.

For what I understood, (and I may be wrong), the data will only be
saved if COMMIT is done. So if one of the first 3 queries fail, no
COMMIT will be done, then no data will be saved.

Same occurs if first 3 queries are made with success, and the last one
fails.
As I said - I'm not sure on that. You need to check the MySQL
newsgroups as to what MySQL does in this case.
>
>There are other things you will need to consider with COMMIT and
ROLLBACK.

What things?
See comp.databases. mysql.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Aug 2 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3069
by: Rick | last post by:
I have been trying to run this MySQL query using PHP: SELECT id, trans_type, remote_addr, DATE_FORMAT(time, '%M %e, %Y %r') as time FROM transactions WHERE client_id = " . $client_id . " ORDER BY time asc and I am getting this error message: MySQL Error number: 1064: You have an error in your SQL syntax near 'ORDER BY time asc' at line...
1
1879
by: Abhi | last post by:
I am a general user of PHP and Mysql, not an expert. But I am having following problem: we have two tables called Users(uID, uName) Users_Groups (gID, uID, isAdmin) uID is Autoincreament in Users and Foreign key in UserGroups table. I am using transactions to insert a new user into User Table and immediately insert into Users_Groups during...
0
1692
by: Lodewijk Voge | last post by:
hello, MySQL lets CURRENT_TIMESTAMP tick on inside transactions. I'm wondering why? doesn't this violate the atomicity of transactions? thank you, Lodewijk
0
1650
by: Thomas Svenson | last post by:
I'm looking for any online resources/tutorials and such about transactions. Preferable for MySQL, but others will do. Other than that, is there any good book about transactions. Again preferable for MySQL. /T --
0
3312
by: Heikki Tuuri | last post by:
Hi! Many people have complained over years that Borland's dbExpress driver does not work with MySQL and transactions, because it disconnects from mysqld after each SQL statement. The postings below suggests that this problem might now be fixed by Borland. Best regards, Heikki Tuuri
5
2038
by: princevejita1 | last post by:
Hello I have problem with my MySQL server and transactions. I installed MySQL server 5.0.11 with MySQL administrator & MySql Query Browser on Win XP Prof. I would like to use transactions, so I have read the manual ana I thought I knew how to do it. I set the tables type to InnoDB (i can't use BDB) and change the default mysqld.exe to...
0
1244
by: Patrox | last post by:
hi ! in mysql doc it is stated that : "MySQL supports local transactions (within a given client connection) " ref : http://dev.mysql.com/doc/refman/5.1/en/transactional-commands.html but what happens if for instance 2 different users tries to modify same data in 2 different transactions in 2 different connections ? does the last one which...
12
4401
by: mantrid | last post by:
Hello Can anyone point me in the right direction for the way to read a text file a line at a time and separate the fields on that line and use them as data in an INSERT to add a record to a mysql table. Then read the second line in text file and repeat. Thanks for your time Ian
14
9010
realin
by: realin | last post by:
Hiya all, after my 1-2 weeks research i finally found a more consistent way to fire mysql queries in php i.e. transactions. I have two options to insert data in multiple tables :: 1) through procedures 2) through transactions Of course i am going to prefer is the 2 way i.e. transactions. I went thru all the manuals of which Ronald gave...
0
7619
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7930
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7681
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7983
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6290
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5228
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1229
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.