Pass a variable instead of a where & variable name

0

My query is the next. you can put a variable within a query variable $ size is the one I want to put inside my query inside the while

 $ok = "false";
    $codigo = $datos[0];
    $talla = $datos[1];
    $existencia = $datos[2];

    $sql = "SELECT COUNT(*) total_registro FROM Prueba " . "WHERE codigo_articulo='" . $codigo."'";
    $rs = $this->consulta($sql);

    while ($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) {
        $total_registro = $row["total_registro"];
        error_log($total_registro);
        if ($total_registro == 0) {
            $sql = "insert into prueba("
                . "codigo,"
                . "$talla"
                . ") "
                . "values(?,?)";
            error_log(&sql)
            $stmt = $this->consulta_prepared($sql);
            $stmt->bind_param("ss", $datos[0], $datos[2]);
            $stmt->execute();
            if ($stmt) {
                $ok = "true";
            }
        } else {


        }
    }
    $arr = array('ok' => $ok);
    return ($arr);
    
asked by Cesar 17.02.2017 в 21:37
source

2 answers

0

The way to add a variable to a query is to concatenate correctly said variable, for your example it will be

$sql = "insert into prueba(codigo,".$talla.") values(?,?)";
    
answered by 18.02.2017 / 00:14
source
0

Variables within PHP strings work differently if you enclose your string with single quotes if you enclose them with double quotes.

Single quotes

With the single quotes you are forced to close your string and concatenate the command / variable you want to use:

$variable_de_prueba = 'roja';

echo 'Prueba de variable $variable_de_prueba solo como muestra';
//Prueba de variable $variable_de_prueba solo como muestra

echo 'Prueba de variable ' . $variable_de_prueba . ' solo como muestra';
//Prueba de variable roja solo como muestra

Double quotes

Double quotes, on the other hand, allow you to enter the variables directly in the string without having to end it and concatenate it:

echo "Prueba de variable $variable_de_prueba solo como muestra";
//Prueba de variable roja solo como muestra

echo "Prueba de variable " . $variable_de_prueba . " solo como muestra";
//Prueba de variable roja solo como muestra

Taking this into account, the code:

$sql = "insert into prueba(" . "codigo," . "$talla" . ") " . "values(?,?)";

You are concatenating strings in double quotes so if you are including that variable in your query . Other ways to write the same query are:

$sql = "insert into prueba(codigo,$talla) values(?,?)";
$sql = "insert into prueba(codigo," . $talla . ") values(?,?)";
$sql = 'insert into prueba(codigo,' . $talla . ') values(?,?)';
    
answered by 18.02.2017 в 02:50