How to create an array with Object from an SQL query

Asked

Viewed 5,404 times

0

I need the following result within 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 obtained like this:

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

UPDATE: If I have 1 or more ID’s, that is, 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]"
  }
}
  • Places the code of your query and how far you have gone in trying to do the array.

  • I don’t know how you create this query with Object, that’s the question. Can you help with any example query? The array I created manually.

3 answers

1


To connect to 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";
?>

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 take the returned values and play straight:

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

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

UPDATING

To do in the loop with the bank select is 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 above code you put an array inside another, maybe this is confusing you.

Look at that one Fiddler and see if it gets easier, in it I stick an object inside the array. I believe it will be better in your case, but again, without your code to pick up and change it’s hard to understand what you really need.

  • There’s one thing... in case I have from 1 to 100 ID's, that is, 1 to 100 nomes and emails?? EDICT QUESTION!

  • Just do the loop, I edited the answer.

  • And the object???

  • Inside the array you put what you want, you can even put a new Minhaclasse() {given = value, date1 = value1}... Then you do anything.

  • He’s bringing me [0] => array(1) { before the object(stdClass), how to solve?

  • I edited the answer, this is pq you put an array inside the other, look at the Fiddler I made using a mounted object, much easier to understand, then you load each new object with the database data and play it in the array. http://phpfiddle.org/main/code/au2f-x290

Show 1 more comment

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>

1

Simply assign this return to a new variable, doing the following:

Return as an 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 converted association 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 just walk them like any other object, but within 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/>";
}

Browser other questions tagged

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