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)){
}
Related
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];
}
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']);
}
What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}
I'm probably missing something easy, but I seem to be blocked here... I have a MySQL database with two tables and each table has several rows. So the goal is to query the database and display the results in a table, so I start like so:
$query = "SELECT name, email, phone FROM users";
Then I have this PHP code:
$result = mysql_query($query);
Then, I use this to get array:
$row = mysql_fetch_array($result);
At this point, I thought I could simply loop through the $row array and display results in a table. I already have a function to do the looping and displaying of the table, but unfortunately the array seems to be incomplete before it even gets to the function.
To troubleshoot this I use this:
for ($i = 0; $i < count($row); $i++) {
echo $row[$i] . " ";
}
At this point, I only get the first row in the database, and there are 3 others that aren't displaying. Any assistance is much appreciated.
You need to use the following because if you call mysql_fetch_array outside of the loop, you're only returning an array of all the elements in the first row. By setting row to a new row returned by mysql_fetch_array each time the loop goes through, you will iterate through each row instead of whats actually inside the row.
while($row = mysql_fetch_array($result))
{
// This will loop through each row, now use your loop here
}
But the good way is to iterate through each row, as you have only three columns
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['email']." ";
}
One common way to loop through results is something like this:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
// do stuff with $row
}
Check out the examples and comments on PHP.net. You can find everything you need to know there.
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.