0

I noticed something today and thought that it could cause huge problems in the future. Let me explain;

Example; I have a like this

$query1 = "INSERT INTO table1(col1,col2,col3) VALUES('$col1','$col2','$col3')";
$query2 = "INSERT INTO table2(col1,col2,col3) VALUES('$col1','$col2','$col3')";
$query3 = "UPDATE table3 SET col1 = '$col1' WHERE id='$id'";

if (mysql_query($query1) && mysql_query($query2) && mysql_query($query3)) {
    echo "successful message";
}
else {
    echo mysql_error();
}

When this happens, non-error queries are processed. So if one of them fails, the statistics screen is wrong.

What I want to do;

If there is an error in one of the queries, none should be processed. How can i do that?

Ali Heikal
  • 3,790
  • 3
  • 18
  • 24
  • 2
    have a read of [this](https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).. and [this](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – treyBake Jan 03 '20 at 13:41
  • It should already be the case because of the use of `&&` operator. If first one returns a falsey value, no need to evaluate the other alternatives.. (also +1 on @treyBake 's comment) – Kaddath Jan 03 '20 at 13:42
  • 1
    @user3783243 you're probably right, you could elaborate your comment to an answer then.. – Kaddath Jan 03 '20 at 13:49
  • @user3783243 Sorry I deleted it, and I mixed it up with `mysqli_multi_query();` I shouldnt comment `mysqli` procedural is strange to me love `pdo` .lol –  Jan 03 '20 at 14:06
  • 1
    **The `mysql` PHP extension is dead** -- Don't use the [`mysql_*()` PHP functions](http://php.net/manual/en/function.mysql-connect.php) in new code. They are old, deprecated since PHP 5.5 and completely removed in PHP 7. Use [`mysqli`](http://php.net/manual/en/book.mysqli.php) or [`PDO_mysql`](http://php.net/manual/en/ref.pdo-mysql.php) instead. Read the answers to [this question](https://stackoverflow.com/q/12859942/4265352) to learn more about why and how. – axiac Jan 03 '20 at 14:09

1 Answers1

3

What you want to achieve can't be done using the mysql_ driver (another reason to update). With PDO or mysqli you can use a transaction to achieve this behavior. You also should take advantage of their prepared statements as well.

  1. https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
  2. https://www.php.net/manual/en/pdo.prepared-statements.php

Then once you have that done, with whichever driver you choose (PDO is preferable, IMO), See:

  1. https://www.php.net/manual/en/mysqli.begin-transaction.php
  2. https://www.php.net/manual/en/pdo.begintransaction.php
user3783243
  • 5,368
  • 5
  • 22
  • 41