Return database data to PHP page not returning data

Asked

Viewed 2,890 times

0

Good morning, you guys.

I have a page (index.php) that needs to return the database data to it. I have a . php (connection.php) that connects to the database, see:

$_SG['servidor'] = 'localhost';    // Servidor MySQL
$_SG['usuario'] = 'root';          // Usuário MySQL
$_SG['senha'] = 'XXXX';                // Senha MySQL
$_SG['banco'] = 'projetoqa';            // Banco de dados MySQL
$_SG['paginaLogin'] = '../login.php'; // Página de login
$_SG['tabela'] = 'usuarios';       // Nome da tabela onde os usuários são salvos
// ==============================
// ======================================
//   ~ Não edite a partir deste ponto ~
// ======================================
// Verifica se precisa fazer a conexão com o MySQL
if ($_SG['conectaServidor'] == true) {
  $_SG['link'] = mysql_connect($_SG['servidor'], $_SG['usuario'], $_SG['senha']) or die("MySQL: Não foi possível conectar-se ao servidor [".$_SG['servidor']."].");
  mysql_select_db($_SG['banco'], $_SG['link']) or die("MySQL: Não foi possível conectar-se ao banco de dados [".$_SG['banco']."].");
}
// Verifica se precisa iniciar a sessão
if ($_SG['abreSessao'] == true)
  session_start();

The connection I know is OK, because I already used another function of the code to insert content in it. However, on the index.php page where I need to display results, I can’t. See the code:

<?php

        // Inclui o arquivo com o sistema de segurança
        require_once("php/conexao.php");

        // executa a query 
        $busca = "SELECT titulo FROM questoes";

        $resultado = mysql_query($busca);

        // Encerra a conexão
        mysql_close();
    ?>

And where the result should be displayed:

<li><a href="#"><?php $resultado ?></a></li>

Just stay blank! Nothing shows up. What’s wrong with this case? I looked at some forums and other methods of how to perform the search, I couldn’t find it. The data in question that returns there, is just a title. For example "How to play video game?"

Thank you!

  • OMG Buddy, I get a few headaches just trying to read your code, because you’ve defined the Arrays in a somewhat laborious way, even though the technique is outdated, inefficient, and not recommended, you’ve made it even more complicated. Try putting a echo $resultado, I need to take a closer look at your code.

  • I will try. Sorry for the disorganization of the code, really not only new in PHP and SQL, I’m still just messing with the code without organizing it yet.

  • 1

    Try a var_dump($result) to see what is being returned in the variable and a hint, the mysql_* functions are deprecated from php 5.5, try replacing with PDO or mysqli_*.

2 answers

1

You must use a loop to display the query data.

First, make sure your query is actually correct.

if (!$resultado ) {
    //se a consulta está incorreta, mostra erro
    die( "Erro na consulta: " . mysql_error() );<br>
}else{
    //você precisa utilizar um laço para pegar os resultados desta query
    //porque o metodo mysql_query() traz outros atributos além dos dados do banco 
    while ($row = mysql_fetch_assoc($result)) {
        //echo $row['campoDoBanco'];
   }
}

1


Hello, first of all I would like to recommend you a PHP upgrade to a recent and stable version. Nowadays almost nobody uses the MySQL because it was officially unpublished and is unsafe, recommending then the MySQLi.

Answer

<?php

//Login do SQL
DEFINE("HOST", "localhost"); 
DEFINE("USR", "usuario");
DEFINE("PWD", "senha");
DEFINE("BD", "banco_de_dados");
// Ou $db = array("host"=>"localhost", "usr"=>"usuario", "pwd"=>"senha", "bd"=>"banco_de_dados");
// Ou $host = "localhost"; $usr = "usuario"; $pwd = "senha"; $bd = "banco_de_dados";

//Conexao
$conexao = mysqli_connect(HOST, USR, PWD, BD);
// $conexao = mysqli_connect($db["host"], $db["usr"], $db["pwd"], $db["bd"]);
// $conexao = mysqli_connect($host, $usr, $pwd, $bd);


if(mysqli_connect_errno()){
    //Encerra a conexao e mostra a mensagem com o erro    
    die("Erro: " . mysqli_connect_error());
}

// Preparo da consulta SQL

$sql = mysqli_query($conexao, "SELECT x FROM z");
if(!$sql){
    die("Erro: zzz");
}
//Looping para retornar os valores
while($resultado = mysqli_fetch_assoc($sql)){
    // Ou echo "Nome: " . $resultado["nome"];    
    ?>
    <!--
    Algum HTML aqui
    ex.:
    !-->
    <b>Nome: </b><?php echo $resultado["nome"]; ?>
    
    <?php
}

mysqli_free_result($sql);

mysqli_close($conexao);

?>

OBS: Alguns dos comentários que inseri no código, são possíveis alternativas de como poderias escrever o código, apesar de ainda existirem várias outras que não coloquei.

Another thing, before you try to return the result of a query with the echo, you should tell the PHP how to select, and what results to select, using the prefixed function mysqli_fetch_[aqui_o_metodo], can select only 1 set of values, or even all existing sets of values using a looping and/or syntax SQL.

And most of all, I’m sorry for my laziness and ignorance, but I’d rather write a code similar to yours than try to understand yours :/

PHP.NET - Here you can find several examples, and recommended ways to use some functions.

There are also websites of their own that talk and address about the recommended ways of writing queries SQL.

Here in the StackOverflow there are also several questions already answered that can help you.

  • Edilson, thank you so much for the help and whitening. I will start researching on MYSQLI. I confess that I am new and I ended up looking for some examples of SQL connection to play a little and understand more how it works. I ended up crashing and catching something very old. I remade my code searching for this new method.

Browser other questions tagged

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