Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //MySql
- CREATE TABLE user
- (
- id serial NOT NULL,
- nome text,
- end text,
- tel numeric(10,2)
- )
- //PHP
- <?php
- header('Content-Type:' . "text/plain");
- $host = "localhost";
- $user = "user";
- $pswd = "pass";
- $dbname = "bd";
- $con = null;
- $con = @pg_connect("host=$host user=$user password=$pswd dbname=$dbname") or die (pg_last_error($con));
- //@pg_close($con);
- if(!$con) {
- echo '[{"erro": "Não foi possível conectar ao banco"';
- echo '}]';
- }else {
- $sql = "SELECT * FROM user ORDER BY nome";
- $result = pg_query($sql);
- $n = pg_num_rows($result);
- if (!$result) {
- echo '[{"erro": "Há algum erro com a busca. Não retorna resultados"';
- echo '}]';
- }else if($n<1) {
- echo '[{"erro": "Não há nenhum dado cadastrado"';
- echo '}]';
- }else {
- for($i = 0; $i<$n; $i++) {
- $dados[] = pg_fetch_assoc($result, $i);
- }
- echo json_encode($dados, JSON_PRETTY_PRINT);
- }
- }
- ?>
- //HTML
- <!DOCTYPE HTML>
- <html lang="pt-br">
- <head>
- <meta charset="UTF-8">
- <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
- <script src="script.js" type="text/javascript"></script>
- </head>
- <body onload="carregarItens()">
- <section>
- <h1>EltonDEV</h1>
- <h2></h2>
- <table id="minhaTabela">
- <caption>Cadastro de Clientes</caption>
- <thead>
- <th>ID</th>
- <th>Nome</th>
- <th>Endereco</th>
- <th>Telefone</th>
- </thead>
- <tbody>
- </tbody>
- </table>
- </section>
- </body>
- </html>
- //Json
- function carregarItens(){
- var itens = "", url = "ophpdobanco.php";
- $.ajax({
- url: url,
- cache: false,
- dataType: "json",
- beforeSend: function() {
- $("h2").html("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{
- for(var i = 0; i<retorno.length; i++){
- itens += "
- ";
- itens += "" + retorno[i].id + "
- "; itens += "" + retorno[i].nome + "
- "; itens += "" + retorno[i].end + "
- "; itens += "" + retorno[i].tel + "
- "; itens += "
- ";
- }
- $("#minhaTabela tbody").html(itens);
- $("h2").html("Carregado");
- } }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement