I have a while loop that contains another while loop. Both loops are iterating over different mysql result sets. The problem is that the second time the outer while loop calls the inner while loop it doesn't run. Does Mysql_fetch_row discard itself after it has been iterated over?
Here is what the code looks like:
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
And here is what the output is like: You can see that the $result holds four records and the output is showing that the loop is working correctly. However, the inner loop over the $dictionary result set doesn't run the second time $result is being iterated over. Any ideas why? I tried to use mysql_fetch_array as well but still the same result.
Thanks
When ever you are calling mysql_fetch_row($dictionary) It gives you a particular column details in the row and it deletes it from the $dictionary array.
So there are no elements for next use.
Instead of declaring $dictionary outside declare it in while loop. It will solve your problem.
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
$dictionary=("Select * from database");//your own logic
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
or you can use mysql_data_seek().
Related
while ($row = mysqli_fetch_assoc($result)) {
$price6 = substr("{$row['price']}",0,15);
}
for example in this code if its going to print out five results, i want to do something immediately after the third result is printed out. Please someone help me out.
You can either have a variable $i = 0 before the loop and count it in the loop and after let say $i == 3 you can write break and go out of the loop OR your can write a for loop and do the same:
Example 1:
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
$price6 = substr("{$row['price']}",0,15);
$i++;
if ($i == 3) break;
}
Example 2:
$row = mysqli_fetch_assoc($result);
for ($i = 0; $i < count($row); $i++) {
// do something
if ($i == 3) break;
}
I haven't tested this on your example but just to give you an idea.
The other suggestions here are good, here's another way of doing it:
Replace your while loop with the following:
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
Now you can use that array in foreach loops like so
foreach($rows as $id => $row){
//id is now the "count"
//keep in mind it starts from zero
}
Did you try adding a counter?
$teller=0;
while ($row = mysqli_fetch_assoc($result)) {
$price6 = substr("{$row['price']}",0,15);
if ($teller == 3) {
// do something magical
}
$teller++;
}
I'm trying to set up my php script to add to a value to the previous value that is returned in the loop. Below is an example. The number on the left is the number that comes from the loop and is returned as $axle. The number on the right is the total as is the number from above added to the number on the right '$totalAxle'. I tried a few examples that I found online but they did not seem to work for me. My latest attempt which is the code below resulted in an error Notice: Array to string conversion
6/6
6/12
4/16
echo "<td>";
$axle = "Not Found!";
foreach ($railunit->railUnit as $ru) {
if((string)$ru->rvXMLfilename == $rvXMLfilename){
$axle = (string)$ru->axleCount;
$array = array("axle" => $axle);
$axleTotal = array();
$i = 1;
$previous = 0;
foreach($array as $key => $val) {
$axleTotal['number'.$i] = $val+$previous;
$previous += $val;
$i++;
};
}
}
echo $axle, "/", $axleTotal;
echo "</td>";
Turns out that your foreach could be way simpler. I was able to solve it together with OP after a discussion in chat.
// add $total = 0; OUTSIDE of any loops so it doesnt get overwritten
$total = 0;
foreach($railunit->railUnit as $ru) {
$axle = $ru->axleCount;
$total = $total + $axle;
}
echo $axle . "/" . $total;
I have the following script that divides the total by the number of people and stores the results in an array.
Instead of dumping the $result array at the end, I wonder if I could echo out the value of each array item in the for loop as it goes?
// initial conditions
$total = 1001;
$people = 5;
// count what is the minimal value, that all the results will have
$value = floor($total / $people);
$result = array_fill(0, $people, $value);
// distribute missing "+1"s as needed in the result
$overheads = $total - $value * $people;
for ($i = 0; $i < $overheads; $i++) {
$result[$i]++;
}
// voila...
var_dump($result);
So, the above script should loop out:
200
200
200
200
201
Technically speaking, you can't "echo out the value of each array item
in the for loop as it goes" because you're not filling the arrays
in a loop, you're filling with array_fill(). The loop you have is to
work with the remainder. If you echo out there, you'll get partial
results. So either you keep your code and echo the values at the end,
with a simple line:
foreach ($result as $r) echo "$r\n";
Or you modify your code to fill the arrays in another manner. Which
might be interesting. Note that you're forgetting about the modulus
operator, %, for the remainder of division. This line:
$overheads = $total - $value * $people;
Could be written simply as:
$overheads = $total % $people;
An idea to fill in a loop:
// initial conditions
$total = 1001;
$people = 5;
$value = floor($total/$people);
$overheads = $total % $people;
foreach (range(1, $people) as $p) {
$r = $value;
if ($overheads) {
# if there is still remainders:
$r++;
$overheads--;
}
# echo the value and also store it
echo "$r\n";
$result[] = $r;
}
// initial conditions
$total = 1001;
$people = 5;
// count what is the minimal value, that all the results will have
$value = floor($total / $people);
$result = array_fill(0, $people, $value);
// distribute missing "+1"s as needed in the result
$overheads = $total - $value * $people;
$i = 1;
foreach($result as $res)
{
if ($i < $people){
echo $res . "\n";
}else{
echo $res + 1 . "\n";
}
$i++;
}
// voila...
I have some data, which i currently have hard coded, basically i am trying to split the numbers, 1-port and recreate it as
'INSERT INTO '.$tbl_name.'(PortNumber) VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(145),(146),(147),(148),(149),(150),(151),(152),(153),(154),(155),(156)';
and etc.. i have a pretty good start i think..
PHP
//post vars
$port = 24; //(int)$_POST['ports'];
$super = 2; //(int)$_POST['super'];
$col = 12; //(int)$_POST['columns'];
$row = 2; //(int)$_POST['rows'];
//rest of vars
$halfPort=$port/2;//12
$colHalf = $col / $super;//6
$half=$colHalf-1;//5
$count=1;
$and=1;
$one=1;
echo "<h1>here goes nothen</h1><br><br>";
//sperate port
$finalArray = array();
for ($i = $port; $i >= 1; $i -= $colHalf) {
$tempArray = array();
for ($j = 0; $j < $colHalf; $j++) {
$tempArray[] = $i - $j;
}
$tempArray[]= sort($tempArray);
$finalArray[] = implode(",", $tempArray);
}
$finalArray = array_reverse($finalArray);
echo "<pre>" . print_r($finalArray, true) . "</pre>";
echo "<br><br>";
//sql for insert
$sqlinsert='
INSERT INTO '.$tbl_name2.'
(PortNumber) VALUES ';
$start='(';
$end=')';
//preset b
$b=0;
for($c = $port; $c >= 1; $c -= $colHalf) {
$queryStart = array();
$queryStart[]=explode(',',$finalArray[$b]);
echo "<pre>" ."start". print_r($queryStart, true) . "</pre>";
for($s=0; $s<6; $s+=$and) {
$queryEnd = array();
$queryEnd[] = $start.$queryStart[$s].$end;
echo "<pre>" ."end". print_r($queryEnd, true) . "</pre>";
}
$b+=1;
}
to view it live insert it here: http://phptester.net/index.php?lang=en
baisaclly it gets to $queryEnd, everything goes down hill, any ideas?
I'm not quite sure what you want to do, but if you just want to build something like the INSERT query you can do something like:
$tbl_name = '?';
echo 'INSERT INTO '.$tbl_name.'(PortNumber) VALUES ('.implode('),(', array_merge(range(1,12),range(145,156))).')';
I think I see it. You are reinitializing your $queryEnd array every time the For loop runs. Move that out of the For loop.
Mike
I've got a query which finds the top 10 most loaned books in my loan table, however i want to store these ten values into a single array so that I can then use the array again. Here is the code I have so far... Thanks for any help in advance!
//select a database to work with
$selected = mysql_select_db("ds2",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT book.title, book.book_id, count(book.book_id) AS count_book_id, loan.book_id FROM book
INNER JOIN loan ON book.book_id = loan.book_id
GROUP BY book.book_id ASC
ORDER BY count(book.book_id) DESC");
$titles = array();
while($row = mysql_fetch_array($result))
{
echo $row['title'];
echo "<br>";
}
echo "<br><br>";
for($index = 1; $index <= 10; $index++)
{
array_push($titles,$result[$row]);
print_r($titles);
echo "<br>";
}
Rather than echo $row['title'] You can use below code to store them into an array
$titles[] = $row['title'];
Use array notion to access them later.
$titles[0]; // 1st item
$titles[1]; //2nd item
You can even use a foreach loop to loop through all the items.
foreach($titles[] as $title)
echo $title;
Below will allow you to get a comma separated string(Just for your information if you need it)
$comma_separated_titles = implode(",", $titles);
Try,
while($row = mysql_fetch_array($result))
{
echo $row['title'];
$arr[] = $row['title']; //Store in an array
echo "<br>";
}
echo "<br><br>";
//Since you need only 10 values, else this for loop is not required.
for($index = 1; $index <= 10; $index++)
$titles[] = $arr[$index]['title'];
unset($arr); //unset the original array if you don't need it anymore.
print_r($titles); //Print top 10 values
echo "<br>";
You should fill your array in the loop, not after it in a separate loop:
$count = 0;
while($row = mysql_fetch_array($result))
{
echo $row['title'];
echo "<br>";
if ($count < 10)
{
array_push($titles, $row);
}
$count++;
}