I am trying to store the data from my sql database into an array. Currently I have this:
$query = mysql_query("SELECT * FROM `InspEmail` WHERE `Company` LIKE '$company'");
while($row = mysql_fetch_array($query))
{
$inspector = $row['name'];
}
The problem is that I have 8 rows of data. I need to store each 8 names from that database into an array. When I try this:
$inspector = array($row['name']);
It doesn't work.
If you want to store all of the names in an array, you need to define the array outside the scope of the while loop and append to it. Like this:
$nameArray = array();
while($row = mysql_fetch_array($query)) {
// Append to the array
$nameArray[] = $row['name'];
}
What you want is:
$inspector[] = $row['name'];
This will store all 8 names in an array similar to:
array(
[0] => name1
[1] => name2
[2] => name3
)
Lots of good answers. But if you do this often, you might want to write a little function:
mysql_field_array($sql, $fieldname)
{
$res = mysql_query($sql);
$a = array();
while($row = mysql_fetch_array($res))
{
$a[] = $row[$fieldname];
}
mysql_free_result($res);
return $a;
}
Replace this line...
$inspector = $row['name'];
...with this:
$inspector [] = $row['name'];
After that, the inspector array contains all the names.
$query = mysql_query("SELECT * FROM `InspEmail` WHERE `Company` LIKE '$company'");
$data = array();
while($row = mysql_fetch_array($query))
{
$inspector[] = $row;
}
for($i=0;$i<mysql_num_rows($row);$i++)
{
$data = $inspector[$i];
}
return $data;
Check it...
Related
I have the following PHP code:
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
I fetch all the data with the column name "name" in database. How can I output it like this?
["John", "Doe", "Deer"]
You have to make $data as array type variable.
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // required output
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // output key wise display like
Array ( [0] => John [1] => Doe ) etc.
But output as you suggestion then just add json_encode()
print_r(json_encode($data)); // output like
["John", "Doe", "Deer"]
$data = [];
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
echo json_encode($data); // or you can use print_r for debugging.
You need to use json_encode() method to your array to be accepted in your jquery. Rearrange the code like following..
$data = array();
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
$new_array = json_encode($data);
echo $new_array; // use 'echo' to print. The json_encode() convert $data array to string.
If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it
while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
}
I want an array which has the entries of the array idlist as it's index and entries of the array namelist as it's values.
Is there a short way to do this?
Like this, if I understand your request. Use $info['id'] as the array key to the accumulating array $namelist (or whatever you decide to call it)
while($info5 = mysql_fetch_array($result)){
$namelist[$info['id']] = $info5["name"];
}
i'm not sure i understand your question but probably something like this should be fine.
while($info5 = mysql_fetch_array($result)){
$values[$info5['id']] = $info5;
}
$result = array();
while($info5 = mysql_fetch_array($result))
{
$id = $info5['id'];
$name = $info5['name'];
$result[$id] = $name;
}
This should give the output array $result you want, if I understood correctly.
You can use array_combine as long as the arrays have the same number of values:
$result = false;
if (count($idlist) == count($namelist))
$result = array_combine($idlist, $namelist);
Check out the docs: http://www.php.net/manual/en/function.array-combine.php
But, I also wonder why you don't just do it in the while loop:
$values = array();
$namelist = array();
$idlist = array();
while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
// this is the combined array you want?
$values[$info5["id"]] = $info5["name"];
}
I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>
This is my code
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
is there any way to extract title,text,date from $result and put them into 3 dimensional array?
What about
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$array = array();
$i = 0;
while( $row = mysql_fetch_assoc( $result ) {
$array[$i] = array();
// i'm just guessing at what sort of array you want
$array[$i][$row['title'] = array( 'text' => $row['text'], 'date' => $row['date'] );
$i++;
}
I'd be interested to know what the ... you need a three-dimensional array for but ok:
$dim = array();
$result = mysql_query(...);
while ( $row = mysql_fetch_assoc($result) )
// Whatever you want to save in that particular bucket,
// I'll be using the result set
$dim[$row['title']][$row['text']][$row['date']] = $row;
Strange, ...
If we are already guessing, here is mine:
$results = array();
while(($row = mysql_fetch_assoc($result))) {
$results[] = $row;
}
which will create an array like this:
array(array('title' => 'foo',
'text' => 'bar',
'date' => 'baz'),
//...
)
I think what you're after is actually a two-dimensional array (in which the second dimension has three elements). (Correct me if I'm wrong.)
One of the comments under the documentation of mysql_fetch_array has an answer to this:
(Disclamer: This code is unnecessarily verbose. I prefer not changing it though as I have copied it from the above web-page. For improvements, I refer to the comments.)
<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
$i=0;
$keys=array_keys(mysql_fetch_array($result, $numass));
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
foreach ($keys as $speckey) {
$got[$i][$speckey]=$row[$speckey];
}
$i++;
}
return $got;
}
?>
You should then be able to use this function as
<?
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$arr = mysql_fetch_rowsarr($result);
$row_2_title = $arr[2]['title'];
?>