Variable not defined in SQL query for PHP

Asked

Viewed 111 times

0

I am trying to send an array in PHP, a query with the information of a table in Mysql, but I am finding the following error when I try to print an array position:

"Notice: Undefined variable: array in C: xampp htdocs Domiritmo Inicio.php on line 104"

Follow my code below:

<?php                  
  $sql = "SELECT msgNAutor, msgTAutor, msgTipo, msgTopicos, msgTexto, msgData FROM tbmensagem";
  if ($con->query($sql) === TRUE) {
    $result = mysql_query($sql);
    $array = array();
    if (!$result) {
      die("Error: ".mysql_error());
    }               
    while($row = mysql_fetch_assoc($result)) {
      $array[] = $row;
    }   
  }                                           
?>

The position of the array I tried to run and the above error occurred:

<?php
  print_r($array[0]['msgNAutor']);
?>

I’m sorry if I’ve been asked about that mistake here in the community, but I’ve looked at several websites and I can’t find the solution.

1 answer

0

I managed to solve the problem!
I used the functions mysqli instead of mysql, in addition to some amendments.
Below is the new code:

<?php                                 
          $sql = "SELECT msgNAutor, msgTAutor, msgTipo, msgTopicos, msgTexto, msgData FROM tbmensagem";             
            $result = mysqli_query($con, $sql);
            $array = array();              
            $index = 0;                                                     
            while($row = mysqli_fetch_assoc($result)) {
                $array[$index] = $row;
                $index++;
            }
          mysqli_free_result($result);
          mysqli_close($con);
        ?> 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.