Help my transaction in php pdo is sometimes done and sometimes not

1

I am carrying out a transaction, what I do first is a post of values obtained from a form of both arrays and variables, sometimes the values are inserted correctly in the table orders and detail, in other occasions this does not occur.

<?php
include_once 'resource/session.php';

          if ($_SESSION['capturar_pedidos'] == 1){   

//including the database connection file
include_once("resource/Database.php");

if(isset($_POST['Submit'])) {   
                $cliente = $_POST['cliente'];
        $orden_de_compra = $_POST['orden_de_compra'];



            $productos= (is_array($_POST['productos'])) ? $_POST['productos'] : array();
        $unidad= (is_array($_POST['unidad'])) ? $_POST['unidad'] : array();

            $cantidad= (is_array($_POST['cantidad'])) ? $_POST['cantidad'] : array();

            $fecha_de_embarque= (is_array($_POST['fecha_de_embarque'])) ? $_POST['fecha_de_embarque'] : array();

            $notas = (is_array($_POST['notas'])) ? $_POST['notas'] : array();
            $etiquetado= (is_array($_POST['etiquetado'])) ? $_POST['etiquetado'] : array();





    if(empty($cliente) || empty($productos) ||empty($unidad) ||empty($cantidad) || empty($fecha_de_embarque)  || empty($etiquetado) ) {

        if(empty($cliente)) {
            echo "<font color='red'>Campo cliente esta vacio.</font><br/>";
        }



        if(empty($productos)) {
            echo "<font color='red'>Campo producto esta vacio.</font><br/>";
        }

        if(empty($unidad)) {
            echo "<font color='red'>Campo unidad esta vacio.</font><br/>";
        }

        if(empty($cantidad)) {
            echo "<font color='red'>Campo cantidad esta vacio.</font><br/>";
        }

        if(empty($fecha_de_embarque)) {
            echo "<font color='red'>Fecha de embarque esta vacio.</font><br/>";
        }


        if(empty($etiquetado)) {
            echo "<font color='red'>Campo etiquetado esta vacio.</font><br/>";
        }



        //link to the previous page
        echo "<br/><a href='javascript:self.history.back();'>Regresa</a>";
    } else { 
        // if all the fields are filled (not empty) 
        try {
    /* First of all, let's begin a transaction */
                if(empty($orden_de_compra)){
                 $db->beginTransaction(); 
         $sql = "select orden_de_compra from clientes where cliente=:cliente"; 
$result = $db->prepare($sql); 
$result->bindparam(':cliente', $cliente);


$result->execute(); 
$orden_de_compra = $result->fetchColumn();  
              $arreglo = explode("-", $orden_de_compra);
                    $numero_sin_ceros =(int) $arreglo[1] + 1;

                    $numero_sin_ceros = str_pad((string)$numero_sin_ceros, 4, '0', STR_PAD_LEFT);
$orden_de_compra_nuevo  = $arreglo[0] . '-'.$numero_sin_ceros ;   


    $sql = "UPDATE clientes SET orden_de_compra=:orden_de_compra_nuevo WHERE orden_de_compra =:orden_de_compra_actual";


$result = $db->prepare($sql); 
$result->bindparam(':orden_de_compra_nuevo', $orden_de_compra_nuevo);
$result->bindparam(':orden_de_compra_actual', $orden_de_compra);

$result->execute();      
    }

else{
                  $db->beginTransaction(); 


}

            //return a string of all the array elements
$string_productos = implode("[x]", $productos);
             $string_fechas = implode("[x]", $fecha_de_embarque);

             $string_unidades = implode("[x]", $unidad);
             $string_cantidades = implode("[x]", $cantidad);
             $string_notas = implode("[x]", $notas);
             $string_etiquetados = implode("[x]", $etiquetado);

$longitud_productos = strlen(utf8_decode($string_productos));
 $longitud_fechas = strlen(utf8_decode($string_fechas));
  $longitud_unidades = strlen(utf8_decode($string_unidades));
             $longitud_cantidades = strlen(utf8_decode($string_cantidades));
  $longitud_notas = strlen(utf8_decode($string_notas));
  $longitud_etiquetados = strlen(utf8_decode($string_etiquetados));

if($longitud_productos <= 255 and $longitud_fechas <= 255 and $longitud_unidades <= 255 and $longitud_cantidades <= 255 and $longitud_notas <= 255 and $longitud_etiquetados <= 255) {


}
            else{
    $string_productos = "Para ver los productos ve a la seccion detalle de pedido";
             $string_fechas = "Para ver las fechas ve a la seccion detalle de pedido";

             $string_unidades = "Para ver las unidades ve a la seccion detalle de pedido";
             $string_cantidades = "Para ver las cantidades ve a la seccion detalle de pedido";
             $string_notas = "Para ver las notas ve a la seccion detalle de pedido";
             $string_etiquetados = "Para ver los etiquetados ve a la seccion detalle de pedido";            


            }

    // A set of queries; if one fails, an exception should be thrown
   $sql = "INSERT INTO pedidos(cliente, orden_de_compra, productos, fechas, unidades, cantidades, notas, etiquetados) VALUES(:cliente, :orden_de_compra, :productos, :fechas,:unidades, :cantidades, :notas, :etiquetados)";

            $insertStmt = $db->prepare($sql);

        $insertStmt->bindparam(':cliente', $cliente, PDO::PARAM_STR);
         $insertStmt->bindparam(':orden_de_compra', $orden_de_compra, PDO::PARAM_STR);
         $insertStmt->bindparam(':productos', $string_productos, PDO::PARAM_STR);
         $insertStmt->bindparam(':fechas', $string_fechas, PDO::PARAM_STR);
         $insertStmt->bindparam(':unidades', $string_unidades, PDO::PARAM_STR);
         $insertStmt->bindparam(':cantidades', $string_cantidades, PDO::PARAM_STR);
         $insertStmt->bindparam(':notas', $string_notas, PDO::PARAM_STR);
         $insertStmt->bindparam(':etiquetados', $string_etiquetados, PDO::PARAM_STR);


$insertStmt->execute();

$sql = "INSERT INTO detalle(orden_de_compra, cliente, producto, unidad, cantidad , fecha_de_embarque, notas, etiquetado) VALUES(:orden_de_compra,:cliente, :producto, :unidad, :cantidad , :fecha_de_embarque, :notas, :etiquetado)";

$insertStmt = $db->prepare($sql);

         $i=0;
    foreach ($productos as $producto) {


        $insertStmt->execute( array('orden_de_compra' => $orden_de_compra,'cliente' => $cliente,'producto' => $producto,'unidad' => $unidad[$i],'cantidad' => $cantidad[$i] ,'fecha_de_embarque' => $fecha_de_embarque[$i] ,'notas' => $notas[$i] ,'etiquetado' => $etiquetado[$i] ));
                        $i++;





    }                  

        // Alternative to above bindparam and execute
        // $query->execute(array(':name' => $name, ':email' => $email, ':age' => $age));
    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}











                $URL="index.php";
echo "<script type='text/javascript'>document.location.href='{$URL}';</script>";
echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '">';


    }
}


          }
?>
</body>
</html>
    
asked by Daniel Treviño 01.11.2017 в 19:50
source

1 answer

0

The transaction worked perfectly towards the post with values taken from a select, the latter was obtained from the database and I realized that it eliminated double blanks, which I left by accident when registering some clients, which I did it was to use in the where the id instead of the varchar name of the client:

  <select required name="id_cliente">
 <?php
        echo '<option value="">Selecciona un cliente</option>';

                    $sql = "Select id_cliente, cliente from clientes";

    $query = $db->prepare($sql);
    $query->execute();
       while($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo '<option value= "'.$row['id_cliente'].'">'.$row['cliente'].'</option>';
       }
     ?>
 </select>
    
answered by 02.11.2017 в 06:08