I have an issue. I need to out from inner loop once DB will be updated using PHP but in my case its not happening like this. I am explaining my code below.
for ($i=0; $i < count($result); $i++) {
for ($j=0; $j < 4; $j++) {
$index=$j+1;
$up_sql=" file".$index."='".$result[$i]['img']."' ";
$sqlget=mysqli_query($connect,"select * from cn_sell_info where file".$index."= '' and sid =".$sid);
if(mysqli_num_rows($sqlget) > 0){
$update="update cn_sell_info set ".$up_sql." where sid=".$sid ;
$upsql2=mysqli_query($connect,$update);
break;
}
}
}
Here I have put break statement still same value is updated in cosucative columns as per code. I need once table will updated it will come out from inner for loop means again first for loop will execute again.Please help me.
Break has an optional parameter which indicates the number of levels to break out of. so break is equivalent to break 1. But you can do break 2 which breaks out of two levels of nesting.
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?>
Above is from http://php.net/manual/en/control-structures.break.php which gives good examples.
Instead of using break, you can use while loops with natural exit conditions. You don't need to calculate $up_sql every time, do it once inside the if (it's included in query below).
$num_rows = 0;
$i = 0;
while ($i < count($result) && !$num_rows) {
$j = 0;
while ($j < 4 && !$num_rows) {
$index = $j + 1;
$sqlget = mysqli_query($connect, "select * from cn_sell_info where file{$index} = '' and sid = {$sid}");
$num_rows = mysqli_num_rows($sqlget)
if ($num_rows) {
$update = "update cn_sell_info set file{$index}='{$result[$i]['img']}' where sid={$sid}";
$upsql2 = mysqli_query($connect, $update);
}
$j++;
}
$i++;
}
Related
Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam:
"Convert the following script using for loop without affecting the output:-"
<?php
//Convert into for loop
$x = 0;
$count = 10;
do
{
echo ($count. "<BR>");
$count = $count - 2;
$x = $x + $count;
}
while($count < 1)
echo ($x);
?>
Please help me as my computer sir is out of station and I am really puzzled by it.
Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change.
Try:
$count = 10;
$x = 0;
$firstRun = true;
for(; $count > 1 || $firstRun;) {
$firstRun = false;
echo ($count . "<BR>");
$count -= 2;
$x = $x + $count;
}
echo ($x);
By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false.
EDIT
$firstRun to avoid infiniteLoop
$count in loop
EDIT
Fixed code for new requirement
Removed unnecessary code
Hmmm I don't know if your teacher wanted to own you... but the do{} will execute only once since $count is never < 1.
The output of your teacher's code is:
10
8
I presume there was a mistake in the code and the while would be while($count > 1) which would make more sense (since it's weird to ask for a loop to output only 10 8) and would result in this output:
10
8
6
4
2
20
Then a good for() loop would have been :
$x = 0;
$count = 10;
for($i = $count; $i > 1; $i -= 2)
{
$count -= 2;
echo $i . "<br>";
$x += $count;
}
echo $x;
Which will output the same values.
If you can, ask your teacher for this, and comment the answer ^^ ahahah
I need to make a loop in php that says 1*9 = 9 2*9 = 18 and 1*8 = 8 and 1*7 = 7 etc in loop so the result will be this:
1*7 = 7
2*7 = 14
3*7 = 21
1*8 = 8
2*8 = 16
3*8 = 24
1*9 = 9
2*9 = 18
3*9 = 27
And I need to use a nested loop for that i tried some things out but i cant get it to work here is what is did. But for the most part i don't really understand what nested loops do and what there used for. hope you can help me thanks!
for ($tafel7 = 0; $tafel7 <= 9; $tafel7++) {
for($tafel7 = 0; $tafel7 <= 9; $tafel7++){
for($tafel7 = 0; $tafel7 <= 9; $tafel7++){
$antwoord9 = $tafel7 * 9;
echo "$tafel7 x 8 = $antwoord9 <br>";
$antwoord8 = $tafel7 * 8;
echo "$tafel7 x 8 = $antwoord8 <br>";
$antwoord7 = $tafel7 * 7;
echo "$tafel7 x 7 = $antwoord7 <br>";
};
};
};
Your question is not as clear but if you just want the exact result, here's the code:
for($i = 7; $i <= 9; $i++){
for($j = 1; $j <= 3; $j++){
$result = $i * $j;
echo $j." * ".$i." = ".$result."<br>";
}
}
If you need to print complete tables, then try this:
for($i = 1; $i <= 9; $i++){
for($j = 1; $j <= 10; $j++){
$result = $i * $j;
echo $i." * ".$j." = ".$result."<br>";
}
}
As far as the explanation is concerned, then listen:
A normal loop works by executing a block of statement(s) again and again until a condition is met.
So, nested loops are basically loops in another loop. This means that the block of code will be executed 'n' number of times by the inner loop, and then the inner loop will again be executed by the outer loop, again 'n' number of times.
'n' means whatever the number of times the conditions are met for the respective for loops.
Hope you got my explanation!
You need to loop over your two variables, (1) the left operand and (2) the right operand
for ($right = 7; $right <= 9; $right++) {
for ($left = 1; $left <= 3; $left++) {
$product = $left * $right;
echo "{$left} x {$right} = {$product} <br>";
}
}
In this example, I have to loops one with the times table you want eg 7, 8 and 9 "tafel" and the other one with how many times you want it to run for each times table "$hoeveel". This can easily be altered to more times tables or how many times you want to run, you also only need to export the values once as it cycles through the loops anyways. Hope it helps.
for ($tafel = 7; $tafel <= 9; $tafel++) {
for ($hoeveel = 1; $hoeveel <= 3; $hoeveel++) {
$antwoord = $tafel * $hoeveel;
echo "$tafel x $hoeveel = $antwoord <br>";
}
}
I am trying to implement a quick search bar to search a table populated by an SQL database. The search will not search the table, but will generate SQL statements and search the database. I need to implement a search function using PHP that will use flags to stop the search. This is my code so far:
//THIS CODE WILL EXECUTE WHEN THE SEARCH BUTTON IS PRESSED
if($_REQUEST['btnsearch']){
if(isset($_POST['quicksearch']) and !empty($quicksearch)){
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name ='alerts_table'
AND column_name IN('name', 'year','make','model','alert','date')";
$retvalues = mysqli_query($conn, $sql);
$data = array();
//LOOP POPULATES THE ARRAY WITH THE CURRENT COLUMN NAMES.
for($counter = 0; $counter <= $row=mysqli_fetch_array($retvalues, MYSQL_ASSOC); $counter++){
$string = $row["column_name"];
$data[$counter] = $string;
}
$length = count($data);
$flag = 1;
while($flag == 1){
for($x = 0; $x <= $length - 1; $x++){
$sql3="SELECT * FROM alerts_table WHERE $data[$x] = $quicksearch";
$retvalues2=mysqli_query($conn, $sql3);
if(!empty($retvalues2))
{
//POPULATE THE TABLE WITH RESULTS HERE !!!!!!!!!
$flag = -1; ///HOW CAN I BREAK THE LOOP???
}
}
}
}else{
From the PHP break documentation:
(PHP 4, PHP 5, PHP 7)
break ends execution of the current for, foreach, while, do-while or
switch structure.
break accepts an optional numeric argument which tells it how many
nested enclosing structures are to be broken out of. The default value
is 1, only the immediate enclosing structure is broken out of.
In your case you have two loops; a while loop and an inner for loop. You can set your flag in your inner loop to a value that will stop the while loop, and then use a break to stop the for loop.
$flag = 1;
while($flag == 1){
for($x = 0; $x <= $length - 1; $x++){
// ...
if(!empty($retvalues2))
{
$flag = -1; // set while condition to false
break; // break out of for loop
}
}
// execution continues here after break
// end of while body, start next loop iteration
// $flag == 1 => false, and the while loop will end
}
Okay, so I have a unique problem that I ran into when trying to code a 5x3 star pattern. I can do the for loops to get the 5x3, that's easy. However I need something different than a square.
We can have a maximum of 15 stars. So printing out a full block would look like this:
* * *
* * *
* * *
* * *
* * *
But we can pass in a parameter for the number of stars that we want. So let's pass in 11 instead of 15. We should get:
* * *
* * *
* * *
* *
However, with 11 as my parameter the output is like this:
*
* *
* *
*
It prints out the correct number of rows with the incorrect number of stars. I know why this is, and it's because of the modulus in my code. I also tried a different approach, which printed out one less row than needed. I am stuck and not sure where to go from here.
Here is my code:
<?php
$num = 11;
$rows = ceil($num/3);
$count - 0;
for($j = 0; $j < $rows; $j++){
echo '<div class="row-fluid"><ul class="thumbnails">';
for($i = $num%3; $i < 3; $i++){
echo '*';
$count++;
}
$num-=$count;
echo '</ul></div>';
}
?>
With some simple PHP-Fu:
$stars = 11;
$row_length = 3;
$array = array_fill(0, $stars, '*');
$array = array_chunk($array, $row_length);
$table = '<table border="0">';
foreach($array as $row){
$table .= '<tr><td>'. implode('</td><td>', $row) .'</td></tr>';
}
$table .= '</table>';
echo $table;
Online demo.
The idea should be as simple as: keep drawing until you reach the target number.
So you could do this:
$num = 11;
for( $i=0; $i<$num; $i+=3) {
echo "<div class=\"row-fluid\"><ul class=\"thumbnails\">";
for( $j=0; $j<3 && $i+$j<$num; $j++) {
echo "*";
}
for( ; $j<3; $j++) { // finish the current row (optional, remove if not needed)
echo " ";
}
echo "</ul></div>";
}
Ooh a puzzle!
I don't know if using for was a requirement for your assignment, I prefer while.
$num_of_stars = 15;
$stars_per_row = 3;
while($num_of_stars > 0){
echo "*";
if($stars_per_row == 1){
$stars_per_row = 3;
echo "<br />";
}else{
$stars_per_row --;
}
$num_of_stars --;
}
I don't see why you would have to use two for-loops.
I would do something like this: (I noticed you don't have any <li>'s in your code) Of course you would have to set the class="thumbnails" to include list-style-type:none;
<?php
$num = 11;
$cols = 3;
echo '<div class="row-fluid"><ul class="thumbnails">';
$count = 0;
for($j = 0; $j < $num; $j++){
$count++;
echo '<li style="float:left;">*</li>';
if ($count>=$cols) {
$count = 0;
echo '<li style="clear:both;"></li>';
}
}
echo '</ul></div>';
?>
For this to work, this is what you need.
$num = 11;
$cols = 3;
$rows = ceil($num/$cols);
for($j=0;$j<$rows;$j++)
echo "<div class='row'>";
for($i=0;$i<$cols;$i++){
echo "*";
}
echo "</div>";
}
To show where you went wrong in your code. First, your definition of $count should be = not -. Next, your inner for loop is odd.
First loop through, $num is equal to 11. In your inner loop you set $i = $num%3 which is $i = 2. So the inner loop runs through once while $i++ < 3, echo's one star and increments count once. inner loop exits, you subtract $count from $num making $num=10 and row is completed, next outer loop iteration.
Next time the inner loop runs, $num is 10 so $i = $num%3 becomes $i=1. Inner loop runs 2 times while $i++ < 3, echo'ing 2 more stars and incrementing $count both times making it now 3. after the inner loop you subtract 3 more from $num making it 7 and row ends, outer loop continues.
Next inner loop, $num is 7 so $i = $num%3 becomes $i=1. Inner loop runs 2 times while $i++ < 3, echo'ing 2 more stars and incrementing $count both times making it now 5. after the inner loop you subtract 5 from $num making it now 2, row ends, outer loop continues.
Last iteration of the outer loop (row limit hit), $num is 2 so $i = $num%3 becomes $i=1. Inner loop runs once, echo's one star and inrement count once making it now 8. Inner loop finishes, you subtract 8 from $num making it now -6, row ends, outer loop ends.
Ive managed to loop through a table and get the difference in days between 2 dates adjacent to each other in the table.
Multiple entries have the same date, i have it now that when that date changes, it displays an image however i want it to display the image as many times as the difference in date
$sql = mysql_query("SELECT * FROM Films_Info")
or die(mysql_error());
$last_value = null;
while ($row = mysql_fetch_assoc($sql)) {
if (!is_null($last_value)) {
$a = new DateTime($row['FilmRelease']);
echo "<p>".$row['FilmName']."</p>";
$interval = $a->diff(new DateTime($last_value));
//echo $interval->format('%d days');
$i = 0;
}
$howManydays = $interval->days;
for ( $i; $howManydays; $i++) {
echo "<img src=\"day.jpg\" />";
$howManydays = 0;
}
$last_value = $row['FilmRelease'];
}
for ( $i = 0; $i < $howManydays; $i++) The second is a conditional statement telling when the loop should stop.
The first section in the for loop where it says $i = 0 initialized the variable $i to 0 and then tests the condition $i < $howManydays.
Let's say $howManydays equals 1. That means 0 < 1, so the loop will perform.
At the end of the loop, the third section is called ($i++), so $i is incremented and now equals 1. The second section is called again to test conditions $i < $howManydays which is asking if 1<1 which it's not, so the loop will exit.
So if $howManydays is greater than 0, the loop should happen the integer amount that is in $howManydays.
You will want to remove $howManydays = 0; within the for loop, if you don't want it to only fire once.
The for loop
for ( $i = 0; $i < $howManydays; $i++){
// ...
}
is somewhat equivalent to the while loop:
$i = 0;
while ( $i < $howManydays ){
// ...
$i++;
}
http://php.net/manual/en/control-structures.for.php for more information
In your code above, you should also check if interval was set. You should probably just do an if rather than a while, if only need one interval.
you could just do a simple division on the interval and print out the image that many times
$last_value_u = $last_value->format('U');
$a_u = $a->format('U');
$interval = $a_u - $last_value_u;
$image_count = intval($interval/86400);
for($i=0;$i<$image_count;$i++)
echo "<p><img src=\"day.jpg\" /></p>";
Update
An alternative option would be to loop through the interval:
for($i=$last_value_u;$i<$a_u;)
{
if(intval(($a_u - $i)/86400) == X)
{
// run special code for specific day
}
else
{
// run code for every other day
}
$i+=86400;
}