-4
I know very little about SQL and I’m thinking about a very simple system - but I don’t know how to set it up and it’s for a public school that doesn’t have a programmer to hire at the moment.
I have an SQL table with some student registration data and each one has an ID. I wanted to build a system with PHP with only one field in which I would type this ID and with a Enter it would display all the data to confirm.
I don’t know if I used all the correct code and called it correctly in PHP. I did some research and found an AJAX code for this, but I also don’t know if it’s all right... Follow what I have so far:
index.js file
//Classe para criar e configurar requisição ajax
var Ajax = function() {
'use strict';
var request;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
request = new XMLHttpRequest();
} else { // code for IE6, IE5
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var url;
var data;
var method;
var getUrl = function() {
return url;
}
var setUrl = function(v) {
url = v;
}
var getData = function() {
return data;
}
var setData = function(v) {
data = v;
}
var getMethod = function() {
return method;
}
var setMethod = function(v) {
method = v;
}
var send = function(loading, done) {
if (!url) throw new Error('Url esperada.');
if (!method) {
console.warn('Metodo não especificado. Presumido POST.');
method = 'POST';
}
request.onprogress = function(event) {
if (event.lengthComputable && loading) {
var percentComplete = event.loaded / event.total * 100;
loading(percentComplete);
}
};
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200 && request.responseText && done) {
done(request.responseText.toString().replace('while(1);', ''));
}
};
request.open(method, url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf8');
request.send(data);
}
//Métodos ou propriedades públicas da classe
return {
//Significa que quando instanciar a classe,
//O objeto terá o método 'getUrl', por exemplo.
//Quando o mesmo for executado: instancia.getUrl
//Será executada a função 'getUrl', definida acima 'var getUrl = function..'
getUrl: getUrl,
setUrl: setUrl,
getData: getData,
setData: setData,
getMethod: getMethod,
setMethod: setMethod,
send: send
}
}
var campoid = document.getElementById('campoid');
campoid.onblur = function() {
//Instancia a classe Ajax
var requestid = new Ajax();
//Configura a requisição
requestid.setUrl('/conecta.php');
requestid.setData('ID = ' + this.value);
requestid.setMethod('POST');
//Envia a requisição
requestid.send(null,
function(resposta) {
//falha na busca, id ausente
if (!resposta) {
alert('ID não encontrado');
campoid.focus();
campoid.clear();
return false;
}
//não precisa de else, o return false acima termina a execução da função
//Transforma a string que o PHP criou em um objeto (JSON)
var dados = JSON.parse(resposta);
document.getElementById('outrocampodoform').value = dados.nome;
});
}
</script>
index.html file
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<title>Central</title>
<link href='https://fonts.googleapis.com/css?family=Lato:400,700,300|Open+Sans:400,600,700,300' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/css?family=Cinzel" rel="stylesheet" type='text/css'>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/animate.css">
<link rel="stylesheet" type="text/css" href="css/style1.css">
</head>
<body>
<php include 'conecta.php' ?></php>
<div class="field" align="center">
<label>ID: </label>
<input name="id" id="id" placeholder="ID" tabindex="3" required maxlength="10" onblur="ajax.js" autofocus>
</div><br>
<div class="field" align="center">
<label>Nome: </label> <input class="input-tam-1" name="nome" id="nome" type="text" disabled>
</div><br>
<div class="field" align="center">
<label>Status: </label> <input class="input-tam-1" name="status" id="status" type="text" disabled>
</div><br>
<div class="field" align="center">
<label>Documento: </label> <input class="input-tam-1" name="documento" id="documento" type="text" disabled>
</div><br>
<div class="field" align="center">
<label>Nascimento: </label> <input class="input-tam-1" name="nascimento" id="nascimento" type="text" disabled>
</div><br>
<div class="field" align="center">
<label>Instituição: </label> <input class="input-tam-1" name="instituicao" id="escola" type="text" disabled>
</div><br>
<div class="field" align="center">
<label>Validade: </label> <input class="input-tam-1" name="validade" id="validade" type="text" disabled>
</div><br>
</body>
</html>
File connects.php
<?php
error_reporting (E_ALL & ~ E_NOTICE & ~ E_DEPRECATED);
// definições de host, database, usuário e senha
$host = "localhost";
$db = "wjr_estudante";
$user = "wjr_estudante";
$pass = "xdr56tfc";
// conecta ao banco de dados
$con = mysql_pconnect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR);
// seleciona a base de dados em que vamos trabalhar
mysql_select_db($db, $con);
// cria a instrução SQL que vai selecionar os dados
$query = sprintf("SELECT ID, NOME, STATUS, DOCUMENTO, NASCIMENTO, INSTITUICAO, VALIDADE FROM estudantes WHERE NOME = ". $nome");
// executa a query
$dados = mysql_query($query, $con) or die(mysql_error());
// transforma os dados em um array
$linha = mysql_fetch_assoc($dados);
// calcula quantos dados retornaram
$total = mysql_num_rows($dados);
//Jogar dentro dessa $results os resultados da query
if (mysqli_num_rows($results) != 0)
{
$i = 0;
//Pega os resultados e transforma em um array
while ($result = mysqli_fetch_assoc($results))
{
$campos = array_keys($result);
foreach($campos as $campo)
{
$allData[$i][$campo] = $result[$campo];
}
$i++;
}
echo "while(1);" . json_encode($allData);
}
?>
You can do this with ajax and an sql query by or a field called matricula. You need to give more details about your problem and which 'foot' it is
– rray
This jquery was the code embed from here that added... I will not use, no
– William Gerrit
The server runs PHP 5.6, but I can change up to 7.1. The table has columns of ID, name, status, date etc. The same that are in the html form and I want to return from the ID query (unique for each registration).
– William Gerrit
No, just query... The data goes to db by another system. I just want to enter the ID so that it looks at the other data in sql and display in the form.
– William Gerrit