how to save data with commas in mysql with php using pdo, save it in two when I insert it and delete the comma

1
                $objAdjEmail = new adjuntoEmail();
                //$objAdjEmail = $arrayObjAdjuntos[$indice];
                $objAdjEmail->setUrlArchivo($urlAdjunto);
                $objAdjEmail->setIdCorreo($pcorreo->getId());
                $objAdjEmail->guardar()

example after, step I want to save that, keep it in two register in the bd after step

    
asked by ruben 25.06.2016 в 01:37
source

3 answers

1

Because you do not try to escape the commas using str_replace , something similar to this:

<?php
 $tuVariable = "a,b,c";
 $tuVariable = str_replace(',','\,', $tuVarialbe);
 //Produce: a\,b\,c
?>

I hope you find it.

    
answered by 25.06.2016 в 01:49
0

I do it through a function to perform the insert. My function is:

function insertarBD($tabla,$campos, $valores){
  // Connect and create the PDO object
  $conn = dbConnect ();
  // Define an insert query
  $param = explode(",",$campos);
  $parametros = implode(",:",$param);
  $parametros = ":".$parametros;

  $insertSQL ="INSERT INTO " . $tabla . "(" . $campos . ") VALUES (" . $parametros .")";
  $sentencia = $conn->prepare("INSERT INTO " . $tabla . "(" . $campos . ") VALUES (" . $parametros .")");
  $arr_length = count($param);
  $parametros1 = explode(",",$parametros);
  $valores1 = explode("|",$valores);
  for($i=0;$i<$arr_length;$i++)
  {
      $sentencia->bindParam($parametros1[$i], $valores1[$i]);
  }
  $sentencia->execute();
  $conn = null;        // Disconnect
}

The parameters are separated by commas and the values by pipes (|), and that's how it works for me

    
answered by 25.06.2016 в 21:18
0

Question:

  

How to insert (write / save) data that contains commas in a database?

Answer:

  

There should be no problem when making the query with PDO whenever the parameters are good.

Example of construction and use

  

Prepare configuration constants for the database, in this case MySQL

define("DRIVER_SQL", "mysql");
define("DATABASE", "tu_base_de_Datos");
define("PORT", "3306");
define("HOSTNAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "1234");

define("URI", DRIVER_SQL . ":dbname=" . DATABASE . ";port=" . PORT . ";host=" . HOSTNAME);
  

Create class by applying a singleton pattern that returns an instance of PDO.

class DB
{
    private static $pdo;

    final private function __construct() 
    {
        // Constructor vacío y privado. 
    }

    function _destructor()
    {
        // Destructor que se encarga de cerrar la conexión y limpiar el puntero de PDO.
        self::$pdo = null;
    }

    private static function connect()
    {
        try 
        {
            if (self::$pdo != null) return self::$pdo;
            self::$pdo = new PDO(URI, USERNAME, PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            self::$pdo->setAttribute(PDO::ATTR_PERSISTENT, true);
            return self::$pdo;
        } 
        catch (PDOException $e) 
        {
            echo($e);
            return false;
        }
    }

} 
  

Add static methods to the class that use the PDO instance.

public static function insertUpdateDelete($sql, $parameters)
{
    try 
    {
        $rs = DB::connect()->prepare($sql);
        $rs = $rs->execute($parameters);
        return $rs != null && $rs != 0 ? true : false;
    } 
    catch (PDOException $e) 
    {
        print_r($e);
        return null;
    }
}

public static function select($sql, $parameters = null)
{
    try 
    {
        $rs = DB::connect()->prepare($sql);
        $rs->execute($parameters);
        return $rs->fetchAll(PDO::FETCH_ASSOC);
    } 
    catch (PDOException $e) 
    {
        print_r($e);
       return null;
    }
}
  

Use of the DB class created. The parameters are passed in an array.

include_once 'DB.php';

$query = "INSERT INTO tabla VALUES (?,?,?,?);";
$params = [ null, "STACK", "OVERFLOW", 8 ];

$rs = DB::insertUpdateDelete($query, $params);

echo $rs === true ? 'INSERT OK' : 'INSERT ERROR';

$query = "SELECT * FROM tabla WHERE age > ?;";
$params = [ 5 ];

$filas = DB::select($query, $params);

foreach ($filas as $fila) {
    foreach($fila as $columna) {
        // Hacer algo
    }
}
    
answered by 26.07.2016 в 11:36