Store all records of a table in a variable (PHP)

Asked

Viewed 1,272 times

1

I need to make a query in my Mysql database and store all rows that are returned within the variable $dadosBrutos. The intention is that each line be separated by the character "§", for example: nomeCliente1,telefoneCliente1§nomeCliente2,telefoneCliente2§nomeCliente3,telefoneCliente3 and so on.

The data will be obtained with the command SELECT * FROM tbClientes, but I have no idea how to separate one line from the other and store them within the variable $dadosBrutos.

I tried to make this code with Do...While, but I have no idea how to continue.

For now I have the following code:

if($qtdeClientesCadastrados > 0) {  
    $contador = 0; 
    do {

    } while ($contador < $qtdeClientesCadastrados);
} else { 
    echo "zero_clientes_cadastrados";
}

Remarks:

  • The variable $qtdeClientesCadastrados has already been stated in the above section of the posted code and stores the amount of customers who are registered in the tbClientes of the database;

  • The whole system of connection to the database is already created and working properly;

  • If there is any better method to make the code other than with the Do...While, also serves, as long as in the end it is possible to give the command echo $dadosBrutos;.

  • 1

    The problem is separating with this character §

2 answers

3


  • assuming that the names of the columns are cliente and telefone
  • For the character § in all cases below, I used header("Content-type: text/html; charset=windows-1252");

Example table.

inserir a descrição da imagem aqui

data for connection.php

    $hostname="localhost";  
    $username="USUARIO";  
    $password="SENHA";  
    $db = "Nome_DB";

Using PDO

$dbcon = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);

$sql = "select cliente,telefone from tbClientes";
$stmt = $dbcon->prepare($sql);
$stmt->execute();

if ($data = $stmt->fetch()) {
    do {
        $dadosBrutos .= $data['cliente'].','.$data['telefone'].'§'; 
        
    } while ($data = $stmt->fetch());

    $dadosBrutos= substr($dadosBrutos,0,-1); //AQUI ELIMINA O ULTIMO §

} else {
    $dadosBrutos= "zero_clientes_cadastrados";
}

echo $dadosBrutos;

Using mysqli

$dbcon = new mysqli($hostname, $username, $password, $db);
  
$query = $dbcon->query("select cliente,telefone from tbClientes");

$qtdeClientesCadastrados=mysqli_num_rows($query);

option 1

if($qtdeClientesCadastrados>0){

    do {
        $dadosBrutos .= $data['cliente'].','.$data['telefone'].'§'; 

    } while ($data = $query->fetch_array()); 
    
      $dadosBrutos=substr($dadosBrutos, 2); // elimina os dois primeiros caracteres (,§)
     $dadosBrutos= substr($dadosBrutos,0,-1); //AQUI ELIMINA O ULTIMO §

}else{
     $dadosBrutos= "zero_clientes_cadastrados";
}

echo $dadosBrutos;

option 2

if($qtdeClientesCadastrados>0){

    while($row = $query->fetch_array())
    {       
        $dadosBrutos .= $row['cliente'].','.$row['telefone'].'§'; 
    } 

     $dadosBrutos= substr($dadosBrutos,0,-1); //AQUI ELIMINA O ULTIMO §

}else{
     $dadosBrutos= "zero_clientes_cadastrados";
}

echo $dadosBrutos;

0

Goal: echo $dadosBrutos;

Solution made with implode() in arrays resulting from the query.

I tried to make the code as simple as possible.

If you did not want to use $result as a function parameter, change the getDadosBrutos function a little and use mysql_fetch_array

<?php
    //Conexão apenas para exemplo
    $conn = new mysqli($servername, $username, $password, $dbname);
    if($conn->connect_error) die("Connection failed: " . $conn->connect_error);
    $query = $conn->query("SELECT nomeCliente, telefoneCliente FROM tbClientes");
    $conn->close();

    //Joga a query na função para obter os dados concatenados
    $dadosBrutos = getDadosBrutos($query);

    //objetivo
    echo $dadosBrutos;

    function getDadosBrutos($result){
        $clientes = array();
        if($result->num_rows > 0){
            while($row = $result->fetch_assoc()){
                $clientes[] = implode(',',$row);
            }
        }else{
            //nenhum cliente
            return '';
        }
        return implode('§', $clientes);
    }
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.