I got a database with 2 fields: amount and name.
I want to get all the data from the database (40 rows) and create an associated array out of it like this:
$arr = array("amount" => "12", "name" => "John");
How is this done dynamically in PHP? I am stuck.
If you're using the mysql_* function, you can do the following to get one row at a time:
$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}
To get all rows in a single array:
$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
$customers[] = $row;
}
Well, if you run your query, e.g.
$result = mysql_query('SELECT amount, name FROM table');
you can loop over the result like that:
$values = array();
while(($row = mysql_fetch_assoc($result))) {
$values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}
and you will have an array of arrays.
Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);
That's it in PDO. And if you're not using PDO, well, that's your problem then...
Related
I am trying to fetch a column from a database and display the entire contents as an array. I have so far been able to fetch only one of the entries from the table. I understand that I am fetching only $row[0] which is why i am getting only 1 element. I have tried to fetch all elements but I have not succeeded yet. can someone please let me know how to do it correctly? I have attached my code below.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT `current` FROM `monitor` ORDER BY `Sno.`";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_NUM);
printf("%s\n",$row[0]);
mysqli_close($con)
?>
PDO has a dedicated feature for your problem PDOStatement::fetchColumn.
So, from your question what I understand is- you want to fetch a database column and store this in a array which will make you to display the results.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT current FROM monitor ORDER BY Sno";
$result = mysqli_query($con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
$first_col = array_column($arr, 0);
print_r($first_col);
mysqli_close($con)
?>
i.e. if you have five entry to the database whose first column contains
the values like 'current1', 'current2', 'current3', 'current3' and 'current4' the result of this code will be
Array
(
[0] => current1
[1] => current2
[2] => current3
[3] => current4
[4] => current5
)
I am trying to add array data from mysql. But only the last row details are getting added. I tried array_push also but did not work. Can any one help
$sql="SELECT * FROM server_details";
$result=mysqli_query($dbC, $sql);
while ($row = mysqli_fetch_array($result))
{
$services=array(
$row['server_name'] => array($row['server_add'] => $row['port'])
);
}
By not creating a new array in every iteration of the loop :
$sql = "SELECT * FROM server_details";
$result = mysqli_query($dbC, $sql);
$services = array();
while ($row = mysqli_fetch_array($result)) {
$services[$row['server_name']] = array($row['server_add'] => $row['port']);
}
Perhaps you're looking for this:
$services[ $row['server_name'] ] = array($row['server_add'] => $row['port']);
In the end you'll get in your $services variable an associative array, indexed by server_name column values.
If they're not unique, you should do this instead...
$services[ $row['server_name'] ][] = array($row['server_add'] => $row['port']);
This way you'll still get the same associative array, but its values will be indexed arrays; thus you won't lose any information for records with the same server_name.
This is a problem that I come across frequently when using PHP to query mysql data, and I would like to know if there is a more efficient solution. When I only need two columns of data, for instance the columns 'id' and 'price', I prefer this 'flat' format:
array(
id 1 => price 1,
id 2 => price 2,
id 3 => price 3,
...
);
or in json:
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]
And my usual solution is to loop twice, like so:
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id' => $row['id'],
'price' => $row['price']
);
}
mysql_close($con);
$array2 = array();
foreach ($array1 as $key => $value) {
$array2[$key][$value['id']] = $value['price'];
}
print json_encode($array2);
which does work, but I think this code is too lengthy for its purpose, and there should be a better way -- so that I only have to loop one array. Any suggestions?
You can simplify your loop to this
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id '.$row['id'] => 'price '.$row['price']
);
}
print json_encode($array1);
$result = array();
while ($row = mysql_fetch_assoc($info)) {
$result[$row['id']] = $row['price'];
}
print_r($result);
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info))
$array1[$row['id']] = $row['price'];
mysql_close($con);
print json_encode($array1);
NOTE: your $array2 is a two dimensional array. If it works for you, you need to change your javascript code to handle following flat format i.e. the above code produce
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]
I've been working on a OOP method that is supposed to return the rows of a MySQL query. I have to have the data array in the format:
$rows = array('row'=> rownum, 'fld1'=> fldval .... 'fldn' => fldval);
What I have encountered are the two problems of either:
returns
$rows = array('0'=>fldval, 'fld1'=> fldval .... 'n'=> fldval, 'fldn' => fldval);
or single row of
$rows = array('fld1'=> fldval .... 'fldn' => fldval);
Little frustrated as every PHP mysql function I have tried has some sort to goofy crap flaw and will not do a straight out process.
I assume there is a good example somewhere, that can get me past the crap limitations, but haven't found anything useful yet!
I've tried all of the following:
$row = mysql_result($db_res,$n);
$row = mysql_fetch_array($db_res);
$row = mysql_fetch_assoc($db_res);
$row = mysql_fetch_object($db_res);
$row = mysql_fetch_row($db_res);
None have worked successfully! For getting out the bogus "numeric" array entries. I wrote:
foreach ($row as $k => $v)
if (is_numeric($k)) { continue; }
$result[$k] = $v;
} // end foreach $row
$row = array_push($row, 'row'=>$rownum, $result);
Hoping someone has a link.
$list = array();
$query = "SELECT value FROM table";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list['fld' . (1 + count($list))] = $row['value'];
}
$list = array('row' => count($list)) + $list;
if table have 3 row, the code above is going to give you a array like:
array(
'row' => 3,
'fld1' => 12,
'fld2' => 34,
'fld3' => 56
);
I have a query returning data that looks like this:
Status Total
Success 234
Failed 20
Missing 12
I want to add this to an array which can then be used to populate a google pie chart.
the array would look like this:
array backup = array("Success" => 234),
("Failed" => 20),
("Missing" => 12);
How would I add these item dynamically at each row in a query?
$result = mysql_query(...);
$backup = array();
while ($r = mysql_fetch_assoc($result)) {
$backup[$r['Status']] = $r['Total'];
}
Here's how you can make the Google Charts API call:
$values = implode(',', array_values($backup));
$labels = implode('|', array_keys($backup));
$img = "http://chart.apis.google.com/chart?cht=p3&chd=t:{$values}&chl={$labels}&chs=250x100";
echo "<img src='{$img}' alt='Chart'>";
Assuming this is your query:
SELECT status, total FROM table
Then you can do:
$data = array();
while(($row = mysql_fetch_assoc($result))) {
$data[$row['status']] = $row['total'];
}
If this is not what you mean, please clarify your question and/or provide the code you already have.
I think we need a bunch more information, but in the mean time look at array_merge()
http://www.php.net/manual/en/function.array-merge.php