1
I want to get the name of the columns of a table and their respective records.. Ex: I have the table criminal records and on it are the columns name, login, password and there are 2 records recorded in this table, leaving +- so:
name = Alisson / login=admin / password = 123
name = alisson2 / login=admin2 / password = 123
So I’d like to take the name of the columns (name, login, password,) and take the value of the 2 records in it (Alisson, admin, 123 e alisson2, admin2, 123)
<?php
protected function ListColumn($table){
$Query = $this->connect->prepare("SHOW COLUMNS FROM {$table}");
$Query->execute();
while($e = $Query->fetch(PDO::FETCH_ASSOC)){
$colunas[] = $e['Field'];
}
return array($colunas);
}
QuerySearch = $this->connect->prepare("SELECT * FROM {$table} WHERE login LIKE '%teste%'");
$QuerySearch->execute();
$Retornados = $QuerySearch->rowCount();
if($Retornados > 0){
while($b = $QuerySearch->fetch(PDO::FETCH_ASSOC)){
foreach($this->ListColumn($table) as $field){
$s[] = $field;
}
}
echo json_encode($s);
}else{
echo json_encode(array('error'=>'Nada foi encontrado com o termo informado.', 'result'=>'0'));
}
?>
It was not very clear your doubt...
– Papa Charlie
@Papacharlie edited the question
– Alisson Acioli
I’m trying to understand but I can’t... What is the relationship with the names of the columns? In your code, which row executes what you want to do?
– Papa Charlie
I just want to get the column names of a table and along with the name, get the records
– Alisson Acioli
You get the names of the tables and then the records.
– Jorge B.
I even know how to do with mysql_fetch_array, but I won’t inform for example that I want the names, making for ex $data["name"]... the "name" will be the result of capturing the columns to form a $data[$field]
– Alisson Acioli
@Alisson keep using PDO , these on the right track. I believe the Pope’s answer is what you want
– gmsantos
Too bad I only saw the comments two years later :) Follow the version with
mysqli
, more suitable for visitors who do not need "portability" of DB: How to list a query without knowing what will be returned?– Bacco