-1

I create a PHP that execute multiples query. I wanna make a transaction, because i need to save all the query if everything works ok, if not make a rollback. Is critical save all the data. I don't know how to make the transaction. I've been following that:PHP + MySQL transactions examples but it's not working.

This is my php:

<?php 

require_once __DIR__ . '/connect_to_database.php';

$db = new DB_CONNECT();

$response = array();

$horaSeleccionada= $_POST['horaSeleccionada'];
$fechaElegida= $_POST['fechaElegida'];
$data1FK= $_POST['data1FK'];
$reservado= $_POST['reservado'];
$usuarioFK= $_POST['usuarioFK'];
$nombreAuxiliar= $_POST['nombreAuxiliar'];
$fechaDeReserva= $_POST['fechaDeReserva'];
$telefonoAux= $_POST['telefonoAux'];
$anioHoy = (int) $_POST['anioHoy']; 
$filasAfectadas = 0;
$consultasRealizadas = 0;

$fecha = date_create($fechaElegida);
$anioAuxiliar = (int) $fecha->format("Y");

while($anioHoy == $anioAuxiliar){
    $fechaAGuardar = (String) $fecha->format('Y-m-d');

    $query_search = "insert into table(hora, data1FK, usuarioFK, reservado, fecha, nombreAuxiliar, fechaDeReserva, telefonoAux) values ('$horaSeleccionada','$data1FK','$usuarioFK','$reservado','$fechaAGuardar','$nombreAuxiliar','$fechaDeReserva','$telefonoAux')";

    $result = mysql_query($query_search) or die(mysql_error());

    if(mysql_affected_rows()>0){
        $filasAfectadas++;
    }
    else{
        $response["success"] = 0;
        $response["mensaje"] = "Hubo un error";
        break;
    }

    $consultasRealizadas++;

    date_add($fecha, date_interval_create_from_date_string('7 days'));
    $anioAuxiliar = (int) $fecha->format("Y");
}

if($consultasRealizadas == $filasAfectadas && $consultasRealizadas!=0){
    $response["success"] = 1;
    $response["mensaje"] = "Todo ok";
}
else { 
    $response["success"] = 0;
    $response["mensaje"] = "Hubo un error";
}
echo json_encode($response);
?>  

My database is in the same server, with phpmyadmin. Thanks for helping me!

Community
  • 1
  • 1
Federick Jons
  • 93
  • 1
  • 13
  • [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 06 '16 at 15:18
  • 1
    Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 06 '16 at 15:18
  • What table type are you using? Is it InnoDB? – Jay Blanchard May 06 '16 at 15:19
  • Could you give literal example for that using the example of the url that you give me? Sorry I'm too noob. – Federick Jons May 06 '16 at 15:20

1 Answers1

1

I'm going to get shat on for this answer but there is no reason for you to use transactional queries but before I can explain why, here are a few things I want to point out.

Firstly,

mysql has been deprecated since PHP 5.5. The newer and more kickass version of which, is mysqli. That said, there's no more reason to use mysql since mysqli is everything and more of mysql.

EDIT: What @Jay mentioned, this is not enough. You need to surround the variable in single quotes. Even better if you concatenate it too... Furthermore, if you know what sort of values you should be getting in a form, like username being alphanumeric, you can use preg_replace to ensure that only alphanumeric makes it to the code.

Secondly,

After implementing point #1, try escaping your post variables. Something like mysqli_real_escape_string works wonders in preventing any exceptions from popping up when you are running your insert query. In addition, the most important point of using mysqli_real_escape_string is that it prevents database injections entirely, therefore you should start using it immediately.

Thirdly,

Try not to use procedural and OOP together, it makes for a very messy code. Choose one, stick to it and if you want to change from one to another, do so with the whole page of code.

Lastly,

The reason why transactional queries like the one you linked exists, is for projects and codes that executes multiple queries, of which, you don't. In addition, if you do your string escaping well, all the queries will execute perfectly. The only time when you need transactional queries is when you are running mass inserts, updates or deletes where if one thing fu*ks up, it could potentially crash the whole system.

Your system doesn't seem to require that.

  • Could you give a little example with my php how to use correctly _POST with mysqli_real_escape_string , please. It's gonna help me to understand everything ok! – Federick Jons May 06 '16 at 15:27
  • 1
    Did you know that even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe? Better to recommend [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 06 '16 at 15:32
  • **TIL**. I usually concatenated the variables. Forgot to mention that. Also, @FederickJons, you can try something like `$horaSeleccionada = mysqli_real_escape_string($sqlcon, $_POST['horaSeleccionada']);` provided that `$sqlcon` is your `mysqli_connect()` connection. –  May 06 '16 at 15:33
  • **Hey!!! @JayBlanchard** I'm a big fan of procedural MySQLi since day 1! It's also pretty easy ya know... It's just that you do need to watch out for string escaping... –  May 06 '16 at 15:38
  • You can use prepared statements with procedural MySQLi. – Jay Blanchard May 06 '16 at 15:38
  • @LFlare Well, in the while loop I make several query, How can I now that everything is going to works great and some query is not gonna crash? Sorry for be too noob. – Federick Jons May 06 '16 at 15:42
  • @FederickJons, you can, instead of outputting `or die(mysqli_error())`, log into system log the query that failed to run like `error_log($query_search);` –  May 06 '16 at 15:47
  • @JayBlanchard, From day one, I've been using procedural statements, which is interesting because I also learnt how to escape strings perfectly too. It's just not easy to put into words for others to learn from. I do agree that prepared statements is easier to use but not necessarily safer compared to a properly escaped query... –  May 06 '16 at 15:49
  • @LFlare, please I have to contact you, send me and email to a.3710@hotmail.com, I have a particular question for you. – Federick Jons May 07 '16 at 16:58