It shows you a single row because when you execute a query with query
, the data comes in an object that must be traversed row by row (most recommended way especially when you expect a lot of data, to safeguard the memory) or emptied suddenly elsewhere (when few rows are expected and a method is available for it). Either way, you have to resort to some method to retrieve or display the data (the most common are the different fetch_*
methods that exist).
These fetch_*
methods are used to traverse the result set row by row , returning a numeric, associative array or both (depending on which one you use).
When you apply the method outside of a loop, you only get the first row, because you do not keep moving the result set to the next row (this is what is currently happening with your code).
So, to empty the data in an array for example, you must apply the fetch_*
of your choice within a loop (the most used is while
), which will allow you to pass from one row to another. If you do this, every step of the loop will fill the formularioRegistroMuestra
array with each row of the result set the way you expect:
$sql="SELECT id_muestra FROM lacem_obras_civiles.msa_registro_muestra where id_ott=$ott;"
if($resultadoMuestra = $mysqli_obra->query($sql)) {
while ($row=$resultadoMuestra->fetch_assoc()){
/*
*Aquí se irá llenando el array con cada fila
*y al usar fetch_assoc cada valor quedará asociado
*al nombre de la columna
*Nótese que se pone [] después del nombre de tu variable
*/
$formularioRegistroMuestra[]=$row;
}
print_r($formularioRegistroMuestra);
}
NOTE: That I used fetch_assoc
instead of fetch_array
, because the latter creates you both a numeric array and associative by
each column. You will then have twice each value of form
unnecessary (as in fact it shows your var_dump
). By using fetch_assoc
you can access each value using
your column name, for example:
$formularioRegistroMuestra["id_muestra"]
You can also use
fetch_row
, and access using the index for each column. In my judgement
fetch_assoc
is much clearer.
WARNING ON SECURITY : The query you are using is highly vulnerable to SQL injection attacks. It is convenient that
implementes queries prepared to prevent that serious hole
security in your code.