Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing database records into array

Tags:

arrays

php

mysql

I would want to create an array that will hold records retrieved from a database using a query of SELECT statement.

The records to be retrieved have multiple fields such as lastname, firstname, mi and 20 more fields. What would be the best approach on coding this function?

alright i have followed what prisoner have given below.. the next question is how do i search through this kind of array using queries? for example i want to search for a username..

like image 703
zerey Avatar asked Mar 20 '11 03:03

zerey


People also ask

How data is stored in array in database?

First, create a table called example with the following SQL statement: CREATE TABLE example ( `id` int NOT NULL AUTO_INCREMENT, `docs` JSON, PRIMARY KEY (`id`) ); The example table will have two columns: the id column and the docs column. And that's the easiest way you can store an array type using MySQL.

How can we store database values in array in PHP?

Using simple assignment to initialize an array in your program leads to code like this: $addresses[0] = '[email protected]'; $addresses[1] = '[email protected]'; $addresses[2] = '[email protected]'; // ... That's an indexed array, with integer indexes beginning at 0.

How do I save an array of objects in SQL database?

You can store the array using serialize / unserialize . With that solution they cannot easily be used from other programming languages, so you may consider using json_encode / json_decode instead (which gives you a widely supported format).

Can a database have an array?

Array Databases are a class of databases that store, manage, and analyze data whose natural structures are arrays. Currently, there are a few systems, including SciDB, RasDaMan, MonetDB, and Google Earth Engine that are array databases (Baumann et al., 2018).


2 Answers

<?php

// run query
$query = mysql_query("SELECT * FROM table");

// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;

  // OR just echo the data:
  echo $row['username']; // etc

}

// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
like image 111
Prisoner Avatar answered Sep 21 '22 18:09

Prisoner


You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:

if (isset($_GET['search'])) {
  $search = mysql_real_escape_string($_GET['search']);
  $sql = "SELECT * FROM users WHERE username = '$search'";
  $res = mysql_query($sql) or trigger_error(mysql_error().$sql);
  $row = mysql_fetch_assoc($res);
  if ($row){
    print_r($row); //do whatever you want with found info
  }
}
like image 40
Your Common Sense Avatar answered Sep 18 '22 18:09

Your Common Sense