I think that I may be over trying things with little sleep but I am having problems creating arrays from mysql queries. I have a query like so:
$result = mysqli_query($con,"SELECT * FROM vehicles ORDER BY id");
while($row = mysqli_fetch_array($result)) {
$description = $row['description'];
$description = strtoupper($description);
$id = $row['id'];
}
I want it to create an array like so:
$v[1] = "Myarray1";
I have tried this but it does not work:
$v[ $row['id']] = $row;
Do I have to query like this:
while( $row = mysql_fetch_assoc( $result)){}
and if I do, how I do create the array as I need it?
Many thanks in advance
At no point are you creating an array here. In your loop you are simply modifying some variables that in the context you posted I cannot reason on.
If all you need, no data filtering whatsoever this will do:
$list = Array();
while( $row = mysqli_fetch_array($result) ) {
$list[] = $row;
}
[] basically 'appends' in PHP, it is an ugly mechanism but it works.
If you want to access rows per primary key ( id in your case I think ) then simply replace [] with [$row["id"]]
I'm not exactly sure of the end result you're looking for. But if you want to access the results as $row['column'], where 'column' is a column name in your MySQL database, then you need to use mysql_fetch_assoc. I think this example will help:
while (($row = mysqli_fetch_assoc($result))) {
$v[$row['id']] = $row;
}
$v[1]['description'] is the data in the column description for the record with an id=1
Related
Im trying to set the indexes of a 2d PHP array from numeric indexing to keys. What I have so far is :
$result = mysql_query("SELECT * FROM settings");
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_assoc($result)){
$dataArray[] = $row ;
}
}
$value_to_display = $dataArray[0]['value'];
However, what I'd like to be able to use is something like this :
$value_to_display = $dataArray['some_index_value']['value'];
Anyone know how I can achieve this ? Ive tried replacing making a keys array and then using combine, but I can only do this manually. Any help is appreciated!
How about
while ($row = mysql_fetch_assoc($result)) {
$dataArray[$row['somefield']] = $row;
}
Assuming that somefield is unique, you'll get an array keyed by that field's values. If you need to key names to come from somewhere else, e.g.
$keynames = array('foo', 'bar', 'baz', ....);
$idx = 0;
while($row = mysql_fetch_assoc($result)) {
$dataArray[$keynames[$idx]] = $row;
$idx++;
}
just make sure you have enough keynames to handle all the records you get back from the query.
I'm trying to create an array(); from the mysql results/query.
The Array OUTPUT should look exactly like this:
{"1":{"info":"Rooz","lat":51.503363,"lng":-0.127625},
"2":{"info":"Michelle","lat":51.503343,"lng":-0.127567}}
So I tried to do it this:
$sql = "SELECT id, name, lat, lng FROM positions ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
$testLocs = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$testLocs[] = $row;
}
print_r(json_encode($testLocs));
but the OUTPUT of the code above is like this:
[{"id":"1","name":"Rooz","lat":"51.5033630","lng":"-0.1276250"},{"id":"2","name":"Michelle","lat":"51.503343","lng":"-0.127567"}]
I have no idea how to achieve the output that I want in an array.
Could someone please advise on this?
any help would be appreciated.
Change
$testLocs[] = $row;
to
$testLocs[$row["id"]] = array("info"=>$row["name"], "lat"=>$row["lat"], "lng"=>$row["lng"]);
Addition to #Sean's answer: You could also use (array) $row instead of create the array manually with every key:
$testLocs[$row["id"]] = (array) $row;
If you change your query in the future, you don't have to change this line.
PHP arrays are not built in a distinct way from JSON objects:
$testLocs[$row["id"]] = $row;
If you purposely want to exclude the $id property from $row you can remove it from the $row array first.
$id = $row["id"];
unset($row["id"]);
$testLocs[$id] = $row;
I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}
I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>
I want to retrieve a set of records from a MySQL table as an array.
So far I was able to retrieve each row as an associative array. But I want all the rows in one array because I have to access that complete object in jQuery to display them.
This is what I have done so far.This is my .php script to retrieve data
//select query
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
$numRows = mysql_num_rows($result); //to iterate the for loop
//passing as an associative array
for ($count = 0; $count < $numRows; $count++){
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo json_encode($row);
}
This is what I currently get
{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"}
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"}
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"}
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}
But I want this result set as follows.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
I seek help in doing this. Thanks in advance.
Put it all in one array, then json_encode it:
$json = array( );
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
$json[] = $row;
}
echo json_encode( $json );
FYI: there's no need to count the number of results to loop. mysql_fetch_* will internally keep a pointer to the current record and increment that on each call. That makes it a perfect candidate to use in a simple while loop. Also, instead of mysql_fetch_array and passing MYSQL_ASSOC, you can simply use mysql_fetch_assoc instead, a method I much prefer. Makes the code easier to read too (in my opinion, anyway).