How to create an array with object from an SQL query

0

I need the following result inside a variable from a query PHP + MySQL :

array(1) {
    [0] => object(stdClass) #1 (3) { 
    ["id"]= > string(2) "1" 
    ["nome"] => string(5) "teste" 
    ["email"] => string(18) "[email protected]"
    }
}

The above result is as follows:

$results = array((object) array( 
      'id' => '1', 
      'nome' => 'teste', 
      'email' => '[email protected]'
    ));
  
    

UPDATE: If I have 1 or more ID's, ie 1 or more names and emails

  
array(2) {
  [0]=>
  object(stdClass)#2195 (3) {
    ["id"]=>
    string(2) "1"
    ["nome"]=>
    string(16) "testao"
    ["email"]=>
    string(14) "[email protected]"
  }
  [1]=>
  object(stdClass)#2196 (3) {
    ["id"]=>
    string(2) "2"
    ["nome"]=>
    string(17) "testado"
    ["sml_email"]=>
    string(18) "[email protected]"
  }
}
    
asked by anonymous 25.11.2015 / 21:48

3 answers

1

To connect to the MySQL database:

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

Making the Select in the database:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

In your case you can get the values returned and play directly:

$results = array((object) array( 
      'id' => $row["id"], 
      'nome' => $row["nome"], 
      'email' => $row["email"]
    ));

Without having your data to use for example it becomes difficult. But I believe that with this code you can connect to the database, make the select and mount the array.

UPDATE

To do in the loop with the select of the bank looks like this:

$newArray = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        
	
	$newArray[] = array(


	'id' => $row["id"], 
        'nome' => $row["nome"], 
        'email' => $row["email"]


           );

    }
}

In the code above you put an array inside another one, maybe this is confusing you.

Look at this fiddler and see if it gets easier, in it I paste an object into the array. I believe it will be better in your case, but again, without your code to pick up and change it is difficult to understand what you really need.

    
25.11.2015 / 21:56
1

Just assign this return to a new variable by doing the following:

Return as object:

<?php

$con = new mysqli('localhost', 'root', '', 'exemplo');

if($query = $con->query('SELECT * FROM exemplo LIMIT 5')){
    while($resultado = $query->fetch_object()){
        $obj[] = $resultado;
    }
}

print_r($obj);

?>

Return as association converted to output

<?php

$con = new mysqli('localhost', 'root', '', 'exemplo');

if($query = $con->query('SELECT * FROM exemplo LIMIT 5')){
    while($resultado = $query->fetch_assoc()){
        $obj[] = (object) $resultado;
    }
}

print_r($obj);

?>

To return the results you just have to scroll them like any other object, but inside a loop:

foreach($obj as $key=>$val){
    # imprime o indice da array 
    # e o respectivos valores de cada objecto nessa array
    print "#{$key} " . $obj[$key]->titulo . "<br/>";
}
    
26.11.2015 / 00:27
1

To print as you said, use the function below:

public function listar(){   //new Pessoa(id, nome, telefone, endereco)
$query = "SELECT *FROM pessoa ";            
try {               
    $stmt = $this->conexao->mysqli->prepare($query);
    if($stmt->execute()){
        $result = $stmt->get_result();
        while ($row = $result->fetch_object()) {
            array[] = $row;
        }
        $stmt->free_result();
        $stmt->close();
        return $this->array;
    }else{
        echo "Erro ao buscar dados";
    }
} 
catch (Exception $e) {
  echo $e->errorMessage();
}

}

To call the function, do:

$exemplo = new daoPessoa();
$pessoa = $exemplo->listar();

<!-- para imprimir organizado faça: -->
<pre>
<?php print_r(pessoa); ?>
<pre>
    
24.10.2016 / 03:46