How to use an Array array and declare variables

2

Hello I'm just new to PHP I want to declare variables with the result of a while of an Array

<?php 
include("conexion.php");
$query4= mysqli_query($conexion,"SELECT refprofesor FROM asigna_materia 
WHERE refgrupo='3-A' AND refcarrera='09TICSI'");
while($row = mysqli_fetch_array($query4, MYSQLI_NUM))
{
echo $row[0].'<br>';
echo $row[1].'<br>';
}
$ejemplo1 = $row[0];
$ejemplo2 = $row[1];
?>

This is the Result Result

and this is the image of the database

BD

    
asked by gmp_97 18.08.2018 в 05:52
source

3 answers

0

The problem is that the variable $ row [1] does not exist. This is due to the .iteration within the while, which each time takes one of the results from the base, which is the one that prints with $ row [0]. The correct way to create an array with all the values would be:

while ($ row = mysqli_fetch_array ($ query4, MYSQLI_NUM)) { $ results [] = $ row [0]; }

This creates the keys of the array with an autoincremental value and assigns it the value of each row. Greetings!

    
answered by 18.08.2018 / 06:30
source
1

The error is simple, the query currently only returns one column, but you try to access a second column

echo $row[0].'<br>'; // correcto
echo $row[1].'<br>';  //incorrecto, indice no válido

Also, outside of while it would not make sense to access $row , the last two lines you must delete them.

Final Code

include("conexion.php");
$query4= mysqli_query($conexion,"SELECT refprofesor FROM asigna_materia 
WHERE refgrupo='3-A' AND refcarrera='09TICSI'");
while($row = mysqli_fetch_array($query4, MYSQLI_NUM))
{
   echo $row[0].'<br>';
}

It would not be convenient to have variables within while since with a query, we will not know exactly how many records will return, it will work as long as a single record is obtained (it would not need a while) .

For this, a array would be appropriate if you want to obtain the result and not print it directly.

$resultado = [];
while($row = mysqli_fetch_array($query4, MYSQLI_NUM))
{
   $resultado[] = $row;
}
// Al terminar el while
//Aquí  su variable $resultado, tendrá todos los registros devueltos
    
answered by 18.08.2018 в 05:55
-1

Try to name it

$row['refprofesor'];

would be

while($row = mysqli_fetch_array($query4, MYSQLI_NUM)) {
    echo $ejemplo = $row['refprofesor']."<br>";
}
    
answered by 18.08.2018 в 08:20