Fetch Value in reverse order using while loop - php

I have a code which retrieves the values from data base.but i want to fetch this values in reverse order.See this example
While($row=mysql_fetch_assoc($rs)){
echo $row['id']."<br>";//gives 1 and 2 and so on
echo $row['val']."<br>";// gives abc and def and so on
}
But i want
2
def
1
abc
How could i do this .i don't wanna use the Query for this like use of ORDER BY.so can i control this at PHP End??

while($row = mysql_fetch_array($rs)){
$data[] = $row;
}
$data = array_reverse($data,true);
while($data){
}
Haven't tested it though
I tested it in this site and it works. Here's the snippet I used:
$data = array(1 => array("foo" => "bar"), 2 => true);
$data = array_reverse($data,true);
print_r($data);
Edit:
Using your edited answer, I got this:
$data = array(1 => array(1, "abc"), 2 => array(2, "def"));
$data = array_reverse($data,true);
foreach($data as $d){
echo "id>".$d[0]." | val>".$d[1]."<br />";
}

Store your data in an array (in your while-loop). After that, you can use array_reverse to reverse item order.

You can also use a cursor that iterates through your result set -moving backwards and forwards - using something like PDO - and probably similar variations for each other type of connection:
cursor_orientation
For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the PDO::FETCH_ORI_* constants, defaulting to PDO::FETCH_ORI_NEXT. To request a scrollable cursor for your PDOStatement object, you must set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you prepare the SQL statement with PDO::prepare().
But using an array_reverse might be simpler. Having said that, ordering the data in the query would be simpler again (and probably much more efficient).

$result = $mysqli->query($query);
for($i = $result->num_rows - 1; $i>0; $i--){
$result->field_seek($i);
$finfo = $result->fetch_field();
echo $finfo->id;
echo $finfo->val;
}

Related

php mysql remove numbered key's from fetched array row

I am trying to do a mysql fetch but it keeps adding numbered and labeled keys to the array. I want it to record only the labeled names and data in the array.
Am I using the wrong mysql call?
global $con,$mysqldb;
$sql="SHOW FIELDS FROM ".$dbtable;
$tr = mysqli_query($con,$sql);
$tl = mysqli_fetch_array($tr);
$tl = mysqli_fetch_array($tr);
$sql="SELECT * FROM ".$mysqldb.".".$dbtable." ORDER BY ".$tl['Field']." LIMIT 3";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$table[$row[1]] = $row;
}
foreach($table as $item => $data){
foreach(array_keys($data) as $pointer => $field) {
echo"pointer=".$pointer."\t";
echo"field=".$field."\n";
echo "data=".$data[$field]."\n";
}
}
reults
pointer=0 field=0 data=3823
pointer=1 field=PID data=3823
pointer=2 field=1 data=AA
pointer=3 field=symbol data=AA
pointer=4 field=2 data=1
pointer=5 field=value data=1
I want to omit 0, 2, & 4 from the array.
Take a look at the PHP.net manual for the mysqli_fetch_array() function.
You'll see there's an option called resulttype that will accept 1 of 3 values - MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH the default.
Using MYSQLI_ASSOC will remove the numbered keys.
Or check mysqli_fetch_assoc().
Thanks to thebluefox for a speedy response.
I replaced the fetch with:
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
And now the results are being recorded as they should.

How do I iterate over the results in a MySQLi result set?

I want to loop through the result set of the following query:
select uid from userbase
I am currently employing the following loop, but I can get only the first value.
$i = 0;
$output = mysqli_query($mysqli, "select uid from userbase");
while ($row = $output->fetch_array()) {
$deviceToken = $row[$i];
echo $deviceToken;
$i++;
}
What might be the problem? Is it fetch_array()?
You will notice while researching the PHP manual at https://php.net/manual/en/mysqli-result.fetch-array.php that fetch_array() has the default behavior of generating a result set that contains both indexed and associative keyed elements (MYSQLI_BOTH).
You could use either MYSQLI_ASSOC ...
while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
echo $row['uid'];
}
or MYSQLI_NUM...
while ($row = $output->fetch_array(MYSQLI_NUM)) {
echo $row[0];
}
That said, there is actually an easier, more brief, and more efficient way because MySQLi's query() can be used as an iterable object. The step of calling fetch_array() on every iterated row can be completely omitted. You can write your $output into a foreach() and away you go (refer to column values by the associative key).
foreach ($output as $row) {
echo $row['uid'];
}
I do recommend that you use all "object oriented" syntax rather than procedural or a mix of styles. "Object oriented" syntax is more brief and in my opinion it is easier to read.
Finally, the way that your code is constructed, $i starts at 0 and increments with every row. However, your result set (with both styles of keys) will look something like this...
[
0 => [0 => 1, 'uid' => 1],
1 => [0 => 2, 'uid' => 2],
2 => [0 => 3, 'uid' => 3]...
]
Your first iteration works because $output[0][0] (aka $row[0]) exists.
Your second iteration doesn't work because $output[1][1] (aka $row[1]) doesn't exist.
Nor does the third iteration with $output[2][2] (aka $row[2]) doesn't exist. And so on.You see, the iteration was truly the part that fouled up your script.
You need to define a array and store your data into array inside loop .
Use MYSQLI_ASSOC no need for incremented value
$deviceToken=array();
while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
$deviceToken[] = $row['uid'];
}
print_r($deviceToken);
for($i=0;$i<=count($deviceToken);$i++){
echo $deviceToken[$i];
}

How to store unknown number of columns from mysql query in php

I have a mysql table and I am querying it through PHP. The query is like below
SELECT min(Age) , max(Age) , min(Workexp) , max(Workexp) FROM data_table
Depending on user's choice, it may have to return more or less min/max pairs but it will always return 1 row only.
Had the number of columns been constant, I could have simply used below to store the results in an array and use it.
$result=mysql_query($sql);
while ($obj = mysql_fetch_object($result))
{$SelFieldNameArray[] = array('field_name1' => $obj->field_name1, 'field_name2' => $obj->field_name2);}
However because of variable number of columns, I am not able to do this here. Could anyone please help me regarding this. Thank you.
You can fetch the result as an associative and use that.
while ($result = mysql_fetch_assoc($result)) {
$SelFieldNameArray[] = $result;
}
Firstly: Please switch to using mysqli_* since mysql_* is deprecated.
Try this query which defines attribute names for your min and max selects
SELECT
min(Age) AS minAge,
max(Age) AS maxAge,
min(Workexp) AS minWorkexp,
max(Workexp) AS maxWorkexp
FROM data_table
Now your 1 row, which should have had 4 columns to begin with, should have those 4 attributes named after the given attribute names.
So when requested as associative array (i.e. using mysqli_fetch_assoc), you can access them directly:
$result = mysqli_fetch_assoc($query);
echo 'minAge = '.$result['minAge']
.'maxAge = '.$result['maxAge']
.'minWorkexp = '.$result['minWorkexp']
.'maxWorkexp = '.$result['maxWorkexp'];
To give it to you as an object, use mysqli_fetch_object:
$result = mysqli_fetch_object($query);
echo 'minAge = '.$result->minAge
.'maxAge = '.$result->maxAge
.'minWorkexp = '.$result->minWorkexp
.'maxWorkexp = '.$result->maxWorkexp;
Your problem is you are selecting dynamic number of columns in your query.
You can retrieve them this way:
$SelFieldNameArray = array();
//MYSQL_NUM retrieves all your rows in numbered indexes so you can
//easily loop through them
$row = mysql_fetch_array($sql,MYSQL_NUM);
foreach($row as $k=>$v) {
$SelFieldNameArray[] = array('field_name'.($k+1)=>$row[$k]);
}
Output:
array
0 =>
array
'field_name1' => 5
1 =>
array
'field_name2' => 10
//...etc.
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
First of all, if it returns only one row, you do not need while. Second, you can use mysql_fetch_assoc to fetch both column names and values. For example:
$sql = "SELECT min(Age) , max(Age) , min(Workexp) , max(Workexp) FROM data_table";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$columns = array_keys($row);
print_r($columns); //prints the column names
echo $columns[2]; //prints the name of the third column
echo count($columns); //prints total number of columns
print_r($row); //prints all columns and their values
echo $row[$columns[2]]; //prints what is in the third column
foreach ($row as $key=>$value) {
echo $key.":".$value; //prints min(Age):1 for example
}
NOTE: Do not use mysql_ function since they are deprecated.

create array from mysql query php

I have a little problem that I don't understand. I have a db that has an owner and type (and more off course). I want to get a list of all the type values that has owner equal to the current user, but I get only two result
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ORDER BY id DESC ";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
prints out:
Array ( [0] => 18 [type] => 18 )
and
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ";
prints out:
Array ( [0] => 16 [type] => 16 )
And the result should be something like 19, 19, 18, 17, 16 in an array. Thats all the types that has me as set as owner.
I have got this working now:
for ($x = 0; $x < mysql_num_rows($result); $x++){
$row = mysql_fetch_assoc($result);
echo $row['type'];
}
Here I print out all the values correctly, but I need to create an array with all the values. I though I could use array_push, but there most be a better way of doing it. I thought I would get all the type values with a simple mysql query.
Very often this is done in a while loop:
$types = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['type'];
}
Have a look at the examples in the documentation.
The mysql_fetch_* methods will always get the next element of the result set:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.
It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].
THE CORRECT WAY ************************ THE CORRECT WAY
while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows); // pop the last row off, which is an empty row
You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
while($row = mysql_fetch_assoc($result)) {
echo $row['type'];
}
You could also make life easier using a wrapper, e.g. with ADODb:
$myarray=$db->GetCol("SELECT type FROM cars ".
"WHERE owner=? and selling=0",
array($_SESSION['username']));
A good wrapper will do all your escaping for you too, making things easier to read.
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.
https://en.wikipedia.org/wiki/SQL_injection
I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.

Unexpected result in mysql_fetch_array

I am using a complex join statement to get data from my 'items' table where 'column1' is equal to the value of table2.ID
This is in a mysql_query() statement, and it should return 3 rows.
Now my understanding is that by using
$array=mysql_fetch_array($queryresult);
I can then loop through each 'row' using a
foreach($array as $output) {
echo $output['ID'];
}
This is however not returning what i want. Using print_r on $output is outputting non-sensical information.
So, yes it is ver much back to basics, but obviously i have missed the point.
You need to use while loop:
while($row = mysql_fetch_array($queryresult)){
// handle each row
}
This is how I do it. This is by far not the end all solution... Just an example of how I do it.
$result = mysql_query($query, $dbconnect) or trigger_error("SQL", E_USER_ERROR);
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["questionId"];
echo $row["questionText"];
echo $row["questionReview"];
$i++;
}
http://php.net/manual/en/function.mysql-fetch-array.php
$array has a single row in it when you get to the loop, so when you say $output['ID'] you are one level deeper than you are expecting, walking through the columns instead of each row. When the ids don't exist or are translating to integers, thats where the nonsense comes in.
Use while($row = mysql_fetch_array($queryresult)) to walk through each row in the result set, then access the column values from $row['id'], $row['name'], etc. It will return false when there are no more rows.
The result will always be a single flat array with a single row per index id, regardless of the join dimensions.

Categories