I want to use for loop instead of using the conventional while loop
Like this one (psuedo code):
$list = mysqli_fetch_array($result);
for($x = 0; $x < sizeof($list); $x++){
echo $x;
}
Is this possible?
There's no reason why you can't use a while loop. That being said, when you now use sizeof($list), you will get the number of columns selected from the query (this $list variable has as many elements as columns was selected). You will therefor attempt to loop (and ouput the count of) the number of columns you fetched.
Instead, you might want to do something like this below - fetch the number of rows based on mysqli_num_rows(), which is exactly that - the number of rows returned by the query.
for ($x = 0; $x <= mysqli_num_rows($result); $x++) {
$row = mysqli_fetch_array($result);
var_dump($row);
}
Although, the standard way - and in my opinion the best way - of doing it is via while.
while ($row = mysqli_fetch_array($result)) {
var_dump($row);
}
Related
I'm attempting to combine two pages into one for simplicity, however to do so, I need to find a way to combine a for() loop from one page with a while() loop from the other page, so that they both work in the same way.
This is what they currently are:
for($i = 0; $i < $count; $i++) {
and
while($widget = $grabWidget->fetch_array()) {
As you may see, the for() loop does not loop through a MySQLi query, but rather an array of values which are identical to that of what is also in a database.
The second while() loop grabs a set of identical values from the database. However they both must stay on their current bases.
My question is, can both loops be combined into one, while still being able to loop through individual database and array elements?
Thanks in advance :)
EDIT: As requested, here are both the usages for the loops.
if($grabWidget = $db->query("SELECT * FROM editor_widgets"))
{
while($widget = $grabWidget->fetch_array())
{
$id = $core->input($widget[1]);
$coords[0] = $core->input($widget[4]);
$coords[1] = $core->input($widget[5]);
$temp = $core->input($widget[2]);
$content_out = $core->output($widget[3],true);
and
if(isset($_POST['widgets']))
{
$widget = $_POST['widgets'];
$count = count($widget);
for($i = 0; $i < $count; $i++)
{
$id = $core->input($widget[$i][0]);
$content_in = $core->input($widget[$i][1]);
$coords[0] = $core->input($widget[$i][2][0]);
$coords[1] = $core->input($widget[$i][2][1]);
$temp = $core->input($widget[$i][3]);
$content_out = $core->output($widget[$i][1],true);
The new simplified page must have the ability to loop through from either an array OR a MySQLi query. So basically, I want to use the for() loop and have it also work with MySQLi
Add an interator $i thats in while thats it.
$i=0;
while($widget = $grabWidget->fetch_array()) {
++$i;
// YOUR CODE
}
I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.
I'm working on pagination, and for some reason I cannot use mysql_fetch_array to loop through a result more than once.
//both $page and $imagesPerPage != 0
$offset = $page * $imagesPerPage
while ($row = mysql_fetch_array($result)) {
$total_images++;
}
echo $total_images;
//echos correct amount
$row = null;
$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
$images_to_offset++;
}
echo $images_to_offset;
//echos 0... which is wrong
Should I be using a different php function to get row data in a database?
Thanks!
This is the error
while ($row = mysql_fetch_array($result)) {
$total_images++;
}
once you fetched the array the array pointer set to the end.
use this
$total_images=mysql_num_rows($result);
and
$images_to_offset=mysql_num_rows($result);
OR
To reset the position of pointer Use mysql_data_seek(). it moves internal result pointer
If you wish to start fetching from the beginning after you've already fetched, you'll need you use mysql_data_seek().
Also, please note that the mysql line of functions have been deprecated, and the community is encouraging use instead of MySQLi or PDO_MySQL lines of functions.
You could point the pointer back to the first row with mysql_data_seek.
mysql_data_seek($result, 0);
Also see: http://ca2.php.net/manual/en/function.mysql-data-seek.php
You have to 'rewind' the array, by using the mysql_data_seek function:
$offset = $page * $imagesPerPage
while ($row = mysql_fetch_array($result)) {
$total_images++;
}
echo $total_images;
//echos correct amount
$row = null;
mysql_data_seek(); // <-- rewind to the beginning
$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
$images_to_offset++;
}
echo $images_to_offset;
mysql_fetch_array not only returns an array that corresponds to the fetched row, it also moves the internal data pointer ahead.
There are more than one way of dealing with this, the most obvious is to "park" your result in an array itself and then work from there. Or query 2 times. Or use mysql_data_seek. In your case, maybe mysql_num_rows is more appropriate, since your code indicates you only want to know how many rows you have to iterate through, and thats what this function is there for.
Whatever decide, keep in mind that use of the mysql extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used.
Try using mysql_num_rows() , that way you don't have to iterate the $result twice which is giving you error in the second loop as you have to reset the result pointer. So do it like this which only iterates once:
//both $page and $imagesPerPage != 0
$offset = $page * $imagesPerPage
$total_images = mysql_num_rows($result);
echo $total_images;
//echos correct amount
$row = null;
$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
$images_to_offset++;
}
echo $images_to_offset;
As a side note, you should try to migrate to MySQLi or PDO_MySQL to access mysql as the interface you are using is now deprecated, see the red box in http://es.php.net/manual/en/function.mysql-num-rows.php
You can only loop through the results array once, after that they effectively 'disappear'. the way to loop over the results multiple times is to store them into a new array during the first loop, then loop over the new array as many times as you want...
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.
For whatever reason, I need to go through a MySQL result set twice. Is there a way to do it?
I don't want to run the query twice and I don't want to have to rewrite the script so that it stores the rows somewhere and then reuses them later.
This is how you can do it:
$result = mysql_query(/* Your query */);
while($row = mysql_fetch_assoc($result)){
// do whatever here...
}
// set the pointer back to the beginning
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)){
// do whatever here...
}
However, I would have to say, this doesn't seem the right way to handle this. Why not do the processing within the first loop?
For mysqli you should do the following;
$result= $con->query($sql); // $con is the connection object
$result->data_seek(0);
Try whether mysql_data_seek() does what you need.
mysql_data_seek() moves the internal
row pointer of the MySQL result
associated with the specified result
identifier to point to the specified
row number. The next call to a MySQL
fetch function, such as
mysql_fetch_assoc(), would return that
row.
row_number starts at 0. The row_number
should be a value in the range from 0
to mysql_num_rows() - 1. However if
the result set is empty
(mysql_num_rows() == 0), a seek to 0
will fail with a E_WARNING and
mysql_data_seek() will return FALSE
Alternative to the data seek is to store the values into an array:
$arrayVals = array();
$result = mysql_query(/* Your query */);
while($row = mysql_fetch_assoc($result)){
$arrayVals[] = $row;
}
// Now loop over the array twice instead
$len = count($arrayVals);
for($x = 0; $x < $len; $x++) {
$row = $arrayVals[$x];
// Do something here
}
$len = count($arrayVals);
for($x = 0; $x < $len; $x++) {
$row = $arrayVals[$x];
// Do something else here
}
I confess I haven't tried this, but have you tried after your first iteration
mysql_data_seek($queryresult,0);
to go to the first record?
You can use mysql_data_seek to move the internal pointer to the beginning of the data set. Then, you can just iterate through it again.
Well, you could always count the number of rows you read, and then do something like this:
if (rownumber == mysql_num_rows($result)) { mysql_data_seek($result, 0); }
Don't know why you would need to, but there it is.