Last active
August 29, 2015 14:18
-
-
Save rodrigopedra/52ee84c410b03ce8784c to your computer and use it in GitHub Desktop.
retornando JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function resposta( $resultado, $erro = FALSE ) | |
{ | |
if ( $erro ) | |
{ | |
$resultado = array( | |
'erro' => $resultado | |
); | |
// envia cabeçalho de erro | |
http_response_code( 500 ); // PHP 5.4 | |
// header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); // PHP mais antigo | |
} | |
header( 'Content-Type: application/json' ); | |
echo json_encode( $resultado, JSON_NUMERIC_CHECK | JSON_BIGINT_AS_STRING ); | |
die; // para a execução do PHP | |
} | |
// verifica | |
if ( empty( $_GET ) || empty( $_GET[ 'id' ] ) ) | |
{ | |
resposta( 'dados inválidos', TRUE ); // a função retorna devolve o json e termina a execução | |
} | |
$usuario = $_GET[ 'id' ]; | |
//***** CONEXAO COM O BANCO DE DADOS | |
$servidor = 'localhost'; | |
$porta = 3306; | |
$banco = 'listas'; | |
$usuario = 'root'; | |
$senha = '123456'; | |
try | |
{ | |
$connectionString = sprintf( 'mysql:host=%s;port=%s;dbname=%s', $servidor, $porta, $banco ); | |
$pdo = new PDO( $connectionString, $usuario, $senha ); | |
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, TRUE ); | |
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); | |
$pdo->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC ); | |
//***** CONSULTAS | |
$stmtDados = $pdo->prepare( 'select nome, dataNascimento, cep, rua, cidade, estado, email from dadospessoais where idUsuario = :usuario LIMIT 1;' ); | |
$stmtDados->bindParam( ':usuario', $usuario ); | |
$stmtListas = $pdo->prepare( 'select * from lista where idAnfitriao = :usuario;' ); | |
$stmtListas->bindParam( ':usuario', $usuario ); | |
$stmtPresentes = $pdo->prepare( 'select presente.* from presente inner join itemlista on presente.id = itemlista.idPresente inner join lista on itemlista.idLista = lista.id where idAnfitriao = :usuario;' ); | |
$stmtPresentes->bindParam( ':usuario', $usuario ); | |
//***** RESULTADO | |
$stmtDados->execute(); | |
if ( $stmtDados->rowCount() < 1 ) | |
{ | |
throw new \Exception( 'Usuário não encontrado' ); | |
} | |
$dados = $stmtMateria->fetch(); // 1 registro, no json vai sair como objeto | |
$listas = $stmtListas->fetchAll(); | |
$presentes = $stmtPresentes->fetchAll(); | |
$resultado = array( | |
'listas' => $listas, | |
'presentesLista' => $presentes, | |
'DadosPessoais' => $dados | |
); | |
resposta( $resultado ); // a função retorna devolve o json e termina a execução | |
} | |
catch ( \Exception $ex ) | |
{ | |
// TODO: melhorar esta mensagem de erro | |
resposta( 'erro na consulta', TRUE ); // a função retorna devolve o json e termina a execução | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment