Transform loop while in foreach loop

1

I need to convert it to the foreach

format
$query = "SELECT id_prod FROM productos WHERE nombre_prod='$nombre' OR descrip='$caract' "; 
$result = mysqli_query($con, $query);

while ($mostrar = mysqli_fetch_array($result)) { 
    $id_producto = ($mostrar['id_prod']); 
}
    
asked by alex tiberiu Telegaru 21.01.2018 в 11:06
source

1 answer

0

You can not list using mysql_fetch_array without using a while or a for because mysql fetch array works with records one by one and not with an array of records that is necessary to work with foreach. If you need the foreach here, I show you an adaptation to your code:

$query = "SELECT id_prod FROM productos WHERE nombre_prod='$nombre' OR descrip='$caract' "; 
$result = mysqli_query($con, $query);
$registros = array();
while ($mostrar = mysqli_fetch_array($result)) { 
    $registros[] = $mostrar; 
}

foreach($registros as $mostrar){ 

    $id_producto = $mostrar['id_prod'];

}
    
answered by 21.01.2018 в 13:13