Storing database records into array - php

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');
}

Related

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

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;
}
}
?>

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

PHP Populating an Array from a MySql Query

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

Categories