problem with multi query PHP mysql

0

Hello people, I do not know why this code does not work for me (print "you can not create the date") and I have seen on the internet that multicary is done in this way, here I leave what I did, regards

  

* CLARIFICATION: this is the part of a method .. but I think it is not necessary to attach it completely

     

* the echoes are in test mode to see which conditional enters

if (!$this->conectar()){return 0 ;} // no se pudo conectar a la bd
 $i=1;
 $query="INSERT INTO partido (num_partido,num_fecha) VALUES ($i,$numfecha)";
for ($i=2;$i<=15;$i++)
     {$query.="INSERT INTO partido (num_partido,num_fecha) VALUES ($i,$numfecha)";}
  if ($this->mysqli->multi_query($query)) { echo "la fecha fue creada exitosamente";}
  else {echo "no se pudo crear la fecha :(";}
}
    
asked by fer 22.04.2017 в 03:41
source

1 answer

1

You can try this code:

EDIT:

I've tried the code and it works. With respect to the $query it would work around each variable with single quotes ' ' , assuming that to build all the SQL string uses double quotes: " .

But , to avoid surprises, it is better to send data of the type that are , if integers, integers, strings, strings. That is, if either of the two variables is an integer, better convert it to an integer:

$i = int ($i);
$numfecha = int ($numfecha);

And then, it's better to also build our string INSERT as we would in MySQL.

a. If the value is a string, enclose the variable with '$variable'

b. If the value is an integer, put it without ' ' around

If in your case num_partido and num_fecha are integers:

$query="INSERT INTO partido (num_partido,num_fecha) VALUES ($i,$numfecha);";

If num_partido and num_fecha are strings:

$query="INSERT INTO partido (num_partido,num_fecha) VALUES ('$i','$numfecha');";

If num_partido is string and num_fecha integer:

$query="INSERT INTO partido (num_partido,num_fecha) VALUES ('$i',$numfecha);";

If num_partido is integer and num_fecha string:

$query="INSERT INTO partido (num_partido,num_fecha) VALUES ($i,'$numfecha');";

Already with this, the rest of the code should not give you a problem:

<?php
//    $query="INSERT INTO partido (num_partido,num_fecha) VALUES ($i,$numfecha);";
//Crear la $query como se ha indicado arriba, según el caso 

// Ejecutar SQL
$i = 0;
if( $this->mysqli->multi_query( $query ) )
{
    do {
        $this->mysqli->next_result();
        $i++;
    }
    while( $this->mysqli->more_results() ); 
}

if( $this->mysqli->errno )
{
    die(
        '<h1>ERROR</h1>
        Consulta #' . ( $i + 1 ) . '</pre><br /><br /> 
        <span style="color:red;">' . $this->mysqli->error . '</span>'
    );
}
?>

Note

The contributions of the PHP Manual indicate several problems when using multi-query. I would recommend using PDO and prepared statements if possible, in addition, multiple values can be inserted using prepared statements.

    
answered by 22.04.2017 в 07:00