Next statement in a While Loop with PHP [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Ok i have a while loop function in my site that pulls in excel documents and parses them to the database i want to check for duplicates and if duplicate skip it:
$content = file($selectfile1);
$posted_content = array();
list($rownum, $row) = each($content);
$posted_content[0] = explode(",", $row);
array_push($posted_content[0], "ID");
$count = 0;
// iterate each row (1 post)
while (list($rownum, $row) = each($content))
{
$count++;
$cols = "orderid, created_at, updated_at, notification_type, radius, available, expiration, ";
$vals = "";
$cols2 = "equipment_id";
$vals2 = "";
....{parsing data)...
}
i want to write in a script that checks to see if the record is a duplicate and if not enter it.
$sql25 = "SELECT * FROM notifications WHERE origin =" . $origin_id . " user_id =12039";
$rs25 = $conn->Execute($sql25);
if($rs25->RecordCount() == 1 || $rs25->RecordCount() >= 1)
{
here is where i need a command. Can you use? next()
--------------------------------------------------
}
else
{
Insert query
}

You are looking for the continue statement.
From the docs:
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
(See http://www.php.net/manual/en/control-structures.continue.php)
example:
<?php
while ( ... ) {
if ($foo = 'bar') {
// skip to the next iteration
continue;
}
}

Related

Laravel insert multi array to mysql [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have multiple arrays that I need to insert into mysql with PHP laravel.
Data it show like this
count: (2) [2, 1]
description: (2) [Array(0), Array(2)]
id_male: (2) [38, 27]
id_resturant: 5
pay: "cash"
price: 76
status: 1
title: (2) ["pepsi", "piza"]
count, id_male , title array i need insert it each male in different row.
Description multi array I will insert it implde
Code in php
$dataa = $request->all();
$title = $dataa['title'];
$count = $dataa['count'];
foreach ($title as $key => $input) {
$data = new Order;
$data->title = isset($title[$key]) ? $title[$key] : ''; //add a default value here
$data->description = $request->description;
$data->id_user = Auth::id();
$data->count = $request->count;
$data->id_male = $request->id_male;
$data->id_resturant = $request->id_resturant;
$data->status = $request->status;
$data->price = $request->price;
$data->note = $request->note;
$data->pay = $request->pay;
$data->uuid = $randomNumber;
$data->save();
return response()->json([
'data'=>$data,
'state'=>true,
'msg'=>''
]);
}
It's not working !
I applaud #u_mulder. You, sir, deserve reputation gain on those comments.
#OP, You have to put return outside of foreach loop...
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.
$dataa = $request->all();
$title = $dataa['title'];
$count = $dataa['count'];
foreach ($title as $key => $input) {
...
}
return response()->json([
'data'=>$data,
'state'=>true,
'msg'=>''
]);
If you want all Order entities to be returned after the loop finished processing, add them in to a special array, for example:
$dataa = $request->all();
$title = $dataa['title'];
$count = $dataa['count'];
$dataToReturn = [];
foreach ($title as $key => $input) {
$data = new Order;
...
$dataToReturn[] = $data;
}
return response()->json([
'data'=>$dataToReturn,
'state'=>true,
'msg'=>''
]);

sql loop returns only one result [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm doing a triple loop to insert values on an array (dataArray[]).
The first one, search for workers
The second one is a "for" for each day of the week
The last one look if the person works this day.
I don't know why it show me only 1 result....
If I change the order (first $sql) it shows me another entry.
// display loop
$sql = "SELECT workers.id, workers.surname, workers.name
FROM workers,employment_contract
WHERE employment_contract.fk_company_teams_id='".$teamID."'
AND employment_contract.fk_workers_id=workers.id
AND employment_contract.initial_date<'".$beginingDate."'
AND (employment_contract.final_date>".$beginingDate."
OR employment_contract.final_date='0000-00-00-00:00:00')
ORDER BY workers.surname ASC";
$stmt = $db->prepare($sql);
$i=-1;
$dataArray;
if($stmt->execute()){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$i++;
// datas in array
$nameInitial = substr($row['name'], 0, 1).'.';
// inserting worker name on array
$dataArray[$i]['workerName']=$nameInitial.' '.$row['surname'];
$workerID = $row['id'];
$totalTime = new DateTime('0000-00-00 00:00:00');
for($j=0;$j<7;$j++){
// changing the current date
$incrementation = 'P'.$j.'D';
$currentDate = date_create($beginingDate);
$currentDate->add(new DateInterval($incrementation));
$currentDate = date_format($currentDate, 'Y-m-d');
// sql search for daily timesheet
$sql = "SELECT initial_date,final_date
FROM working_days
WHERE fk_workers_id='".$workerID."'
AND (initial_date >='".$currentDate." 00:00:00.000')
AND (final_date <='".$currentDate." 23:59:59.999')
ORDER BY id ASC";
$stmt = $db->prepare($sql);
$k=1;
if($stmt->execute()){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// formatting date for calculation
$time1 = utf8_encode(strftime("%R",strtotime("$row[initial_date]")));
$time2 = utf8_encode(strftime("%R",strtotime("$row[final_date]")));
$initialDate = new DateTime(date($row['initial_date']));
$finalDate = new DateTime(date($row['final_date']));
$time3 = $initialDate->diff($finalDate);
$timeFormatted = $time3->format('%H:%I');
$totalTime->add($time3);
// setting the day to implement
if($j==0){$day = 'monday';}
if($j==1){$day = 'tuesday';}
if($j==2){$day = 'wednesday';}
if($j==3){$day = 'thursday';}
if($j==4){$day = 'friday';}
if($j==5){$day = 'saturday';}
if($j==6){$day = 'sunday';}
$arrayBox = $day.$k;
// inserting day value on array
$dataArray[$i][$arrayBox] = $time1.' '.$time2.' <b>'.$timeFormatted.'</b></div><br>';
unset($time1);
unset($time2);
$k++;
}
}
}
$totalTimeFormatted = $totalTime->format('H:i');
// inserting holidays value on array
$dataArray[$i]['holidays'] = 'Vac';
// inserting sum value on array
$dataArray[$i]['sum'] = $totalTimeFormatted;
// if no timesheet is found for the worker we don't show anything
if($totalTimeFormatted==='00:00'){
unset($dataArray[$i]);
}
unset($totalTime);
}
}
I think my dates (dateTime) calculations are not efficient but it's not the problem here.
As mentionned in commentary, I used same variable name for sql statements $stmt.
I corrected it to $stmt1 for the third loop and it's working.

How to remove PHP Warning : count() parameter must be an array that implements Countable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I know this question has been asked many times, but I couldn't find anything that helped me.
My PHP code is returning a warning "Warning: count(): Parameter must be an array or an object that implements Countable" when I try to count rows of a json_decode array, but the code works. How can I get rid of this warning ?
Here is the code (it makes anonymous fields in a database) :
//SQL Query to select my data and get "myVar"
while ($row = $result->fetch_assoc()) {
$l__myVar = json_decode($row["myVar"], true);
$l__id = $row["id"];
for ($i = 0; $i < count($l__myVar["node1"]["node1"]); $i++) {
$l__myVar["node1"]["node1"][$i]["fname"] = SUBSTR(MD5(RAND()) . MD5(RAND()), 1, 6);
$l__myVar["node1"]["node1"][$i]["lname"] = SUBSTR(MD5(RAND()) . MD5(RAND()), 1, 6);
}
$myVar = json_encode($l__myVar);
//Then I am doing my SQL update
}
As I said, it works and, for every node of the decoded JSON it does the "SUBSTR(MD5(RAND()) . MD5(RAND()), 1, 6)", but I keep having the warning in my logs.
I don't want to disable all the warnings, but only find a way to correct this one.
Thanks !
EDIT :
Thanks to the comment, I finally managed to fix it. It looks like sometimes it was not an array but "NULL", so I added this :
if(is_array($l__myVar["node1"]["node1"])){
//Code
}
elseif (!is_array($l__myVar["node1"]["node1"])) {
continue;
}
This way, PHP keep going on without displaying any error message.
It seems that sometime $l__myVar["node1"]["node1"] is not an array,to avoid the warning use
if(is_array($l__myVar["node1"]["node1"])){
for ($i = 0; $i < count($l__myVar["node1"]["node1"]); $i++) {
$l__myVar["node1"]["node1"][$i]["fname"] = SUBSTR(MD5(RAND()) . MD5(RAND()), 1, 6);
$l__myVar["node1"]["node1"][$i]["lname"] = SUBSTR(MD5(RAND()) . MD5(RAND()), 1, 6);
}
}else{
/*Your Code*/
}
You are doing the count on $myVar, where as it seems this should be $l__myVar:
while ($row = $result->fetch_assoc()) {
$l__myVar = json_decode($row["myVar"], true);
$l__id = $row["id"];
for ($i = 0; $i < count($l__myVar["node1"]["node1"]); $i++) {
$l__myVar["node1"]["node1"][$i]["fname"] = SUBSTR(MD5(RAND()) . MD5(RAND()), 1, 6);
$l__myVar["node1"]["node1"][$i]["lname"] = SUBSTR(MD5(RAND()) . MD5(RAND()), 1, 6);
}
$myVar = json_encode($l__myVar);
//Then I am doing my SQL update
}
From the code you have posted, $myVar isn't set til after count(); unless you have it set further up the script.

PHP - Multiple conditions in while statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
For some reason this code won't run in my compiler. The intention (as part of a larger project) is to ping a particular host 3 times, or until successful, whichever comes first. It's not producing any errors, just terminating. It works just fine if I remove the second condition from the while statement, but then I would need to have something more complicated to terminate the loop on a successful ping. I haven't touched PHP in a while, so I'm probably missing something stupid.
<?php
function pingAddress($ip) {
//Set variable to limit loops and end if live
$pass = 0;
$result = 0;
//Create conditions for while loop
while( ( $pass < 3 ) && ( $result = 0 ) ) {
//Count loops
$pass++;
//Execute ping
$output=shell_exec('ping -n 1 '.$ip);
//Display ping results for testing purposes
echo "<pre>$output</pre>";
//Check for "TTL" presence
if(strpos($output, 'TTL') !== false)
{
//Notate positive result
$result++;
//Display for testing
echo "Alive";
}
//Display negative result for testing
else
{
echo "Dead";
}
}
}
PingAddress("8.8.8.8");
You'll kick yourself:
while( ( $pass < 3 ) && ( $result = 0 ) ) {
Should use a double equals - it's a comparison, not an assignment:
while( ( $pass < 3 ) && ( $result == 0 ) ) {
You don't need the second variable $result. Use break instead.
while($pass < 3) {
//Count loops
$pass++;
//Execute ping
$output=shell_exec('ping -n 1 '.$ip);
//Display ping results for testing purposes
echo "<pre>$output</pre>";
//Check for "TTL" presence
if(strpos($output, 'TTL') !== false)
{
//Display for testing
echo "Alive";
break; //exiting while loop
}
//Display negative result for testing
else
{
echo "Dead";
}
}
You can even write less code with
while($pass++ < 3) {
Your second condition is written incorrectly. Change it to $result === 0
Use equal operator not assign.
while( ( $pass < 3 ) && ( $result == 0 ) )
This should work.

check if record exist in Laravel 5.5 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a dynamic input form, I want to check if the record exists, if no then it can not insert data
my controller
$user = Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->get();
if($user->isEmpty()){
// insert
}else{
//message "cannot input"
}
if insert one data, success.. but if insert array in my controller not check..
why in input array data always insert???
This is pseudo for only check id_b
$data = [1,2,3,4];
$data_a = [1,2,3,4];
$masters = Master::whereIn('id_b', $data)->whereIn('id_a', $data_a)->get();
foreach($data as $key => $value) {
$isExisted = false;
foreach ($masters as $master) {
if ($master->id_b == $value[$key] && $master->id_a == $data_a[$key])
{
$isExisted = true;
break;
}
}
if ( ! $isExisted) {
$master = new Banner();
$master->value = your_data;
$master->save();
}
}
You could use exists()
if(Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->exists()) {
do something
}
Also I would suggest you reduce the amount of in-line stuff you're doing, instead something like this:
$id_a = $request->get('id_a');
$id_b = $request->get('id_b');
if(Master::where('id_a','=', $id_a)->where('id_b','=',$id_b)->exists()) {
do something
}
If I understand correctly, you want to insert a Master if a given id_a and id_b doesn't already exists for one Master
If so, you could actually use firstOrCreate :
Master::firstOrCreate(
['id_a' => $request->get('id_a'), 'id_b' => $request->get('id_b')],
['yourcolumntocreate' => columnvalue, ...]
)

Categories