Getting remainding lines in a CSV - php

I have a script here which will get all the lines in a csv and insert them into a database (FileMaker to be exact), and I want it to count to 100 lines, break the loop, then tell me the remainding lines which are left. My code is below, Please see and any help would be greatly appreciated.
public function insertTimesheet() {
//Get the public variables
$fm = $this->fm;
$timesheet = $this->data['timesheets'];
$total = count($timesheet);
$fm = $this->fm;
$count = 0;
$total = count($timesheet);
//Loop through the data items in the array
foreach ($timesheet as $element) {
//Checks each key value in the array
for ($i = 0; $i < count($timesheet); ++$i) {
if($i == 100){
printf('%d Timesheets added', $i);
break;
// Return which timesheets have not been added //
}
//Prevents duplicate entries
$count++;
//Manually add some data to the array
$timesheet[$i]['Created_By_Staff_ID'] = $_SESSION["user"]->staff_id;
$timesheet[$i]['Key_Staff_ID'] = $_SESSION["user"]->staff_id;
$timesheet[$i]['Timesheet_Type'] = 'CSV_UPLOAD';
$timesheet[$i]['Resource_ID'] = 'N/A At this time [CSV UPLOAD]';
//Convert the dates to USA dates (FileMaker Format)
$timesheet[$i]['Date_From'] = $this->convertDate($timesheet[$i]['Date_From']);
$timesheet[$i]['Date_To'] = $this->convertDate($timesheet[$i]['Date_To']);
//Insert the data into the Database
$addReq = & $fm->createRecord('Web_Staff_Timesheet', $timesheet[$i]);
$result = $addReq->commit();
//Checks for filemaker errors
if (!FileMaker::isError($result)) {
$return['error'] = false;
$return['msg'] = 'Timesheet added successfully';
$strOut = sprintf('<br />Working on %d of %d timesheets', $count, $total);
//return true;
} else {
$return['error'] = true;
$return['errorCode'] = $result->code;
$return['msg'] = 'Unable to add Timesheet';
$strOut = sprintf('<br />Sorry, we could not add your time sheet, FileMaker Produced this error: %s <br /> Failed to insert the following timesheets [Line number]: ', $return['errorCode'], $count);
return false;
}
}
break;
}
//Clear the array to prevent duplicates
unset($timesheet, $element, $this->data);
return $strOut;
}

Just FYI guys, I've sorted it out now. Thanks for your time anyways!

Related

Looping through PHP array shows invalid Response

I have created a function in PHP that mainly index files from a txt file here is the function that was supposed to do the job
public function getPlayingItem()
{
$playData = [];
$startTimes = [];
for($i=0; $i < count($this->playListFiles); $i++){
$item = $this->playListFiles[$i];
if(empty($item)){
unset($this->playListFiles[$i]);
continue;
}
$tmp = explode(',', $item);
$playData[$i]['startTime'] = array_pop($tmp);
$startTimes[$i] = $playData[$i]['startTime'];
$playData[$i]['name'] = implode(',',$tmp);
}
array_multisort($startTimes, SORT_ASC, $playData);
for($i=0; $i < count($playData); $i++){
if (strtotime($playData[$i]['startTime']) >= time()){
break;
}
}
$info = $this->get_mp3($playData[$i-1]['name'], true, false);
$tmp = explode(DS,$playData[$i-1]['name']);
$name = array_pop($tmp);
$playing = ['number'=>($i-1),'path'=>$playData[$i-1]['name'],'name'=>$name,'duration'=>$info['data']['time'],'startTime'=>$playData[$i-1]['startTime']];
$info = $this->get_mp3($playData[$i]['name'], true, false);
$tmp = explode(DS,$playData[$i]['name']);
$name = array_pop($tmp);
$next = ['number'=>$i,'path'=>$playData[$i]['name'],'name'=>$name,'duration'=>$info['data']['time'],'startTime'=>$playData[$i]['startTime']];
$output = ['playing'=>$playing, 'next'=>$next];
return $output;
}
Here is the txt file
E:\xampp\htdocs\radioclass\files\2021-02-23 22.47.04.mp3,19:10:00
E:\xampp\htdocs\radioclass\files\2021-03-15 19.39.25.mp3,19:10:39
E:\xampp\htdocs\radioclass\files\2021-05-15 19.05.13.mp3,19:10:43
E:\xampp\htdocs\radioclass\files\2021-07-14 23.04.50.mp3,19:11:03
E:\xampp\htdocs\radioclass\files\2021-08-31 11.55.38.mp3,19:11:05
E:\xampp\htdocs\radioclass\files\2021-08-31 11.56.23.mp3,19:11:09
E:\xampp\htdocs\radioclass\files\2021-09-03 23.47.38#ssr.mp3,19:12:19
E:\xampp\htdocs\radioclass\files\frmu.mp3,19:12:23
E:\xampp\htdocs\radioclass\files\frmun.mp3,19:12:26
The response:
{"playing":{"number":8,"path":"E:\\xampp\\htdocs\\radioclass\\files\\frmun.mp3","name":"frmun.mp3","duration":"00:10","startTime":"19:12:26"},"next":{"number":9,"path":null,"name":"","duration":null,"startTime":null}}
**Now the problem is that first of all it should start from 0 and end at 10 and the second thing is that it shows the path, name, duration, of the second line as null any help will be greatly appreciated because I'm a begginer **

Php save more Array into MySQL

I'm trying to save arrays on a MySQL database with PHP.
The code inserts only the first line, if I have an array of 5 elements it just inserts the first element and the others and 4 don't save them for me.
Can anyone tell me where I'm wrong?
Thanks a lot.
<?php
//getting user values
$day = $_POST['Day'];
$nDay = $_POST['n_Day'];
$fieldOne = $_POST['Field_one'];
$fieldTwo = $_POST['Field_two'];
$timeOne = $_POST['Time_one'];
$timeTwo = $_POST['Time_two'];
$idR = $_POST['id_ristorante'];
$day_array = explode(",",$day);
$nDay_array = explode(",",$nDay);
$timeOne_array = explode(",",$timeOne);
$timeTwo_array = explode(",",$timeTwo);
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
$output=array();
//require database
require_once('db.php');
//checking if email exists
$conn=$dbh->prepare('SELECT id_ristorante FROM Orari WHERE id_ristorante=:idR');
$conn->bindParam(':idR', $idR, PDO::PARAM_STR);
$conn->execute();
//results
if($conn->rowCount() !==0){
$output['isSuccess'] = 0;
$output['message'] = "Orario giĆ  inserito";
} else {
for($i=0;$i<$len;$i++){
$day = $day_array[$i];
$nDay = $nDay_array[$i];
$timeOne = $timeOne_array[$i];
$timeTwo = $timeTwo_array[$i];
$conn=$dbh->prepare('INSERT INTO Orari (Day, n_Day, Field_one, Field_two, Time_one, Time_two, id_ristorante) VALUES (?,?,?,?,?,?,?)');
//encrypting the password
$conn->bindParam(1,$day);
$conn->bindParam(2,$nDay);
$conn->bindParam(3,$fieldOne);
$conn->bindParam(4,$fieldTwo);
$conn->bindParam(5,$timeOne);
$conn->bindParam(6,$timeTwo);
$conn->bindParam(7,$idR);
$conn->execute();
if($conn->rowCount() == 0) {
$output['isSuccess'] = 0;
$output['message'] = "Errore, riprova.";
} elseif($conn->rowCount() !==0){
$output['isSuccess'] = 1;
$output['message'] = "Orari salvati!";
}
}
}
echo json_encode($output);
?>
When you trying to do count on multiple array as:
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
The and cause the array to be boolean evaluated so the final assign to $len is 1 and that why the loop is done only once and only the first element is inserted to DB.
If all the array in the same length you should just do count on 1 of them as:
$len = count($day_array)
Better practice will be to do count on each on them and then assign $len with the minimum value
Change this line
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
To
$len = count($day_array) + count($nDay_array) + count($timeOne_array) + count($timeTwo_array);

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

PHP - array_push() expects parameter 1 to be array, null given in

I'm currently experiencing issues where array_push() is not working. I have ensured the arrays are directly accessible and declared correctly. Yet I'm still receiving these warnings and the values are not being pushed onto the array.
Here is my code:
include('../connstr.inc');
$email=$_REQUEST["email"];
$datafile=$_REQUEST["datafile"];
$email_safe=preg_replace("/[^a-zA-Z]/","_",$email);
$path="../uploaded_data";
$xml = simplexml_load_file("{$path}/{$email_safe}/{$datafile}.xml");
// Retreive data details for specified activity
$lapCount = $xml->Activities->Activity->Lap->count();
// Lap Variables
$totalTime = array(); $distance = array(); $maxSpeed = array();
$calories = array(); $intensity = array(); $trigMethod = array();
$avgSpeed = array();
// Convert filename to DateTime format
$datafile = convertID($datafile);
$datafile = date('Y-m-d H:i:s', strtotime($datafile));
// Variables for accurate distance calculations
$polarDistance = true;
$lapID;
$totalLapDistance;
$firstPoint = array();
$secondPoint = array();
// Collect details for each lap
for($x = 0; $x < $lapCount; $x++) {
$totalLapDistance = 0;
$lapNumber = $x+1;
$totalTime[$x] = $xml->Activities->Activity->Lap[$x]->TotalTimeSeconds;
$distance[$x] = $xml->Activities->Activity->Lap[$x]->DistanceMeters;
$maxSpeed[$x] = $xml->Activities->Activity->Lap[$x]->MaximumSpeed;
$calories[$x] = $xml->Activities->Activity->Lap[$x]->Calories;
$intensity[$x] = $xml->Activities->Activity->Lap[$x]->Intensity;
$trigMethod[$x] = $xml->Activities->Activity->Lap[$x]->TriggerMethod;
$avgSpeed[$x] = $xml->Activities->Activity->Lap[$x]->Extensions->LX->AvgSpeed;
// Store activity details into the 'detail' table
$sqlLap = "INSERT INTO lap (lapDate,lapNumber,TotalTime,distance,maxSpeed,avgSpeed,calories,intensity,trigMethod) VALUES (\"$datafile\",\"$lapNumber\",\"$totalTime[$x]\",\"$distance[$x]\",\"$maxSpeed[$x]\",\"$avgSpeed[$x]\",\"$calories[$x]\",\"$intensity[$x]\",\"$trigMethod[$x]\")";
$runLap = mysql_query($sqlLap) or die("unable to complete INSERT action:$sql:".mysql_error());
// Trackpoint variables
$altitude = array(); $tDistance = array(); $latitude = array();
$longitude = array(); $speed = array(); $pointTime = array();
// Retreive lapID
$lapID = getLapID();
// Find how many tracks exist for specified lap
$trackCount = $xml->Activities->Activity->Lap[$x]->Track->count();
$trackpointTotalCount = 1;
for($t = 0; $t < $trackCount; $t++) {
// Find out how many trackpoints exist for each track
$trackpointCount = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint->count();
// Collect details for each specificied track point
for($tp = 0; $tp < $trackpointCount; $tp++) {
$altitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->AltitudeMeters;
$tDistance[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->DistanceMeters;
$pointTime[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Time;
$latitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LatitudeDegrees;
$longitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LongitudeDegrees;
$speed[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Extensions->TPX->Speed;
// Check Track point
if(checkTP($altitude[$tp], $tDistance[$tp], $latitude[$tp], $longitude[$tp], $speed[$tp])) {
// Check if accurate distance should be calculated
if($polarDistance) {
$aa = $latitude[$tp];
$bb = $longitude[$tp];
$cc = $altitude[$tp];
if($tp == 0) {
array_push($firstPoint, $aa, $bb, $cc);
} else if($tp != 0) {
array_push($secondPoint, $aa, $bb, $cc);
}
printArray($firstPoint);
printArray($secondPoint);
// Add distance between trackpoints to total lap distance
$totalLapDistance += calcDistance($firstPoint, $secondPoint);
}
// Insert current trackpoint data into 'trackpoint' table
$sqlTC = "INSERT INTO trackpoint (tpDate,tpNumber,altitude,distance,latitude,longitude,speed,pointTime) VALUES (\"$datafile\",\"$trackpointTotalCount\",\"$altitude[$tp]\",\"$tDistance[$tp]\",\"$latitude[$tp]\",\"$longitude[$tp]\",\"$speed[$tp]\",\"$pointTime[$tp]\")";
$runTC = mysql_query($sqlTC) or die("unable to complete INSERT action:$sql:".mysql_error());
}
$trackpointTotalCount++;
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
}
}
if($polarDistance) {
if($tp != 0) {
// Update lap with more accurate distance
echo $totalLapDistance . '<br />';
$sqlUlap = "UPDATE lap SET accDistance='$totalLapDistance' WHERE lapID = '$lapID' ";
$runUlap = mysql_query($sqlUlap) or die("unable to complete UPDATE action:$sql:".mysql_error());
}
}
}
I didn't include all of the code below as there is quite a lot and I very much doubt it's relevant.
The warnings themselves only appear when trying to push a variable onto $secondPoint:
array_push($secondPoint, $aa, $bb, $cc);
However values are not being pushed onto either of the variables ($firstPoint, $secondPoint)
As a test I did echo $aa,bb and $cc and they did contain correct values.
Anybody have an idea of what I'm doing wrong?
EDIT: I have showed more of the code as I do use these arrays later, however this should not affect how the values are initially pushed? Below is some code which may affect it, namely the assign by reference?
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
That unset($secondPoint) will probably do it.
Try this instead:
if($polarDistance) {
if($tp != 0) {
$firstPoint = $secondPoint;
$secondPoint = array();
}
}

Show SINGLE RECORD with newest expiration date

I am using a FFDB database (flat File Database).
This script works as long as $vinc field has the same value, but I have 5 different types of $vinc values R1, R2, R3, R4, R5 - if I add new record where $vinc is not R1, a blank page appears instead.
<?php
function getbyfunction($selectfn, $orderby = NULL, $includeindex = false)
{
if (!$this->isopen)
{
user_error("Database not open.", E_USER_ERROR);
return false;
}
// If there are no records, return
if ($this->records == 0)
return array();
if (!$this->lock_read())
return false;
// Read the index
$index = $this->read_index();
// Read each record and add it to an array
$rcount = 0;
foreach($index as $offset)
{
// Read the record
list($record, $rsize) = $this->read_record($this->data_fp, $offset);
// Add it to the result if the $selectfn OK's it
if ($selectfn($record) == true)
{
// Add the index field if required
if ($includeindex)
$record[FFDB_IFIELD] = $rcount;
$result[] = $record;
}
++$rcount;
}
$this->unlock();
// Re-order as required
if ($orderby !== NULL)
return $this->order_by($result, $orderby);
else
return $result;
}
function returnRec($item){
if($item)
return true;
}
$db = new FFDB();
if (!$db->open("foo"))
{
$schema = array(
array("key", FFDB_INT, "key"),
array("status", FFDB_STRING),
array("vinc", FFDB_STRING),
array("month", FFDB_STRING),
array("day", FFDB_INT),
array("year", FFDB_INT)
);
// Try and create it...
if (!$db->create("foo", $schema))
{
echo "Error creating database\n";
return;
}
}
$result = $db->getbyfunction("returnRec", "vinc");
show_rec(end($result));
function show_rec($record){
$number = $record["key"];
$Rvinc = $record["vinc"];
$Rstatus = $record["status"];
$Rday = $record["day"];
$Rmonth = $record["month"];
$Ryear = $record["year"];
$tday = getdate();
$current_year = $tday['year'];
$current_month = $tday['month'];
if (($status == ON) && ($vinc == R1) && ($month >= $current_month) && ($year == current_year)){
echo "myrecord $vinc $status $day $month $year";
}
?>
Any help?!
Thanks
Yegge, using show_rec($result[0]); it shows 1 record but instead the most recent expiration date is showing the latest expiration date:
i.e.:
1 record expire 08/01/2011
2 record expire 11/01/2011
show_rec($result[0]); is showing the record with expiration date 11/01/2011 instead of 08/01/2011
Yegge
show_rec(end($result)); worked as long as $vinc == R1 only, if adding another record where vinc is not R1 then shows a blank page, any ideas?
<?php
function getbyfunction($selectfn, $orderby = NULL, $includeindex = false)
{
if (!$this->isopen)
{
user_error("Database not open.", E_USER_ERROR);
return false;
}
// If there are no records, return
if ($this->records == 0)
return array();
if (!$this->lock_read())
return false;
// Read the index
$index = $this->read_index();
// Read each record and add it to an array
$rcount = 0;
foreach($index as $offset)
{
// Read the record
list($record, $rsize) = $this->read_record($this->data_fp, $offset);
// Add it to the result if the $selectfn OK's it
if ($selectfn($record) == true)
{
// Add the index field if required
if ($includeindex)
$record[FFDB_IFIELD] = $rcount;
$result[] = $record;
}
++$rcount;
}
$this->unlock();
// Re-order as required
if ($orderby !== NULL)
return $this->order_by($result, $orderby);
else
return $result;
}
function returnRec($item){
if($item)
return true;
}
$db = new FFDB();
if (!$db->open("foo"))
{
$schema = array(
array("key", FFDB_INT, "key"),
array("status", FFDB_STRING),
array("vinc", FFDB_STRING),
array("month", FFDB_STRING),
array("day", FFDB_INT),
array("year", FFDB_INT)
);
// Try and create it...
if (!$db->create("foo", $schema))
{
echo "Error creating database\n";
return;
}
}
$result = $db->getbyfunction("returnRec", "vinc");
foreach($result as $item) {show_rec($item);break;}
function show_rec($record){
$number = $record["key"];
$Rvinc = $record["vinc"];
$Rstatus = $record["status"];
$Rday = $record["day"];
$Rmonth = $record["month"];
$Ryear = $record["year"];
$tday = getdate();
$current_year = $tday['year'];
$current_month = $tday['month'];
if (($status == ON) && ($vinc == R1) && ($month >= $current_month) && ($year == current_year)){
echo "myrecord $vinc $status $day $month $year";
}
?>
i think you need to use break in loop, like above.
select product, expirationdate from your_table
where expirationdate > {current_date} order by expirationdate ASC limit 1
{current_date} is variable that should be passed from php or you can use mysql function instead
If I understood your code correctly, instead of
foreach($result as $item) {show_rec($item);break;}
//use
show_rec($result[0]); //only show the very first item in the result array
Edit: Then use this:
show_rec(end($result));
SOLUTION:
I just want to make sure to post the solution:
$result = $db->getall(lp_month,lp_year);
$i = 0;
foreach ($result as $row){
print_r (show_record($row));
if ($i >= 1)
break;
$i++;
}
Not a lot different from what I initially had, but print_r instead of echo did the trick:
print_r (show_record($row));
Thanks

Categories