Tenho visto muitas pessoas que começam o caminho de aprendizado da linguagem PHP de maneira errada. Querem programar sem ter conceitos básicos para iniciar um projeto, sendo assim difícil um aprendizado correto.
Para isso tenho criado tutoriais detalhados para entender como é que funciona PHP e outras tecnologias. Veja!:
Entenda!
- Para começar quero que saiba o que faz este aplicativo:
- Ele mostra ao usuário os dados da pessoa solicitada desde o formulario.
- O usuário só deve clicar sobre o nome que quer detalhar!.
Criando Arquivo "index.php"
Este Arquivo contém o Formulário inicial onde o usuário consegue solicitar os dados, veja:
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="pt"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | |
<title>Primeiro Projeto</title> | |
<!--Bootstrap--> | |
<link rel="stylesheet" href="css/bootstrap.min.css"> | |
<!--JS--> | |
<script type="application/javascript" src="js/jquery-3.2.1.slim.min.js"></script> | |
<script type="application/javascript" src="js/popper.min.js"></script> | |
<script type="application/javascript" src="js/bootstrap.min.js"></script> | |
<!--End Bootstrap--> | |
<!--Script Motor Controlador--> | |
<script type="application/javascript" src="js/script.js"></script> | |
<!--End Script Controller--> | |
</head> | |
<body> | |
<!--Form Bootstrap--> | |
<div class="container h-25"> | |
<form> | |
<select class="form-control" name="users" onchange="showUser(this.value)"> | |
<option value="">Selecione um Nome: </option> | |
<option value="1">Miguel Santisteban</option> | |
<option value="2">Nancy Ramos</option> | |
<option value="3">Elena Santisteban</option> | |
<option value="4">Estefany Santisteban</option> | |
</select> | |
</form> | |
<br> | |
</div> | |
<!--End Form Bootstrap--> | |
<!--Magia onde aparece os dados MySQL--> | |
<div id="txtHint"><b>O nome será listado aquí</b></div> | |
</body> | |
</html> |
Criando Arquivo "Script.js"
Este arquivo contém a magia Ajax para solicitar os dados que o usuário quer, utilizando a function showUser!, veja:
This file contains hidden or 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
function showUser(str) { | |
if (str=="") { | |
document.getElementById("txtHint").innerHTML=""; | |
return; | |
} | |
if (window.XMLHttpRequest) { | |
// code for IE7+, Firefox, Chrome, Opera, Safari | |
xmlhttp=new XMLHttpRequest(); | |
} else { // code for IE6, IE5 | |
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); | |
} | |
xmlhttp.onreadystatechange=function() { | |
if (this.readyState==4 && this.status==200) { | |
document.getElementById("txtHint").innerHTML=this.responseText; | |
} | |
} | |
xmlhttp.open("GET","template/muestreUser.php?q="+str,true); | |
xmlhttp.send(); | |
} |
Criando Arquivo "muestreUser.php"
Este arquivo realiza a conexão à nossa Base de Dados MySQL com o Driver PDO e consegue trazer os dados solicitados. Veja:
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="pt"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | |
<title></title> | |
<!--Bootstrap--> | |
<link rel="stylesheet" href="../css/bootstrap.min.css"> | |
<!--JS--> | |
<script type="application/javascript" src="../js/jquery-3.2.1.slim.min.js"></script> | |
<script type="application/javascript" src="../js/popper.min.js"></script> | |
<script type="application/javascript" src="../js/bootstrap.min.js"></script> | |
<!--End Bootstrap--> | |
</head> | |
<body> | |
<?php | |
$q = intval($_GET['q']); | |
echo "<table class='table'>"; | |
echo "<tr><th scope='col'>#</th><th scope='col'>Primeiro Nome</th><th scope='col'>Apelido</th><th scope='col'>Idade</th><th scope='col'>Cidade</th><th scope='col'>Trabalho</th></tr>"; | |
class TableRows extends RecursiveIteratorIterator { | |
function __construct($it) { | |
parent::__construct($it, self::LEAVES_ONLY); | |
} | |
function current() { | |
return "<td>" . parent::current(). "</td>"; | |
} | |
function beginChildren() { | |
echo "<tr>"; | |
} | |
function endChildren() { | |
echo "</tr>" . "\n"; | |
} | |
} | |
$servername = "localhost"; | |
$username = "root"; | |
$password = ""; | |
$dbname = "bdajax"; | |
//corrigindo problema de acentos | |
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8',); | |
try { | |
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, $options); | |
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$stmt = $conn->prepare("SELECT * FROM usuarios WHERE id='".$q."'"); | |
$stmt->execute(); | |
// set the resulting array to associative | |
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC); | |
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { | |
echo $v; | |
} | |
} | |
catch(PDOException $e) { | |
echo "Error: " . $e->getMessage(); | |
} | |
$conn = null; | |
echo "</table>"; | |
?> | |
</body> | |
</html> |
Déjenos su Comentário:
0 commentários: