Showing posts with label PHP While Loop. Show all posts
Showing posts with label PHP While Loop. Show all posts

Wednesday, 5 September 2018

php while and loops to fill array does not work

I have a Product master in which I have 2 fields, ONE is for Main Product (Field name 'Under') and SECOND is for Sub-product (Field name is 'Prod_desc) What I want is a nested loop where I capture all codes (field name is Cylno) from transaction Table (ECR_CBDC).

I have 2 nested loops, First while loop is for PRODUCT_MASTER where based on user selection of a Main-product the sub-products are selected and SECOND loop is for collecting the codes for all sub-products.
Now the issue is it collects only 1 value as the FOR loop overwrites the previous value. Is there any other loop which can hold the previous value of each sub-product.
$p=mysql_query("SELECT * FROM PRODMAST WHERE Under='$product'");
while ($p2=mysql_fetch_assoc($p))
{
    $prodesc=$p2['Prod_desc'];

    $dc=mysql_query("SELECT * FROM ECR_CBDC WHERE Prod_desc='$prodesc'  AND usr='$user'");
    $num_rows = mysql_num_rows($dc);
    $fill_from_array = array(); /* as "value"=>"option" */
    for($i = 1; $i <= $num_rows; $i++)
    {
        $row = mysql_fetch_assoc($dc);
        $fill_from_array[$row['Cylno']] = $row['Cylno'];
    }
}


If I understand what you're asking - $fill_from_array only collects one row's worth - I think you need to define $fill_from_array outside of the first loop, so...
$p=mysql_query("SELECT * FROM PRODMAST WHERE Under='$product'");
$fill_from_array = array(); /* as "value"=>"option" */
while ($p2=mysql_fetch_assoc($p))
{
    $prodesc=$p2['Prod_desc'];

    $dc=mysql_query("SELECT * FROM ECR_CBDC WHERE Prod_desc='$prodesc'  AND usr='$user'");
    $num_rows = mysql_num_rows($dc);
    for($i = 1; $i <= $num_rows; $i++)
    {
        $row = mysql_fetch_assoc($dc);
        $fill_from_array[$row['Cylno']] = $row['Cylno'];
    }
}

That way it's not over-writing $fill_from_array each time the while() loop loops. Is that what you mean?

Friday, 31 August 2018

PHP putting four dates in an array from a while loop

Using the below while loop, I get four dates in the echo, which is what I need.

$data = [];

$start = Carbon::createFromDate('2016', '04', '01');
$end = Carbon::createFromDate('2017', '04', '01');

while($start < $end)
{
    $data[] = $start;

    echo $start;

    $start->addMonths('3');
}

Output:
2016-04-01
2016-07-01
2016-10-01
2017-01-01

But when I dump the $data[] array, I just get four collections, each with the same date:
2017-04-01

What am I doing wrong? I just want to put the above four dates in an array.

You're assigning an object instance ($start) to each array entry (and objects are "by reference"), and modifying that object instance, so the same object instance is being changed wherever.... assign a "clone" into your array
while($start < $end)
{
    $data[] = clone $start;
    echo $start;
    $start->addMonths('3');
}

Getting a random array of a while loop in PHP

I have a page set up for testimonials for a company website. Just the standard message first name, last name, message, blah blah..anyways I can pull the message up and have a single entry show up however, I would like it to randomly generate a 'testimonial' I know there is random_array functions already included in PHP but how would I go about it in a while loop? Thats the only way really I have learned to pull information from a MySQL database. So if there is a simpler way I am all ears.

<?php
    mysql_select_db("test", $link);
    $sql= "SELECT * FROM testimonials LIMIT 1";

    $result = mysql_query($sql);
    while($row = mysql_fetch_assoc($result)){
        // var_dump($row['message']); die;
?>
    <p>
<?php
    echo $row['message']; ?>"<br/>
    <div id="quote"><?php echo $row['first_name']. " " .$row['last_name'];?></div><div id="location"><?php echo $row['city']. " , " .$row['state'];?></div><br/>

    <div class="readmore">
        <a href="greenInformation.php">Click Here to view more</a>
    </div></p>

<?php } ?>


Like this?
$sql="SELECT * FROM `testimonials` ORDER BY RAND() LIMIT 1";

Another, and better method, is if you have a ID column, then you could generate a random number and get a row based on that.
$sql="SELECT * FROM `testimonials` WHERE `id`=".mt_rand(1,500);

Friday, 19 September 2014

while loops in PHP

while loops are the simplest kind of loops. In the beginning of each iteration, the while’s truth expression is evaluated. If it evaluates to true, the loop keeps on running and the statements inside it are executed. If it evaluates to false, the loop ends and the statement(s) inside the loop is skipped. For example, here’s one possible implementation of factorial, using a while loop (assuming $n contains the number for which we want to calculate the factorial):
$result = 1;
while ($n > 0) {
$result *= $n--;
}
print "The result is $result";
StatementStatement List
while (expr)
statement

while (expr):
statement list
endwhile;

Loop Control: break and continue

break;

break expr;

continue;

continue expr;

Sometimes, you want to terminate the execution of a loop in the middle of an iteration. For this purpose, PHP provides the break statement. If break appears alone, as in break; the innermost loop is stopped. break accepts an optional argument of the amount of nesting levels to break out of, break n; which will break from the n innermost loops (break 1; is identical to break;). n can be any valid expression.
In other cases, you may want to stop the execution of a specific loop iteration and begin executing the next one. Complimentary to break, continue provides this functionality. continue alone stops the execution of the innermost loop iteration and continues executing the next iteration of that loop. continue n can be used to stop execution of the n innermost loop iterations. PHP goes on executing the next iteration of the outermost loop.
As the switch statement also supports break, it is counted as a loop when you want to break out of a series of loops with break n.

Thursday, 4 September 2014

Loops in PHP

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
  • for - loops through a block of code a specified number of times.
  • while - loops through a block of code if and as long as a specified condition is true.
  • do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true.
  • foreach - loops through a block of code for each element in an array.
We will discuss about continue and break keywords used to control the loops execution.

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.

Syntax

for (initialization; condition; increment)
{
  code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;

for( $i=0; $i<5; $i++ )
{
    $a += 10;
    $b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
This will produce following result:
At the end of the loop a=50 and b=25

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
  
Syntax
while (condition)
{
    code to be executed;
}

Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;

while( $i < 10)
{
   $num--;
   $i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10 and num = 40 

The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax

do
{
   code to be executed;
}while (condition);

Example

The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
  $i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value)
{
    code to be executed;

}

Example

Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<html>
<body>

<?php
$i = 0;

while( $i < 10)
{
   $i++;
   if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
  if( $value == 3 )continue;
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5