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'=>''
]);
Related
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.
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, ...]
)
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;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have string like this:
My code is:
$html = new DOMDocument();
$html->loadHTML($message);
$items = $html->getElementsByTagName('div');
foreach($items as $item) {
$headline = array();
if($item->childNodes->length) {
foreach($item->childNodes as $i) {
$headline[$i->nodeName] = $i->nodeValue;
}
}
$headlines[] = $headline;
}
foreach ($headlines as $key => $value) {
$quote = $value['blockquote'];
}.
print_r($quote);
output ="this is your message.
Your Ticket ID = :68
Response ID = :45check that if its not contains any error."
I want to get the Ticket ID =:68 and Response id =:45.
when i print the blockquote i get the above text.now i want to get my ticket id and response id but don't know how ?
You could achieve this with regular expressions
$var ="this is your message.
Your Ticket ID = :68
Response ID = :45check that if its not contains any error.";
$match = array();
$ticketID = '';
$responseID = '';
preg_match('/Your Ticket ID = :([0-9]+)/', $var, $match);
if(count($match) > 0) {
$ticketID = $match[0];
}
preg_match('/Response ID = :([0-9]+)/', $var, $match);
if(count($match) > 0) {
$responseID = $match[0];
}
var_dump($ticketID, $responseID);
Outputs:
string 'Your Ticket ID = :68' (length=20)
string 'Response ID = :45' (length=17)
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 9 years ago.
Improve this question
I made a code that reads a table from another website and writes it on mine. Now I want to read just specific rows/columns and write it on my site. The table is filled with weather data and it refreshes every 5 minutes. I need only values for full and half hours and not all the values in the row, but just temperature. For example, there's a row for every five minutes containing temperature value, humidity, sun radiation etc. I need to find a value of, let's say 05:00, and read/write only temperature column of that row. In this case it would be: 05:00 12,5°C. And I need 48 values, because there's 24 hours per day and including another 24 half hours it's 48 all together, right..
This is a part of my code:
<?php
$trazi = ':00';
$citaj = file('proba.txt');
foreach($citaj as $linija)
{
if(strpos($linija, $trazi) !== false)
echo $linija;
}
$traziURL = "somepage";
$stranica = file_get_contents($traziURL);
$tablica = '/(<table.*<\/table>)/s';
preg_match_all($tablica, $stranica, $zeit);
echo $zeit[0][0];
$ime = "proba.txt";
$table = fopen($ime, 'w') or die ("Error!");
$podaci = $zeit[0][0];
fwrite($table, $podaci);
fclose($table);
?>
There's a chance that it won't work for you 'cause some parts are missing, but just to give you the idea.
I'm sure there are multiple other ways to do this, but I'd do it like this.
<?php
/**
* #author Bart Degryse
* #copyright 2013
*/
function getData() {
//Get the html page
$url = "http://www.essen-wetter.de/table.php";
$content = file_get_contents($url);
//Turn it into a dom document searchable by xpath
$dom = new DOMDocument();
$dom->loadHTML($content);
$xpath = new DOMXPath($dom);
//Get field names
$query = "//tr/td[position()=1 and normalize-space(text()) = 'Zeit']";
$entries = $xpath->query($query);
$entry = $entries->item(0);
$tr = $entry->parentNode;
foreach ($tr->getElementsByTagName("td") as $td) {
$fieldnames[] = $td->textContent;
}
//Get field data
$query = "//tr/td[position()=1 and (substring-after(normalize-space(text()),':') = '00' or substring-after(normalize-space(text()),':') = '30')]";
$entries = $xpath->query($query);
foreach ($entries as $entry) {
$fieldvalues = array();
$tr = $entry->parentNode;
foreach ($tr->getElementsByTagName("td") as $td) {
$fieldvalues[] = $td->textContent;
}
$data[] = array_combine($fieldnames, $fieldvalues);
}
//Return data set
return $data;
}
//Gather the data
$data = getData();
//Do something with it
echo "<pre>\n";
foreach ($data as $row) {
echo "Temperature at {$row['Zeit']} was {$row['Temperatur']}.\n";
}
echo "</pre><hr><pre>\n";
print_r($data);
echo "</pre>\n";
?>
If you're going to display the data on a UTF-8 compatible terminal or on a web page that's declared as being UTF-8 encoded this should do it.
If you're want to use single-byte ISO-8859-1 encoding however you'll have to change this line:
$fieldnames[] = $td->textContent;
into this:
$fieldvalues[] = utf8_decode($td->textContent);
Remark
Please note that while doing this is technically not that hard legally you're on loose ground. The data on that page is copyrighted and owned by Markus Wolter. Using his data for your own purposes without his consent is considered theft.