How to use double and single quotes in a string in PHP to go to MYSQL?

0

I have this text saved in this variable:

$variable: Tuberia de acero al carbono Ø4" sch 40 ;

$idDetalle = 1;

What I want is to insert this in a column of a MYSQL table but it does not respect the quotes ("") that I put.

$cadena_insertar .= '( " ' . $idDetalle . '  "," ' . $variable. ' ")';

I want MYSQL to receive it this way:

insert into detalle (idDetalle,variable) values (1,Tuberia de acero al carbono Ø4" sch 40)
  

But MYSQL receives it as if it had sent 3 data since the   double quote ("") that is between Ø4 and sch divides it:

insert into detalle (idDetalle,variable) values (1 , Tuberia de acero al 
carbono Ø4" , sch 40)

How could I put quotation marks so that variable is not split?

    
asked by Luis 01.08.2018 в 21:36
source

3 answers

5

I recommend that for a simpler understanding of the string you use a statement with parameters:

//Escapamos el caracter " como \"
$variable= "Tuberia de acero al carbono Ø4\" sch 40 ;";

$idDetalle = 1;

//No conozco los detalles de tu conexion, asumire que tenes una variable $conn

//Los signos de interrogacion es donde iran los parametros
$sql = "INSERT INTO detalle (idDetalle,variable) VALUES (?,?);";

//Preparamos la sentencia
$stmt = $conn->prepare($sql);

//Asociamos los parametros a las variables, 
//La cadena "is" significa que el primer parametro sera un entero i
//y el segundo parametro sera una cadena s
$stmt->bind_param("is",$idDetalle,$variable);

//Ejecutamos la sentencia
$stmt->execute();

//Cerramos la sentencia
$stmt->close();
    
answered by 01.08.2018 / 22:28
source
0

Try to insert the insertion code so

$cadena_insertar .= '( " ' . $idDetalle . '  ",".chr(34).$variable.chr(34).")';

the chr (34) is an ascii character, the 34 that is the one of my answer is comillas ("), I put this answer because once I had the same problem and this I solve it

    
answered by 01.08.2018 в 22:05
0

Another way can be with Interpolated Chains

When the string starts with double quotes, the variables can be passed in the same string and replaced by their values at run time

$string0 = 'PHP';
$string1 = 'Cadenas';
echo "$string0 acepta $string1 interpoladas";
//output: PHP acepta Cadenas interpoladas

So you can do something like

$sql = "INSERT INTO detalle (idDetalle,variable) VALUES ($idDetalle ,$variable);";
    
answered by 02.08.2018 в 00:18