I have a function in PHP to automate the queries I make:
//arquivo funcao.php
function executaSql($sql, $param=array()){
try {
include "config.php";
$q = $conn->prepare($sql);
$q->execute($param);
$response = $q->fetchAll();
if ( count($response) ) {
return $response;
} else {
return 0;
}
} catch(PDOException $e) {
return 'ERROR: ' . $e->getMessage();
}
}
And then whenever I need to do a sql operation I just call the function like this:
//arquivo consulta.php
$sql = executaSql("SELECT * FROM cadastro_produto");
$sql = executaSql("SELECT * FROM cadastro_categoria");
//e assim por diante
//Os métodos de INSERT, UPDATE, DELETE, etc.. São gerenciados por outra função para verificação de erros
But the result I get is something like this:
Array (
[0] => Array (
[nome_categoria] => Painel
[0] => Painel
[tipo_categoria] => 3
[1] => 3
)
[1] => Array (
[nome_categoria] => Chapa
[0] => Chapa
[tipo_categoria] => 7
[1] => 7
)
)
I always return a int
field with the result repeated.
The current way I use to manipulate the data and return it to the desired end array is by using the combination of foreach
and checking whether the type is int
and, if not, add to a new array , like this:
$data = array();
$i=0;
foreach($sql as $row) {
foreach ($row as $key => $value) {
if(!is_int($key)){
$data[$i][$key] = $value;
}
}
$i++;
}
After all this process I get the final array :
Array (
[0] => Array (
[nome_categoria] => Painel
[tipo_categoria] => 3
)
[1] => Array (
[nome_categoria] => Chapa
[tipo_categoria] => 7
)
)
So my question is: Is there any way to automate this process by removing query results that have type int
, returning only fields and values?