BD connection via php returning json to javascript

Asked

Viewed 2,675 times

0

Guys I’m trying a connection with bd via php and returning a json to my javascript, but there’s something I’m forgetting or doing wrong, because I’ve tried to do several ways but never returns the value of the bank, always gives an error in some "trycatch" halfway.

These files are all on the same server.

If you want to see the code running:

http://engenini.com.br/tst/

My Code:

/**
* Capturar itens do banco de dados
*/
function carregarItens(){
	//variáveis
	var itens = "", url = "dados.php";

    //Capturar Dados Usando Método AJAX do jQuery
    $.ajax({
	    url: $url,
	    cache: false,
	    dataType: "json",
	    beforeSend: function() {
		    $("h2").html("Carregando..."); //Carregando
	    },
	    error: function() {
		    $("h2").html("Há algum problema com a fonte de dados");
	    },
	    success: function(retorno) {
		    if(retorno[0].erro){
			    $("h2").html(retorno[0].erro);
		    }
		    else{
			    //Laço para criar linhas da tabela
			    for(var i = 0; i<retorno.length; i++){
				    itens += "<tr>";
				    itens += "<td>" + retorno[i].id + "</td>";
				    itens += "<td>" + retorno[i].nome + "</td>";
				    itens += "<td>" + retorno[i].console + "</td>";
				    itens += "<td>" + retorno[i].preco + "</td>";
				    itens += "</tr>";
			    }
			    //Preencher a Tabela
			    $("#minhaTabela tbody").html(itens);
			    
			    //Limpar Status de Carregando
			    $("h2").html("Carregado");
		    }
	    }
    });
}
<!DOCTYPE HTML>
<html lang="pt-br">
<head>
	<meta charset="UTF-8">
	<!-- 	<link rel="icon" type="favicon.png" />
	<link rel="stylesheet" type="text/css" href="estilo.css"> -->
	
	<!--jQuery-->
	<script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
	<!--Script-->
	<script src="script.js" type="text/javascript"></script>
	
	
</head>
<body onload="carregarItens()">
	<section>
		<h1>PortilloDesign Tutorial JSON + PHP</h1>
		<!--Área que mostrará carregando-->
		<h2></h2>
		<!--Tabela-->
		<table id="minhaTabela">
			<caption>Cadastro de Jogos</caption>
			<thead>
				<th>ID</th>
				<th>Jogo</th>
				<th>Console</th>
				<th>Valor</th>
			</thead>
			<tbody>
			</tbody>
		</table>
	</section>
</body>
</html>

<?php
/**
* Tutorial jSON
*/

//Definir formato de arquivo
header('Content-Type:' . "text/plain");


$username = ''; // 
$password = '';
$hostname = '';  //
$database = '';
//$porta = '' // 

$con = mysql_connect($hostname, $username, $password)
 or die("Não é possível conectar ao MySQL");

$selected = mysql_select_db($database,$con) 
  or die("Não foi possível conectar ao banco de dados");



//@pg_close($con); //Encerrrar Conexão

if(!$con) {
	echo '[{"erro": "Não foi possível conectar ao banco"';
	echo '}]';
}else {
	//SQL de BUSCA LISTAGEM
	$sql 	= "SELECT * FROM jogos ORDER BY console";
	$result = pg_query($sql); //Executar a SQL
	$n 		= pg_num_rows($result); //Número de Linhas retornadas

	if (!$result) {
		//Caso não haja retorno
		echo '[{"erro": "Há algum erro com a busca. Não retorna resultados"';
		echo '}]';
	}else if($n<1) {
		//Caso não tenha nenhum item
		echo '[{"erro": "Não há nenhum dado cadastrado"';
		echo '}]';
	}else {
		//Mesclar resultados em um array
		for($i = 0; $i<$n; $i++) {
			$dados[] = pg_fetch_assoc($result, $i);
		}
		
		echo json_encode($dados, JSON_PRETTY_PRINT);
	}
}
?>

  • you can here the output of json_encode($dados, JSON_PRETTY_PRINT) ?

  • What’s the mistake, where it stops?

  • @Moshmage http://engenini.com.br/tst/dados.php The error is in php because json was supposed to appear in the output.

  • @rray it here: "error: Function() { $("H2"). html("There is some problem with the data source");" no js, but in php it is not returning anything.

  • Give a console.log on retorno This already helps to identify what happened

  • 1

    Where does the variable come from $con ? And why use mysql ?

  • @rray the console.log in "return" returns nothing.

  • @Edilson, it was error when putting the code here, dbhandle is the con (I will edit)

  • The url in ajax is '$url', but you have set only the variable 'url'.

  • Friend it is kind of complicated to try to understand the code, because I see too many irregularities and variables that have not even been defined beyond the variable $con there are several others. I say then, that if the error is in the PHP must be one of the connection lines that make use of the function die().

  • @Joaopaulo Yes, I fixed it.

  • @Edilson the code is quite strange, but it happened because I didn’t get the connection and so I went to get other codes on the Internet that weren’t mine. I believe if it’s simple, I’m not good yet with web, but whatever is wrong in your point of view can say that I seek to know and fix.

  • @Edilson I removed the codes or die, and now it from connection error.

  • Where did you get this tutorial ?

  • @Edilson here

  • Friend, I edited your answer and put a fully functional example that I created and tested from the original tutorial.

  • @Edilson Sorry for the ignorance, but where is the code you edited? If you can put as an answer I think it would be better.

  • Oh yeah, it looks like they refused my edition, I’m going to create a new answer.

Show 13 more comments

2 answers

2


Hello, this code here worked.

SQL table

--
-- Estrutura da tabela `jogos`
--

CREATE TABLE IF NOT EXISTS `jogos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(36) NOT NULL,
  `console` varchar(16) NOT NULL,
  `preco` decimal(6,2) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `nome` (`nome`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Extraindo dados da tabela `jogos`
--

INSERT INTO `jogos` (`id`, `nome`, `console`, `preco`) VALUES
(1, 'Resident Evil - Retaliacao', 'XBOX 360', '3000.00'),
(2, 'The Elders Scrolls - Skyrim', 'XBOX 360', '5000.00');

HTML file

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JSON + PHP</title>
        <!-- biblioteca jQuery !-->
        <script type="text/javascript" src="jquery.js"></script>
        <!-- Script externo !-->
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body onload="carregarItens()">
        <section>
            <h1>JSON+ PHP</h1>

            <h2></h2>

            <table id="tabela">
                <caption>Cadastro</caption>
                <thead>
                    <th>ID</th>
                    <th>Jogo</th>
                    <th>Console</th>
                    <th>Preço</th>
                </thead>
                <tbody>

                </tbody>
            </table>
        </section>
    </body>
</html>

Script jQuery

function carregarItens(){
    // variavel itens(vazia), e a variavel url(o ficheiro php)
    var itens, url = "json.php";

    //Chamada Ajax
    $.ajax({
        url: url, 
        cache: false, 
        dataType: "json", 
        beforeSend: function(){
            $("h2").html("Carregando...");  
        },
        error: function(errori){
            $("h2").html("Erro, dados não carregados"); 
        },
        success: function(retorno){
            if(retorno[0].erro){
                $("h2").html(retorno[0].erro);
            } else {
                for(var i = 0; i < retorno.length; i++){
                    itens += "<tr>";
                    itens += "<td>" + retorno[i].id + "</td>";
                    itens += "<td>" + retorno[i].nome + "</td>";
                    itens += "<td>" + retorno[i].console + "</td>";
                    itens += "<td>" + retorno[i].preco + "</td>";
                    itens += "<tr>";
                }
                //Colocar os valores da variavel itens no tbody da tabela
                //$("#tabela tbody").html(itens);
                //Mudar status "Carregando" e fazer desaparecer, usei a função fadeOut com um callback
                $("h2").html("Carregado").fadeOut(function(){$("#tabela tbody").html(itens);}, 500);
            }
        }
    });
}

PHP[v2 file]

<?php
header("Content-Type: text/plain");

$conexao = mysqli_connect("localhost", "usuario_", "senha_", "banco_de_dados");

if(mysqli_connect_errno()){
    // Erros como este normalmente nem são visualizados pelo usuário, por segurança
    die('[{"erro" : "Não foi possivel conectar com o banco de dados !"}]');
    // À partir daqui, o código só é executado se a conexão for feita com sucesso !
}

$sql = mysqli_query($conexao, "SELECT * FROM jogos");
if(mysqli_num_rows($sql) >= 1){ 
    //Looping com o while   
    // O looping é feito apenas, se existirem dados da tabela
    while(false != ($resultado = mysqli_fetch_assoc($sql))){
        $dados[] = $resultado;
    }
    //Aqui codificamos o conjunto de valores para um formato JSON
    echo json_encode($dados, JSON_PRETTY_PRINT);
    mysqli_free_result($sql);
} else {
    //Caso o numero de resultados seja  menor que 1 (0), termina a execução
    // E mostra essa mensagem de erro, num formato JSON;    
    die('[{"erro" : "Não foi possivel conectar ao banco de dados !"}]');
}
mysqli_close($conexao); 

// Versão original do script PHP
// header("Content-Type: text/plain");

// $conexao = mysqli_connect("localhost", "usuario_", "senha_", "banco_de_dados");

// if(!$conexao){
    // echo '[{"erro" : "Não foi possivel conectar ao banco"}]';
// } else {
    // $sql = "SELECT * FROM jogos";
    // $resultado = mysqli_query($conexao, $sql);
    // $rows = mysqli_num_rows($resultado);
    // $dados = "";
    // $i = 0;
    // if(!$resultado){
        // echo '[{"erro" : "Consulta falhou"}]';
    // } elseif($rows <= 0){
        // echo '[{"erro" : "Nenhum resultado"}]';
    // } else {
        // for($i=0; $i<$rows; $i++){
            // $dados[] = mysqli_fetch_assoc($resultado);
        // }
        // echo json_encode($dados, JSON_PRETTY_PRINT);
    // }
// } 

?>

I followed the tutorial you indicated, and it worked. I think the problem was the connection to the database, or else, during the conversion of the returned values, to the JSON format, because I was entering the values in the database manually, using Unicode characters without previously cleaning.

Example:

In this database the name of the game is not accented because I will enter it directly in the database, without any processing of the values to be entered.

(1, 'Resident Evil - Retaliation', 'XBOX 360', '3000.00')

Now if I were to enter it, via form, I would rather prepare it to enter into the database, even with the accents. What would result from a conversion of the accents into hexadecimal values that would be entered in the database, and when processed by the server, would have the same return, however, without returning error.

...

$product name = mysqli_real_escape_string($connected,$_POST["product name"]);

...

I also did my best to make the code as close as possible to what was in the tutorial, and I only changed a few things. Many things could still be improved in this tutorial, but some do not make as much difference.

If you still have questions, see the PHP.net. Or go and search on Google, or even here on ptstackoverflow.

I’m sorry, if there were too many spelling errors, I didn’t have much time to read.

Good luck, and even more !

  • What this Edilson, I thank you, I got here was some problem in the BD and Postgre codes that had the "pg_", and I had not changed. But I do not know the difference of using Mysql or mysqli, I have a little doubt with this, but the rest I understood cool, I managed to evolve a lot, thanks.

  • Hello again, the difference is simple, the MySQLi is much safer, and the MySQL as well as being less secure, it has been unsubscribed. For this very reason I always leave a reference from the PHP.net at the end of responses related to php.

2

I redid the JS code, but I need to fix the connection, I made some changes but it returns it in php:

[{"erro": "Há algum erro com a busca. Não retorna resultados"}]

Was it something in the table creation? Table code:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";



CREATE TABLE IF NOT EXISTS `jogos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(45) NOT NULL,
  `console` varchar(45) NOT NULL,
  `preco` int(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=4 ;


INSERT INTO `jogos` (`id`, `nome`, `console`, `preco`) VALUES
(1, 'Geo', 'xbox', '20'),
(2, 'Pett', 'ps3', '50'),
(3, 'Ame', 'xbox', '100');

Code php(current):

<?php
/**
* Tutorial jSON
*/

//Definir formato de arquivo
header('Content-Type:' . "text/plain");

$username = ''; // Se for servidor compartilhado, deve vir com algo_
$password = '';
$hostname = '';  // Pode ser que seja um IP ou um endereço
$database = '';
//$porta = '3333' // As vezes pode ser necessário passar a porta, geralmente não é.

$dbhandle = mysql_connect($hostname, $username, $password, $database)
 or die("Não é possível conectar ao MySQL");

//$selected = mysql_select_db($database,$dbhandle) 
//  or die("Não foi possível conectar ao banco de dados");

//@pg_close($con); //Encerrrar Conexão

if(!$dbhandle) {
    echo '[{"erro": "Não foi possível conectar ao banco"}]';
}else {
    //SQL de BUSCA LISTAGEM
    //$sql  = "SELECT * FROM jogos ORDER BY console";
    //$sql  = "SELECT id, nome, console, preco FROM jogos";
    $sql    = "SELECT * FROM jogos ORDER BY console";
    //$result = mysqli_query($dbhandle, $sql);//Executar a SQL
    $result = mysqli_query($sql);//Executar a SQL
    $n      = mysqli_num_rows($result); //Número de Linhas retornadas

    if (!$result) {
        //Caso não haja retorno
        echo '[{"erro": "Há algum erro com a busca. Não retorna resultados"}]';
    }else if($n<1) {
        //Caso não tenha nenhum item
        echo '[{"erro": "Não há nenhum dado cadastrado"}]';
    }else {
        //Mesclar resultados em um array
        for($i = 0; $i<$n; $i++) {
            $dados[] = mysqli_fetch_assoc($result, $i);
        }

        echo json_encode($dados, JSON_PRETTY_PRINT);
    }
}
?>

Thanks there who helped and forgive the ignorance on the subject, hehehehe.

Browser other questions tagged

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