Mysql connects but does not display keys

Asked

Viewed 41 times

-3

Good morning

my code returns this error

Fatal error: Uncaught Error: Call to Undefined Function mysql_query() in /home2/minhap26/public_html/pages/lists.php:8 Stack trace: #0 /home2/minhap26/public_html/alimentacao/adegas.php(92): include() #1 {main} thrown in /home2/minhap26/public_html/paginas/listas.php on line 8

Below the original code without modifications.


include('../editar/adm_conexao.php'); // conect BD

$sql = "SELECT * FROM empresas WHERE ATIVE_LISTA = 'S' ORDER BY RAND()"; 
// tabela empresa, sinalizadas com S, em ordem aleatória na lista

$result = mysql_query($sql,$conexao)
or die($sql . '<br/>' . mysql_error($conexao) ) ;     
$row = mysql_num_rows($result); 

//die($sql);

if($row== 0){
echo '';}

$conexao->close();

// ----------------------------------

for($i=0 ; $i < $row; $i++);
{
  
$nome = mysql_result($resultado,$i,'nome');
$telefone = mysql_result($resultado,$i,'telefone');

    echo "<h2>$nome</h2>";
    echo "<h2>$telefone</h2>";  
}

1 answer

1


First point to note is that the mysql driver is obsolete, the correct is to use mysqli or PDO, I will show you a PDO connection, in your file php connection. place:

try {
    $conexao = new PDO("mysql:host=localhost; dbname=crudsimples", "root", "123456");
    $conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conexao->exec("set names utf8");
} catch (PDOException $erro) {
    echo "Erro na conexão:" . $erro->getMessage();
}

and in your query can be put:

  $sql = "SELECT * FROM tbestado";
  $resultado = $conexao->query($sql)->fetchAll();

foreach($resultado as $item){
 echo "<p>Nome: ".$item['nome']."<br>";
 echo "<p>Nome: ".$item['telefone']."<br>";
}

Note: the $item['somesomething'] corresponds to the column name of your table

  • Full PDO course: https://www.youtube.com/watch?v=C92cScfsFW4&list=PLYGFJHWj9BYqSXzSfHGd46yipCrkjC8AD

  • Crud Full PDO: https://www.youtube.com/watch?v=rYFIa8oO08Y&list=PLbnAsJ6zliduRkxrkVjB_acpNt9jN68w9&index=6 NOTE: Class 1 to 10

  • More about modern PHP: http://br.phptherightway.com/

  • 1

    Thank you very much Thalles. I succeeded. I will make some adaptations in the code. Big hug.

Browser other questions tagged

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