Variable not defined in SQL query for PHP

0

I'm trying to send a query with the information of a table in MySQL to an array in PHP, but I'm encountering the following error when I try to print an array position:

  

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

Here is 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 that I tried to execute and that the above error occurred was:

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

I'm sorry if you ever asked about this error here in the community, but I looked at several sites and could not find the solution.

    
asked by anonymous 20.06.2017 / 18:10

1 answer

0

I was able to solve the problem! I used the mysqli functions instead of mysql , plus some changes. Here 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);
        ?> 
    
20.06.2017 / 19:45