PHP Populating an Array from a MySql Query - php

I am looking to create an array of data to be pass to another function that is populated from a database query and am not sure how to do this.
$dataArray[0][1];
$qry = mysql_query("SELECT Id, name FROM users");
while($res = mysql_fetch_array($qry)) {
$dataArray[$res['Id']][$res['name']]
}
Thanks in advance.

This would look better
$dataArray = array();
$qry = mysql_query("SELECT Id, name FROM users");
while($res = mysql_fetch_array($qry)) {
$dataArray[$res['Id']] = $res['name'];
}
you can take a look at the PHP manual how to declare and manipulate arrays.

The below code sniper is very handy...
$select=" WRITE YOUR SELECT QUERY ";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
Thanks

Related

how to generate JSON array for entire database tables from MySQL database using PHP

I want this kind of JSON array,
database1 all tables
{
{"table1":"[{"key11":"val11"},{"key12":"val12"},{"key13":"val13"}]"},
{"table2":"[{"key21":"val21"},{"key22":"val22"},{"key23":"val23"}]"},
{"table3":"[{"key31":"val31"},{"key32":"val32"},{"key33":"val33"}]"},
{"table4":"[{"key41":"val41"},{"key42":"val42"},{"key43":"val43"}]"},
{"table5":"[{"key51":"val51"},{"key52":"val52"},{"key53":"val53"}]"},
}
This bellow code is convert a single database table to JSON array, But i want entire database tables to JSON array
$return_arr = array();
$fetch = mysql_query("SELECT * FROM table1");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['val2'] = $row['val1'];
$row_array['val2'] = $row['val2'];
$row_array['val3'] = $row['val3'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
anyone help me please.
Iterate over all tables, you can use that query to get all tables.
select * from information_schema.tables
You still need to select all results inside the tables.
something like this:
$db='recipes';
$tables=$db->query('SHOW TABLES IN '.$db, O_ARRAY);
foreach($tables as $n=>$v){
$table=$v['Tables_in_'.$db];
$array=$db->query("SELECT * FROM $table");
$data[$table]=$array;
}
echo '<pre>';
echo json_encode($data);
that's going to be pretty memory intensive on large data! You might add some filters for unneeded fields, or database-specific fields that need to be skipped or the value translated to another place.
This is the answer for above question change database name only all tables and table records are given in JSON array format.
mysql_connect('localhost','root','');
mysql_select_db('database');
$db='database';
$return_arr = array();
$return_arr1 = array();
$return_arr2 = array();
$return_arr3 = array();
$result = mysql_query("SHOW TABLES IN ".$db);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($return_arr,$row);
}
foreach($return_arr as $key => $value)
{
$table=$value['Tables_in_'.$db];
$array1=mysql_query("SELECT * FROM $table");
while ($row1 = mysql_fetch_array($array1, MYSQL_ASSOC))
{
array_push($return_arr3,$row1);
}
$return_arr1[$table]=$return_arr3;
unset($return_arr3);
$return_arr3 =array();
}
echo '<pre>';
print_r($return_arr1);

Fetching An Array With MySQL / PHP

I have an existing database which has a table called PERSON with a field called NAME. What I’m trying to do is select all of the rows in the table where the NAME is "bill". And then I want the result to be stored in an array that I can step through at a later point.
Now, the problem is my code will only select the FIRST row with the name "bill" and ignore the rest of the rows where the NAME is "bill". At least that’s how it appears when I print out the array contents with print_r(). My code below:
<?php
$getAllPreview = "SELECT * from PERSON where NAME = 'bill'";
$getAllResult = #mysql_query( $getAllPreview );
$getAllRows = #mysql_fetch_assoc( $getAllResult );
print "<pre>";
print_r($getAllRows);
print "</pre>";
?>
<?php
$getAllPreview = "SELECT * from PERSON where NAME = 'bill'";
$getAllResult = #mysql_query( $getAllPreview );
while ($row = #mysql_fetch_assoc( $getAllResult ) ) {
$getAllRows[] = $row;
}
print "<pre>";
print_r($getAllRows);
print "</pre>";
?>
while($row = mysql_fetch_array($getAllResult, MYSQL_ASSOC)) {
$data[] = $row;
}
You just keep looping over mysql_fetch_assoc until no further rows are returned. If you want to output or process them, just do so in each iteration of the loop, as it's more efficient than placing it in an array first. But here you go anyway:
$allRows = array ();
while ($row = mysql_fetch_assoc( $getAllResult)) $allRows [] = $row;
<?php
$getAllPreview = "SELECT * from PERSON where NAME = 'bill'";
$getAllResult = #mysql_query( $getAllPreview );
$num_rows = mysql_num_rows($getAllResult);
while ($row = #mysql_fetch_assoc($getAllResult))
{
for($i=0;$i<$num_rows;$i++)
{
$array[] = $row;
}
}
?>

change my output format

my php code is :
$q = $db->query("SELECT username FROM users LIMIT 3");
$users = array();
while($row = $db->fetchAll($q))
{
$users[] = $row;
}
foreach($users as $user)
{
echo $user['username'].'<br>';
}
and the output will be
Nilsen
Michael
Sam
Does it possible to change my output format to be Nilsen,Michael,Sam without start foreach ?
Any idea please ?
Thank you.
while($row = $db->fetchAll($q)) // fetchAll is wired here, but since you get the result, asume that's right
{
$users[] = $row['username'];
}
then use:
echo join(',' $users);
you can use GROUP_CONCAT() and loop won't be needed on the php side.
SELECT GROUP_CONCAT(username) user_name FROM users LIMIT 3
MySQL GROUP_CONCAT()
$q = $db->query("SELECT username FROM users LIMIT 3");
while($row = $db->fetchAll($q))
{
print_r($row);
}
.
or
echo $row[0], $row[1], $row[2];
I wouldn't recommend this for production though, just for checking/debuging..
Mostly for debugging you can use like this :
$q = $db->query("SELECT username FROM users LIMIT 3");
while($row = $db->fetchAll($q))
{
print_r($row); // or below
var_dump($row);
}
The var_dump() function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.
The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Do you mean this?
$stmt = $db->query('SELECT username FROM users LIMIT 3');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$users = array_map(function($row) {
return $row['username'];
}, $rows);
print_r($users);

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Storing database records into array

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..
<?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
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
}
}
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}

Categories