mysqli_fetch_assoc in object-oriented style

2

I'm getting values from an associative array

  $datos = "";
  $array = array(1, 2, 3, 4);
  foreach ($array as $valor => $dato) {
    $datos = $datos . $dato . ",";
  }

  $app = rtrim($datos, ",");
  echo $app;

Result: 1,2,3,4

Now it's strange I do not understand what is happening in a procedure in object-oriented style in MySQLi it only shows me one result and the rest ignores them.

  $stmt = $con->prepare("SELECT id, notice, tag FROM news WHERE id in (?)");
  $stmt->bind_param('i',$app);
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($id, $notice, $tag);

  while ($stmt->fetch()) {
    echo '<div class="content-notice">
             <h1>'.$notice.'</h1>
             <span>'.$tag.'</span>
         </div>';
  }

I tried changing the integer (i) by string (s) but it gives the same result it only shows one result ...

On the other hand, in a different procedure without object orientation there if you print the 4 results.

$sql = "SELECT * FROM news WHERE id in ({$app})";
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($query)){
    echo '<h1>'.$row['notice'].'</h1>';
}

Can you explain what is happening?

    
asked by Oscar 26.11.2017 в 22:37
source

1 answer

2

Oscar tries this code.

  • $arrIN is an array with the ids you want to use as criteria in IN...
  • From this array, position markers ? will be created that the prepared query will take.
  • A $strTipos string will also be created with the data types for each one, in this case I assume they are of the integer type, so the i .
  • We will use the operator of the three points (PHP 5.6+), called List of variable length arguments to make the dynamic binding of each type and its respective value.

The code would look something like this:

$arrIN=array(1,2,3,4); //Cámbialo por tu array. DEBE SER UN ARRAY
$strMarcas  = str_repeat('?,', count($arrIN) - 1) . '?';
$strTipos = str_repeat('i', count($arrIN));
$strSQL="SELECT id, notice, tag FROM news WHERE id in ($strMarcas)"; //Ningún peligro de Inyección aquí... :)

$stmt=$con->prepare($strSQL);

$stmt->bind_param($strTipos, ...$arrIN);
$stmt->execute();

$stmt->store_result();
$stmt->bind_result($id, $notice, $tag);

while ($stmt->fetch()) {
    echo '<div class="content-notice">
             <h1>'.$notice.'</h1>
             <span>'.$tag.'</span>
         </div>';
}

My final recommendation is to move to PDO. All this roll is due to only one thing, mysqli does not support passing the parameters directly in execute ! With PDO this would have been solved with one or two lines of code. However, look at all the returns that need to be given with mysqli .

You can read about this interesting article published on phpdelusions.net: Why mysqli prepared statemens are so hard to use? - ( Why are prepared queries so difficult to use in mysqli? )

    
answered by 27.11.2017 / 00:26
source