Transactions with PDO and Singleton

0

I have the pattern singleton and a class ticket :

public function registrar(){
//me conecto a la bd
$conexion = Conexion::singleton_conexion(); 
 try{

  $conexion->beginTransaction();
  $queryid="select comprobante from identificadores;"; 
  $array=$conexion->query($queryid);
 foreach($array as $a){
   $id = $a['comprobante'];
  }

  $qnuevoid="UPDATE identificadores SET comprobante=".++$id.";";
  $conexion->query($qnuevoid);

    $queryticket="insert into despensa.ticket (idticket, fecha, total,vuelto) 
    values (".$id.",'".$this->fecha."',56,88);";
    $conexion->query($queryticket);

   $conexion->commit();
  }catch(Exception $e){
  $conexion->rollBack();
   echo "Fallo: " . $e->getMessage(); 
  }
  }
}

The fact is that I want to know how to access the value of a select mysql query with PDO to avoid this:

foreach($array as $a){
   $id = $a['comprobante'];
}

I think it's not the right way!

    
asked by Caruso 29.04.2018 в 17:33
source

1 answer

0

Probably in your method singleton_conexion you have not provided the option fetch_style in this case the call will return the default option PDO::FETCH_BOTH which is an array indexed by column name. In the case that I understand you want the call to return an anonymous object with property names that correspond to the names of the columns you will have to provide as option PDO::FETCH_OBJ .

Ex:

function singleton_conexion()
{
    // asigna opciones para la conexion PDO. en este caso asignamos el modo fetch al objeto,
    // "objeto", esto significa el resultado sera objeto en vez de array, como: $result->comprobante !
    // en caso contario, el modo  FETCH_ASSOC o sin especificar el modo devolvera: $result["comprobante] !
    $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);

    $this->db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS, $options);
}

Here you have more examples.

    
answered by 30.04.2018 в 00:16