I would like to get the id of a specific value in my phpmyadmin table.
So, I have got a table with 'id_cal' as an A.I. id, 'mois' representing the month with numbers (e.g 1 for january) and 'annee' representing the year. (see calendar table)
I am trying to set php variable for the month and the year and if they match the current month and year, I want to get this specific id.
I commented the php code where I am having my trouble, here it is :
<?php
include_once('config.php');
$m = idate('n');
$y = idate('Y');
echo $m; echo "\t"; echo $y; echo "<br>"; echo "<br>"; // The result of this is 7 2019
$reponse = $bdd->query('SELECT * FROM calendrier');
while($donnees= $reponse->fetch()){
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
echo $id_cal;
echo "\t";
echo $mois;
echo "\t";
echo $year;
echo "<br>";
}
// What I am trying to do :
if (($m = $mois) && ($y = $year)){ // If the month and the year are the current month/year
$i = $id_cal; // I want to put the id refering to the current month/year (in my phpmyadmin table) into a new variable
echo "<br>"; // and echo this variable (or use it in other ways)
echo $i; // BUT what I am echoing is 24 representing the number of values in my array
} // How can I only get 7 ? (in this exemple, since we are the 7/2019)
Here is what I am getting in my localhost : echo
I really don't understand why am I not having 7.
Also, I tried this instead of my while:
$donnees= $reponse->fetch();
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
// But in this cas I am having $i = 1, so it's the same problem.
Many thanks in advance for your response I am quite struggling with this.
It is because id_cal gets overwritten with the new value of id_cal in each iteration of your while statement.
To get the result you want, you could put the if inside the while statement...
while($donnees= $reponse->fetch()){
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
echo $id_cal;
echo "\t";
echo $mois;
echo "\t";
echo $year;
echo "<br>";
if (($m == $mois) && ($y == $year)){
$my_var_to_use_elsewhere = $id_cal;
}
}
echo "<br>";
echo $my_var_to_use_elsewhere;
Related
I have found many threads to echo a CSV file as XML, but cannot work out how to filter rows and columns.
The code below does exactly what I want but the output is an HTML table.
I need help to create similar code for xml output.
Scenario
sitemap.csv
1,https://example.com/page1,monthly,1
7,https://example.com/page2,monthly,0.5
14,https://example.com/page3,monthly,0.5
21,https://example.com/page4,monthly,0.5
This is a static website where all pages are already created but should only appear in sitemap at rate of 1 per week ie 10 days after 09 Feb 2020 $launchdate only first two rows should be visible in sitemap.
1st column should not be echoed - it is used to determine if that row should be echoed at load time.
I have looked at many scripts to convert csv to XML but all of them display all columns. I have tried for hours to come up with a solution to create results in XML format.
I know final solution will need to include something like:
header("Content-Type: application/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' .PHP_EOL;
I know final solution will need to exclude the echo of date data at top - currently used for testing
I know final solution will need to replace the column descriptors
eg Loc will become <loc> URL </loc> then <lastmod> <changefreq> <priority>
======
Working code to echo HTML table
<?php
//Sources for this solution
// https://thisinterestsme.com/reading-csv-file-with-php/
// and & https://stackoverflow.com/questions/40285479/filtering-and-displaying-a-csv-file-with-php
// Final solution should be xml not HTML table
$date = date("Y-m-d"); // Todays Date
$date_number = strtotime($date); // Todays date as Integer
$launchdate_number = strtotime('2020-02-09'); //Launch Date as Integer 1581206400
$days_since_launch = ($date_number - $launchdate_number) / 86400; // Days since Launch date
// Echo data for testing, will not be in the final XML file
echo "date ";
echo $date;
echo " ";
echo "date_number ";
echo $date_number;
echo " ";
echo "launchdate ";
echo $launchdate_number;
echo " ";
echo "days_since_launch ";
echo " ";
echo $days_since_launch;
echo "<br>";
$fileHandle = fopen("sitemap.csv", "r");
//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
if ($row[0] > $days_since_launch) continue; // display only pages were value in 1st column[0]less that $days_since_launch
//Print out my column data - exclude 1st column[0]
echo 'Loc: ' . $row[1] . '<br>';
echo 'Lastmod: ' . $date . '<br>';
echo 'changefreq: ' . $row[2] . '<br>';
echo 'priority: ' . $row[3] . '<br>';
echo '<br>';
}
fclose($file_handle);
?>
After many hours I managed to find a solution which reads a CSV file and echos a valid xml sitemap. Thanks to sources in comments of code.
<?php
//Sources for this solution
// https://thisinterestsme.com/reading-csv-file-with-php/
// https://stackoverflow.com/questions/40285479/filtering-and-displaying-a-csv-file-with-php
// https://www.webslesson.info/2017/06/make-dynamic-xml-sitemap-in-php-script.html
header("Content-Type: application/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="UTF-8"?>';
$date = date("Y-m-d"); // Todays Date
$date_number = strtotime($date); // Todays date as Integer
$launchdate_number = strtotime('2020-02-09'); //Launch Date as Integer 1581206400
$days_since_launch = ($date_number - $launchdate_number) / 86400; // Days since Launch date
// Echo data for testing, will not be in the final XML file
$fileHandle = fopen("sitemap.csv", "r");
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
if ($row[0] > $days_since_launch) continue; // display only pages were value in 1st column[0]less that $days_since_launch
//Print out my column data - exclude 1st column[0]
echo '<url>' . PHP_EOL;
echo '<loc>'. $row[1] .'</loc>' . PHP_EOL;
echo '<lastmod>'.$date.'</lastmod>' . PHP_EOL;
echo '<changefreq>'. $row[3] .'</changefreq>' . PHP_EOL;
echo '<priority>'. $row[4] .'</priority>' . PHP_EOL;
echo '</url>' . PHP_EOL;
}
echo '</urlset>';
?>
My array from a database looks like this:
$client[0]['Name'] = 'Foo';
$client[0]['Claim'][0]['year'] = 2013;
$client[0]['Claim'][1]['year'] = 2014;
$client[0]['Claim'][2]['year'] = 2015;
$client[1]['Name'] = 'Bar';
// no 2013!
$client[1]['Claim'][0]['year'] = 2014;
$client[1]['Claim'][1]['year'] = 2015;
// table headers are name, 2013, 2014, 2015...
foreach($client as $c) {
echo '<tr>';
echo '<td>' . $c['Client']['name'] . '</td>';
foreach($c['Claim'] as $claim) :
echo '<td>' . $claim['year'] . '</td>';
endforeach;
echo '</tr>';
}
Which works fine except when a $client is missing a year then the <td> are not balanced; causing my table to be incorrect.
My goal is to have each $claim['Year'] line up with the appropriate table heading.
I figured I could just add empty keys to each array and re-order them but that seems a bit unnecessary and wondered if there was a better way of doing it.
So an array might look
this would be ideal:
$years[null, 2014, 2015]
whereas currently it is
$years[2014,2015]
Hope this makes sense.
I am assuming you have a start and an end year that you want to display the claims for. Then if you replace the inner for loop with this I think it should work:
$x = 0; //Variable to keep track of what claim we are on.
//Loop through the years.
for($i=$start; $i<=$stop; $i++) {
//If there is a claim for this year, echo it and move on to the next claim.
if($c['Claim'][$x]['year'] == $i) {
echo '<td>' . $c['Claim'][$x]['year'] . '</td>';
$x++;
}
//If not, just echo an empty table cell.
else {
echo '<td></td>';
}
}
This only works if the claims are sorted by year. Please note that I have not tested the code.
I implemented code in PHP for linear regression, the idea was to take delivery date for each customer (however many delivery dates per customer there were in the DB) and then to use these delivery dates (converted to days) as a linear regression equation as the y parameter, to eventually prediction a future delivery date/order date, and based on this prediction and comparison to the current date, the system would take some action like send push notification reminders. My code for the implementation is as follows:
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die (mysql_error());
mysql_select_db($db, $conn) or die(mysql_error());
//Outer Loop to save all eligable customer ID's
$idarray=array();
$firstloop=mysql_query("Select id FROM ordering GROUP BY id",$conn);
$number_of_rows_initial=mysql_num_rows($firstloop);
while (($row = mysql_fetch_array($firstloop, MYSQL_ASSOC)) !== false){
$idarray[] = $row; // add the row in to the results (data) array
// print_r($idarray);
}
for($counter=0; $counter<$number_of_rows_initial; $counter++)
{
$id=$idarray[$counter]['id'];
//First confirm if user is already registered via website
$result = mysql_query("SELECT TO_DAYS(date) FROM ordering WHERE id=$id",$conn);
$num_rows = mysql_num_rows($result);
// mysql_query($result,$conn) or die(mysql_error();
//echo $num_rows;
$data = array();
$days=array();
$xAxis=array();
$ldate=array();
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$data[] = $row; // add the row in to the results (data) array
}
// print_r($data); // print result
//This part is working now!!!!
for ($x = $num_rows-1 ; $x > 0; $x--) {
$days[$x] = $data[$x]['TO_DAYS(date)'] -$data[$x-1]['TO_DAYS(date)'];
$xAxis[$x]=$x;
}
$days[0]=30;
print_r("<br />",$days);
//print_r($xAxis);
//my implementation of regression calculation
// calculate sums
$x_sum = (array_sum($xAxis));
$y_sum = array_sum($days);
echo "<br />","Customer ID is: ",$id,"<br />";
echo "Sum of X Axis: ",$x_sum, "<br />";
echo "Sum of Y Axis: ",$y_sum,"<br />" ;
$xx_sum = 0;
$xy_sum = 0;
for($i = 0; $i < $num_rows; $i++) {
$xy_sum+=($xAxis[$i]*$days[$i]);
$xx_sum+=($xAxis[$i]*$xAxis[$i]);
}
// calculate slope
$m = (($num_rows * $xy_sum) - ($x_sum * $y_sum)) / (($num_rows * $xx_sum) - ($x_sum * $x_sum));
// calculate intercept
$b = ($y_sum - ($m * $x_sum)) / $num_rows;
$predict=($m*($num_rows+1))+$b;
echo "The Slope of the Representative line is: ",$m,"<br />";
echo "The Y intercept is ",$b,"<br />";
echo "Predicted next date of delivery in days (from last delivery date) is: ", $predict,"<br />";
//Final Date Calculation
$lastdate=mysql_query("SELECT TO_DAYS(date) FROM ordering WHERE id=$id",$conn);
$num_rows_date = mysql_num_rows($lastdate);
while (($row_date = mysql_fetch_array($lastdate, MYSQL_ASSOC)) !== false){
$ldate[] = $row_date; // add the row in to the results (data) array
}
echo "Total number of records for the given id are: ",$num_rows_date, "<br />";
$ldatefinal=$ldate[$num_rows_date-1]['TO_DAYS(date)'];
echo "Last date in the records for the given ID is ",$ldatefinal,"<br />";
echo "Last date + Prediction days = ",$ldatefinal+$predict,"<br />";
$currentdate=mysql_query("SELECT TO_DAYS(CURDATE())",$conn);
$dcrow = mysql_fetch_assoc($currentdate);
//$dhold=$dcrow['TO_DAYS(CURDATE())'];
//echo "Current Date is: ",$dcrow['TO_DAYS(CURDATE())'],"<br /" ;
//UPON EXECUTION NOTHING BELOW GETS ExEcuted ??
//echo "Last date + Predicted days = ";
if (( (($ldatefinal+$predict) - $dcrow['TO_DAYS(CURDATE())']) <3 )&& $predict>0){
echo "Time to Order<br />","</br />";
}else if((( (($ldatefinal+$predict) - $dcrow['TO_DAYS(CURDATE())']) >3 && $predict>0) )){
echo "You Got Gas!!<br />","</br />";
}else{
echo "Linear Regression not Suitable for this Record ID","<br />";
}
}
mysql_close($conn);
Every thing seems to work perfect except for the times when the prediction comes up with negative numbers, I have for now chosen to ignore these by using the " echo "Linear Regression not Suitable for this Record ID","";" but I am sure there must be a better way to accommodate this type of scenarios, I am just not sure how to in my case, especially using the date format. Any help would be greatly appreciated. I must say this forum and of course its users have been extremely kind and generous with their time and knowledge in the past for me, and hope you guys can point me in the right direction this time as well. Hamood
I'm currently having trouble printing some simple test statements within my for loop.
<?php
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();
echo "LapCount: " . $lapcount;
$totalTime = array(); $distance = array(); $maxSpeed = array();
$calories = array(); $intensity = array(); $trigMethod = array();
echo 'Test1';
// Collect details for each lap
for($x = 0; $x < $lapCount; $x++) {
echo 'Test2';
// Find how many trackpoints exist for specified lap
$trackPointCount = $xml->Activities->Activity->Lap[$x]->Track->Trackpoint->count();
echo 'Test3';
echo "<br /> Lap {$x} TrackP Count: " . $trackPointCount;
echo 'Test4';
}
When I run it, only 'Test1' and the 'lapCount' gets printed. Anything within the for loop doesn't run. No errors are being returned either. $x will definitely be less then $lapCount as this is just 3. I fail to see the (most likely) stupid mistake I've made even after looking over it many times.
The problem with your code is this:
You declare lapcount as $lapcount, but try using it as $lapCount
(Notice the capitalization of the "C")
Ensure all uses of this variable are typed out exactly the same and everything will work
EDIT:
Seems like you discovered this as I posted my answer
Initially you are using variable name $lapcount but in the last for loop you are using $lapCount that is the reason why you are not getting any value. Use $lapcount in the last for loop also.
for($x = 0; $x < $lapcount; $x++) { // use $lapcount
echo 'Test2';
$trackPointCount = $xml->Activities->Activity->Lap[$x]->Track->Trackpoint->count();
echo 'Test3';
echo "<br /> Lap {$x} TrackP Count: " . $trackPointCount;
echo 'Test4';
}
Here, the name of your var is $lapcount without 'C' lowercase:
// Retreive data details for specified activity
$lapcount = $xml->Activities->Activity->Lap->count();
echo "LapCount: " . $lapcount;
but here, you use 'C' uppercase, $lapCount:
for($x = 0; $x < $lapCount; $x++) {
I have a HTML select form to select the day/month/year, and this is generated with PHP. My for loop, for example with the month, looks like this:
$html="<select name=\"".$name."month\">";
for($i=1;$i<=12;$i++)
{$html.="<option value='$i'>$months[$i]</option>";}
$html.="</select> ";
I can't seem to figure out how to set a "default" value to the current month while retaining all of the prior months in the dropdown (I can just set $i=date("n"), but then I lose the ability to select any prior month).
Does anybody know a simple way of setting the default value to be the current day? Thank you very much!
Try this:
<?php
$currentMonth = date("m");
$html = "<select name=\"" . $name . "month\">";
for ($i = 1; $i <= 12; $i++) {
if ($i == $currentMonth) {
$html .= "<option selected='selected' value='$i'>$months[$i]</option>";
} else {
$html .= "<option value='$i'>$months[$i]</option>";
}
}
$html .= "</select> ";
echo $html;
?>