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];
}
Related
I have an element stored in the following way:
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["data"]. "</td></tr>";
$data1= floatval($row["data"]);
...
It is a value extracted from a MySQL database, and thus it is stored this way. If I want to get the value of the iteration let's say "i", it is easy, as I do not have to do anything else but how can I obtain the following value in order to perform a substraction? That's to say, data2 - data1? I thought about something similar to $row["data"][i], but I'm not sure it'll work. Thanks!
As you can see in the manual of fetch_assoc this function fetches only one row at a time and that's why we're using a loop.
The same goes for fetch_array and fetch_row.
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
The only solution that I can think of is to loop that array and to store that data in another array according to your requirements, for instance:
$customArr = array();
$i = 0; //counter.
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["data"]. "</td></tr>";
$data1= floatval($row["data"]);
$customArr[$i] = array('id' => $row['id'], 'date' => $date1);
}
Later on, if you want to compare values in the array you should use while and index-based scenarios like $customArr[$i-1], $customArr[$i].
Just make sure that you check the offset.
$i = 0;
while($i < count($customArr)){
}
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;
}
Why does the operator
$array['country'][] return what logically would be $array[]['country']?
What I am saying is this. If you want to extract from a MySQL array, the value of ['country'] for every row, [1],[2]...[n], you have to use
$array['country'][]
despite fact that they are ordered as
$array['row#']['country']
Is this because PHP is reading something backwards, or because I am just lacking some fundamental array information?
FULL-ish code here
$result = array();
foreach($data as $value){
$array['country'][] = $value['country'];
$array['report'][] = $value['report'];
}
$data = $array;
Let me know if I am just dumb... I can't really grasp why this is working this way.
get an id from the db
SELECT id,country,report from yourdb
while ($row = mysql_fetch_array($result)) {
$array['country'][$row['id']] = $row['country'];
$array['report'][$row['id']] = $row['report'];
}
create an id
SELECT country,report from yourdb
$i=0
while ($row = mysql_fetch_array($result)) {
$array['country'][$i] = $row['country'];
$array['report'][$i] = $row['report'];
$i++
}
Why does the operator
$array['country'][]
return what
logically would be
$array[]['country']?
It is because you are constructing the array in that way:
If you use $array['country'][] = $value['country'];, you are adding a new value to the sub-array which is part of the containing array under the country key. So it will be mapped to $array['country'][], you cannot expect otherwise.
If you want it to map to array[]['country'], then (using part of code from
#Lawrence's answer), you'd have to add the new values using explicit numerical indexes as the key:
SELECT country,report from yourdb
$i=0;
while ($row = mysql_fetch_array($result)) {
$array[$i]['country'][] = $row['country'];
$array[$i]['report'][] = $row['report'];
$i++;
}
Assuming that $data has been built by you using a loop like what you pasted in the comments (while($row=mysql_fetch_assoc($result)){$data[]=$row;}) then my answer would be because that's exactly what you asked PHP to do.
The notion $data[] = some-value-here means take that value and add it with to the end of $data array with an auto-generated key I just don't care. That is, PHP will basically see what the last item's key is, add 1 and use that as the key for the item you are adding to the array.
So what you are doing with that loop is building an array whose keys are numbers starting from 0 and incrementing (+1 each cycle, this is the [] effect) and using these keys for the rows you are getting off the database result set.
If you want to access $data in the way you described, then you have to change the way you are building it. See Lawrence Cherone's answer for that.
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.
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.