Loop until returned true with PHP - php

I'm generating a random code, and I need to check to be sure that the code isn't already in the database. I'm assuming this requires some type of a loop. I have my query all setup and I need it to run a block of code again if mysql_num_rows == 0.

Use a do...while loop:
do {
// Your logic
} while (condition);

$key = true;
while($key){
// Do stuff
if(mysql_num_rows($result) > 0) $key = false;
}

Simple upgrade of James L. script - loop script for test if exist login ID in database. If exist, will add +1 after login:
$key = true;
$a = 1;
$login_test_origin=$login_test;
while($key){
$query_test="SELECT count(*) as 'all' FROM user WHERE login='$login_test'";
$row_test=mysql_fetch_array(mysql_query($query_test));
$error=$row_test[all];
if($error > 0) {
$key = true;
$login_test=$login_test_origin.$a;
$a++;
}
else {
$key = false;
$login=$login_test;
}
}
echo"Used login ID: $login";

Here is a quite different route:
while(true){
if(/* Your logic which you expect to be true */){
break;
}
}

Related

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

Unable to insert more than 100 rows at a time using codeigniter

I am trying to insert more than 100 records at a time. if more records them form will not perform any action unless it will submit and redirect to another page.
How to sove this error.
I tried using insert_batch also. But no use.
I changed php.ini post_max_size also,
Somebody please help me.
Below is my code for controller and model
controller code
foreach($chkproduct as $key=>$chkvalue1){
foreach($chkvalue1 as $key1=>$chkvalue2 ) {
$chkvalue=explode("/",$chkvalue2);
$datachk['product_id'] =$chkvalue[0];
$datachk['client_id']=$chkvalue[1];
$ins1=$this->Sub_model->record_count_Product($chkvalue[0]);
$num1=$ins1->num_rows();
$qry1=$ins1->row();
$prodId=$qry1->prod_rand_id;
$datachk['payment_id']=$paymentid;
$datachk['prod_rand_id']=$prodId;
$datachk['sub_type'] =$st1[$chkvalue[0]][$key1];
$datachk['prod_type'] =$pt1[$chkvalue[0]][$key1];
$datachk['quantity'] =$qty1[$chkvalue[0]][$key1];
$datachk['reductionamount'] =$redamount[$chkvalue[0]][$key1];
$datachk['amountafterreduction'] =$ramount[$chkvalue[0]][$key1];
$datachk['individual_amt'] =$ramount[$chkvalue[0]][$key1]+$redamount[$chkvalue[0]][$key1];
$cliname=$clientname[$chkvalue[0]][$key1];
//$date1=$sd1[$chkvalue];
//$datachk['start_date'] = date('Y-m-d', strtotime($date1));
$cliname=$clientname[$chkvalue[0]][$key1];
$expper=explode("-",$per1[$chkvalue[0]][$key1]);
//echo $expper[0];
$smonth=$this->check($expper[0]);
if($smonth>=10){
$startyear=$year1[$chkvalue[0]][$key1]-1;
}else{
$startyear=$year1[$chkvalue[0]][$key1];
}
//echo $st1[$chkvalue];
if($st1[$chkvalue[0]][$key1]==1){
$endyear=$year1[$chkvalue[0]][$key1];
}elseif($st1[$chkvalue[0]][$key1]==2){
if($smonth>=02 && $smonth<=10){$endyear=$year1[$chkvalue[0]][$key1]+1;}else{$endyear=$year1[$chkvalue[0]][$key1];}
}elseif($st1[$chkvalue[0]][$key1]==3){
if($smonth>=02 && $smonth<=10){$endyear=$year1[$chkvalue[0]][$key1]+3;}else{$endyear=$year1[$chkvalue[0]][$key1]+2;}
}
//echo $endyear;
if($smonth==01){$endmonth=12;}else{$endmonth=$smonth-01;}
$ts = strtotime($expper[0]."".$startyear);
$lastdate=date('t', $endmonth);
if($endmonth=='02'){
if($endyear%4==0){
$lastdate1=29;
}else{
$lastdate1=28;
}
}
elseif($endmonth=='04' || $endmonth=='06' || $endmonth=='09' || $endmonth=='11'){
$lastdate1=30;
}else{
$lastdate1=31;
}
//if($endmonth=='02'){$lastdate1=$lastdate-2;}elseif($endmonth%2==1){$lastdate1=30;}else{$lastdate1=31;}
$datachk['start_date'] =$startyear."-".$smonth."-01";
$datachk['end_date'] =$endyear."-".$endmonth."-".$lastdate1;
$datachk['periodicityno'] = $per1[$chkvalue[0]][$key1];
$datachk['year'] = $year1[$chkvalue[0]][$key1];
$datachk['product_status'] =$ps1[$chkvalue[0]][$key1];
if($comboval == 1 && $datachk['reductionamount']!=0){
$datachk['combostatus']=1;
}else{
$datachk['combostatus']=0;
}
$pbyp1=$this->Sub_model->getProductByperiodicity($chkvalue[0]);
$datapdf['products'][]=array("pname"=>$pbyp1->productname,"cliname"=>$cliname,"abbr"=>$pbyp1->productshortname,"pername"=>$datachk['periodicityno'],
"year"=>$datachk['year'],"subtype"=>$st1[$chkvalue[0]][$key1],"perno"=>$pbyp1->periodicity,"dur"=>$pbyp1->duration,"randid"=>$prodId,"prodid"=>$chkvalue[0]);
$this->Sub_model->addSubscribedProduct($datachk);
}
}
Model
function addSubscribedProduct($data) {
foreach ($data as $key => $value) {
if ($value=="") {
$array[$key] =0;
}else{
$array[$key] =$value;
}
}
$res = $this->db->insert('iman_subscribed_products', $array);
//$res = $this->db->insert_batch('iman_subscribed_products', $array);
//echo $sql = $this->db->last_query();
if($res) {
return 1;
} else {
return 0;
}
}
Screen shot of my form
i think you stumpled into php's max_input_vars option
the standard value for this is 1000
just change your value to something higher than that
Be aware you can't change it with ini_set.
For more information click here.
User insert_batch() instead of insert() as follows:
$this->db->insert_batch(array)); // Here the array is multidimensional which can contain number of rows as you need 100s.

Is it possible to create a for loop inside an if condition?

I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.

foreach function only show last value

when i wanna get all value to check with current user ip it just check last ip with current user , i don't know why before values doesnt check.
i fill IPs in a textarea like this : 176.227.213.74,176.227.213.78
elseif($maintenance_for == '2') {
$get_ips = $options['ips'];
$explode_ips = explode(',',$get_ips);
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
}
else {
$maintenance_mode = false;
}
}
}
If you found the right value, you wan't to BREAK out of the foreach loop
$get_ips = $options['ips'];
$explode_ips = explode(',', $get_ips);
foreach($explode_ips as $ips) {
if ($ips == $_SERVER["REMOTE_ADDR"]) {
$maintenance_mode = true;
break; // If the IP is right, BREAK out of the foreach, leaving $maintenance_mode to true
} else {
$maintenance_mode = false;
}
}
yes, you will always override it. Its better to set a default and only set it once:
(Edit: added #Mathlight's answer, the break, in my solution as he suggested)
$maintenance_mode = false;
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
break;
}
}
EDIT : another solution for the record, for the points of a oneliner
$maintenance_mode = in_array($_SERVER["REMOTE_ADDR"], $explode_ips);

PHP - Any shorter way for checking all values within three dimensional array?

Basically I have this code scenario:
if($_SESSION['player_1_pawn'][0]['currentHealth'] <=0 &&
$_SESSION['player_1_pawn'][1]['currentHealth'] <=0 &&
$_SESSION['player_1_pawn'][2]['currentHealth'] <=0 &&
$_SESSION['player_1_pawn'][3]['currentHealth'] <=0 &&
$_SESSION['player_1_pawn'][4]['currentHealth'] <=0) {
//some code here
}
Is there any way to check or to loop through all of the indexes if all of ['player_1_pawn'][index]['currentHealth'] is smaller than 0, instead of writing it one by one like I posted?
Just write a foreach construct that loops through all of the array elements you need to check:
$flag = true; // after the foreach, flag will be true if all pawns have <= 0 health
foreach ($_SESSION['player_1_pawn'] as $value)
{
// for each pawn, check the current health
if ($value['currentHealth'] > 0)
{
$flag = false; // one pawn has a positive current health
break; // no need to check the rest, according to your code sample!
}
}
if ($flag === true) // all pawns have 0 or negative health - run code!
{
// some code here
}
One more solution is to use array_reduce() to check the condition:
if (array_reduce($_SESSION['player_1_pawn'], function (&$flag, $player) {
$flag &= ($player['currentHealth'] <=0);
return $flag;
}, true));
P.S. Be careful when array $_SESSION['player_1_pawn'] is empty.

Categories