Problem with While (mysql_fetch_assoc)

0

Hi, I'm a programmer who is just starting and I have a problem with While, I'm rescuing a data from an SQL table, so all right, in fact if I do a print_r before the While rescues me without any problem, but when going through the while it does not show me any data.

this is my code:

            $result = mysql_query($sSQL, $conexion) or die(mysql_error());

            if($row = mysql_fetch_assoc($result)){

            $tipo = trim($row["tipo"]);

            if ($tipo == "MT")
            {

                while ($row = mysql_fetch_assoc($result))
                {
                  print_r($row);

Nor does it show me an error in that line of code ... does anyone know what my error may be?

    
asked by Samuel 14.12.2018 в 14:04
source

1 answer

0

Try putting this in the while:

while($row = $result->fetch_assoc()){
}

Also because you put a die () in the variable $ result, theoretically the variable die () you should, to put it if it is not connected to the database, that is, in the variable $ connection. I propose a possible solution, and it is this structure, which I use and it always works for me:

<?php
   $conexion = new mysqli("localhost","user","passwd","DB");
   if(!conexion){
      die("error DB: ".$conexion->connect_error);
   }
   $consulta = "SELECT * FROM table";
   $result = $conexion->query($consulta);
   if($result->num_rows > 0){
      while($row=$result->fetch_assoc()){
        if($row['tipo'] == "MT"){
              print_r($row['tipo']);
        }
      }
   }
?>

What this fragment of condigo would have to do, is that if in the type field of the DB there is a cell with the content "MT" what it will do is print all the values that are in the "type" field, if what you want is to print the entire database you would have to replace'print_r ($ row ['type']) 'to this:

echo "tipo: ".$row['tipo'];
echo "campo2: ".$row['campo2'];
...

So all you want. Obviously you can customize the way you want it to look like.

    
answered by 14.12.2018 / 14:55
source