Date is Echoing without 'echo' command - php - php

I have a form that is updated yearly, so a user inputs a date and other information then submits the form which gets stored in a database. When they come back a year later they do the same to overwrite the old records, the problem is is that when they come back the old date is being Echoed, which shouldn't happen. All of the other fields are blank which should happen. I'm not calling for the date to be echoed in the code but it still is.
Code for defining the date pulldown
// parameters: $fname - main name of field
// $date - actual date value from database
// $beginYear - first value in year list
// $endYear - last value in year list
// return: none
function make_date_pulldown($fname, $date, $beginYear, $endYear)
{
// read the date and break it up into $Year, $Month and $Day
// so that we can set the "SELECTED" in the option list
if ($date == ""){
// set some default values to be safe
$Year = 0;
$Month = 0;
$Day = 0;
} else {
$Year = (int) substr($date,0,4);
$Month = (int) substr($date,5,2);
$Day = (int) substr($date,8,2);
}
// need to build a table around these guys so that there won't
// be any word wrap... it's going to be a 1 row by 5 cols.
echo "<table border=0 cellspacing=0 cellpadding=0>\n";
echo "<tr>\n";
// build month list
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo " <center>Month<br>\n";
echo "<select name='month_$fname'>\n";
echo " <option value='00'></option>\n";
for ($i=1;$i<=12;$i++){
printf (" <option value='%02d'",$i);
if ($i == $Month) {
printf (" SELECTED");
}
printf (">%02d</option>\n",$i);
}
echo "</select>\n";
echo " </center>\n";
echo " </td>\n";
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo "/";
echo " </td>\n";
// build day list
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo " <center>Day<br>\n";
echo "<select name='day_$fname'>\n";
echo " <option value='00'></option>\n";
for ($i=1;$i<=31;$i++){
printf (" <option value='%02d'",$i);
if ($i == $Day) {
printf (" SELECTED");
}
printf (">%02d</option>\n",$i);
}
echo "</select>\n";
echo " </center>\n";
echo " </td>\n";
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo "/";
echo " </td>\n";
// build year list
echo " <td><font class=bluetext face=verdana,arial size=-2>\n";
echo " <center>Year<br>\n";
echo "<select name='year_$fname'>\n";
echo " <option value='0000'></option>\n";
for ($i=$beginYear;$i<=$endYear;$i++){
printf (" <option value='%d'",$i);
if ($i == $Year) {
printf (" SELECTED");
}
printf (">%d</option>\n",$i);
}
echo "</select>\n";
echo " </center>\n";
echo " </td>\n";
echo "</tr>\n";
echo "</table>\n";
}
Code for the PHP form on the website
<u>Date Of Submittal</u><br>
<?php
$startYear = date("Y")-1;
$endYear = date("Y")+1;
make_date_pulldown("submitdate", $submitdate, $startYear, $endYear);
?>

Looks like you want to create a drop down menu based on year ....
$date = new DateTime();
//Years
echo makeSelect($date->format("Y")-1, $date->format("Y")+1,$date->format("Y"));
//Month
echo makeSelect(1, 12,$date->format("m"));
//Day
echo makeSelect(1, $date->format("t"),$date->format("d"));
Function Used
function makeSelect($start, $end, $default = null) {
$content = "<select>";
$range = range($start, $end);
$selected = "";
foreach ( $range as $value ) {
$selected = ($default == $value) ? "selected" : null;
$content .= sprintf('<option value="%s" %s>%1$s</option>', $value, $selected);
}
$content .= "</select>";
return $content;
}

Figured it out, in my get_() function to call the database table I was reading the row for the submitdate and it was pulling and displaying the date based on that command and the function for make_date_pulldown.
Here is what that function looked like (obviously trimmed down):
<?
function get_submit($id, &$submitdate)
{
$query = "select * from submit where id = $id";
$result = mysql_query($query);
if ($result) {
$total_rows = mysql_numrows($result);
} else { $total_rows = 0; }
if ($total_rows > 0) {
$submitdate = trim(mysql_result($result, "", "submitdate"));
} else {
$submitdate = "";
$found = 1;
}
}
?>

Related

Select value inside a dropdown using ternary operator inside a foreach php loop

How do you select a dropdown value inside a foreach loop. The code below generate time with 30 minutes gap. I cannot able to select the value from mysql database.
$sql = "SELECT * FROM batches WHERE batch_id = '$id'";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
// Name
echo "<label>Batch name</label> ";
echo "<input type=text name=name value='".$row['name']."' required> <br />";
// Start time
echo "<label>Start time</label> ";
echo "<select name=starttime value=''> Start time </option>";
$range = range( strtotime("05:00"), strtotime("21:00"), 30 * 60);
foreach($range as $time){
$foo = date("H:i", $time) . "</br>";
$selected = ($foo == $row['start_time']) ? 'selected="selected"' : '';
echo "<option value='$foo'" . $selected . ">" . $foo . "</option>";
} // foreach
echo "</select>";
} // while
Please help!!
You are concatenating a break line (<br>) to your $foo variable, which is why the comparison fails. You don't need this break line inside a option tag either, so just get rid of it:
foreach($range as $time){
$foo = date("H:i", $time);
$selected = ($foo == $row['start_time']) ? 'selected="selected"' : '';
echo "<option value='$foo'" . $selected . ">" . $foo . "</option>";
} // foreach
Also, by your comments, the start_time coming from the database contains seconds as well, so you need to format your timestamps accordingly:
$foo = date("H:i:s", $time);

how to group the data having similar values in php?

I have a table in the database named 'transactions'. I want to list out the values from this table. The result should be displayed in HTML table format. The rows in the resulted table should be grouped as per the amount.There is a column named 'amount' in the 'transactions' table.
Here is my code:
$s1 = DB::table('transactions')
->select(DB::raw("GROUP_CONCAT(selected_seats SEPARATOR '') as selected_seats"),'userid','amount','show_id')
->where("show_id","=",$s)
->groupBy('userid')
->groupBy('amount')
->orderBy('userid','ASC')
->orderBy('amount', 'DESC')
->get();
I am retrieving the values from $s1 variable through loop.
Following is the output:
and i want the result like this:
Please click on the links given above. I am new to this forum so its not allowing me to add images in the question. Kindly help.
Here is the entire code:
if($s1 != null)
{
echo "<div class='panel-body'>";
echo "<table class='table table-responsive'>"; $c = 1;
echo "<th>Drama Title</th>";
echo "<th>Show Date</th>";
echo "<th>Seat booked</th>";
echo "<th>Amount</th>";
echo "<th>User</th>";
for($i=0;$i<count($s1);$i++)
{
echo "<tr><td>".$shows1[0]->show_title."</td>";
echo "<td>".$shows[0]->show_date."</td>";
echo "<td>";
echo $s1[$i]->selected_seats;
echo "</td>";
/*echo $s1[$i]->userid."<br/>";
echo $s1[$i]->amount."<br/>";*/
$transactions = DB::table('transactions')->where('userid',$s1[$i]->userid)->where('show_id',$s1[$i]->show_id)->get();
//var_dump($transactions);
$total_amount = 0;
//echo "<pre>Users<br/>"; var_dump($transactions);
foreach ($transactions as $transaction)
{
//echo "userid ".$s1[$i]->userid." "."show id: ".$transaction->show_id." "."<br/>";
// echo "amount: ".$transaction->amount." ";
$amount = $transaction->amount;
$total_amount = $total_amount + $amount; //echo $amount."<br/>";
$c = $c+1;
//echo "no. of seats:".$c;
$users = DB::table('users')->where('id',$s1[$i]->userid)->get();
}
echo "<td>".$total_amount."</td>";
//echo $s1[$i]->userid."<br/>";
//echo "<td>".$users[0]->name."</td>";
//echo "<pre>"; var_dump($users);
echo "</td>";
if(isset($users[0]))
{
//echo "values are set";
echo "<td>".$users[0]->name."</td></tr>";
}
else
{
//echo "null value";
continue;
}
}
/*echo $shows[0]->show_date."<br/>";
echo $shows[0]->show_title;*/
//echo "<pre>"; var_dump($s1);
//echo "<td>".$users[0]->name."</td>";
//echo "</tr>";
echo "</table>";
echo "</div>";
?>
}
else
{
echo "No records found";
}
Easiest way I think is calculate amounts in the loop you are printing data or readying data to send to a view. Since your data sorted by user_id, you always can change amount variable in the loop when user_id is changing. You can use count(explode($seat_variable)) to get number of seats in a single run of the loop. Look at the example code below.
$num_seat = 0; $amount = 0; $running_user_id = -1;
foreach ($row as $entry) {
...
if ($running_user_id != $entry['user_id']) { // check if the same user
$running_user_id = $entry['user_id'];
$num_seat = 0; $amount = 0; // resetting variable values for seperate user.
}
$num_seat += count(explode($entry['selected_seats']));
$amount += $entry['amount'];
...
}
And I assume you have missing data like emails in the query.
Code update after questioner added his code.
if($s1 != null) {
echo "<div class='panel-body'>";
echo "<table class='table table-responsive'>"; $c = 1;
echo "<tr>";
echo "<th>Drama Title</th>";
echo "<th>Show Date</th>";
echo "<th>Seat booked</th>";
echo "<th>Amount</th>";
// echo "<th>User</th>";
echo "</tr>";
$category = ""; $num_seats = 0;
for ($i=0; $i<count($s1); $i++) {
if ($category != $amount) {
if ($i > 0) { // print totals
echo "<tr>
<td colspan='3' align='right'>Total</td>
<td>".$num_seats."</td>
<td>".($num_seats * $amount)."</td>
</tr>";
echo "<tr><td colspan='5'> </td></tr>"; // empty row after totals printed
$num_seats = 0; //resetting number of seats per category
}
echo "<tr><td colspan='5'><h2>Category : ".$amount."</h2></td></tr>"; // printing category line in the given table
$category = $amount; // this logic is to prevent category line printing for each row
}
$transactions = DB::table('transactions')->where('userid',$s1[$i]->userid)->where('show_id',$s1[$i]->show_id)->get();
echo "<tr>";
$users = DB::table('users')->where('id', $s1[$i]->userid)->get();
// Check below values are correct or not
echo "<td>".$users[0]->name."</td>";
echo "<td>".$s1[$i]->userid."</td>";
echo "<td>".$s1[$i]->email."</td>"; // get user's email property here
echo "<td>".$s1[$i]->selected_seats."</td>";
$num_seats += count(explode(',', $s1[$i]->selected_seats));
echo "<td> </td></tr>"; // empty colomn for amount and the row end
}
echo "</table>";
echo "</div>";
}

how to make static index of array in php

I am trying to store values from form radio to array. But problem which i am facing is that every time array 1st index is replaced with new value. I believe this is scope problem. I also tried to declare global array but no success.
Here is the code:
<?php
include_once("connection.php");
$c = new DBcon();
$c->startcon();
global $array; // not effecive
// $q = $_POST['t'];
// echo 'fff', $q;
$page = $_GET['page'];
echo 'pagesss', $page, 'ppp';
if ($page == "") {
$page = "1";
} else {
// If page is set, let's get it
$page = $_GET['page'];
}
// Now lets get all messages from your database
$sql = "SELECT * FROM quizes";
$query = mysql_query($sql);
// Lets count all messages
$num = mysql_num_rows($query);
// Lets set how many messages we want to display
$per_page = "2";
// Now we must calculate the last page
$last_page = $num;
echo 's', $num;
// And set the first page
$first_page = "1";
// Here we are making the "First page" link
echo "<a href='?page=" . $first_page . "'>First page</a> ";
// If page is 1 then remove link from "Previous" word
if ($page == $first_page) {
echo "Previous ";
} else {
if (!isset($page)) {
echo "Previous ";
} else {
// But if page is set and it's not 1.. Lets add link to previous word to take us back by one page
$previous = $page - 1;
echo "<a href='?page=" . $previous . "'>Previous</a> ";
}
}
// If the page is last page.. lets remove "Next" link
if ($page == $last_page) {
echo "Next ";
} else {
// If page is not set or it is set and it's not the last page.. lets add link to this word so we can go to the next page
if (!isset($page)) {
$next = $first_page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
} else {
$next = $page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
}
}
// And now lets add the "Last page" link
echo "<a href='?page=" . $last_page . "'>Last page</a>";
// Math.. It gets us the start number of message that will be displayed
$start = ($page * ($page - 1)) / $page;
echo 'start', $start;
echo 'page', $page;
// Now lets set the limit for our query
$limit = "LIMIT $start, $per_page";
// It's time for getting our messages
$sql = "SELECT * FROM quizes $limit";
$query = mysql_query($sql);
echo "<br /><br />";
// And lets display our messages
$i = 0;
$l = 0;
while ($row = mysql_fetch_array($query) or die(mysql_error())) {
$a = $row['A'];
echo '<form method="get" action="?page=".$next."">';
while ($row = mysql_fetch_array($query)) {
echo '<div class="boxed" >';
echo "\t" . '<tr><th>' .
$row['question'] . "<br>" .
'</th><th>' . "<input type='radio' name= 't[]' value='{$row['A']}'>" . $row['A'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['B']}'>" . $row['B'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['C']}'>" . $row['C'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['D']}'>" . $row['D'] . '</th>
</tr>';
echo '<input type="hidden" name="page" value="' . $next . '">';
echo '<input type="submit" name="submit"/>';
$i++;
echo '</div>';
echo '</div>';
}
echo '</form>';
if (isset($_GET['submit'])) {
$example = $_GET['t'];
foreach ($example as $value) {
$array[$i++] = ($value);
echo "$array[0] <br>"; // printing correct statement but replacing old values with new value everytime.
echo "$array[1] <br>"; // 0 values
echo "$array[2] <br>"; // 0 values
}
}
}
?>
I have seen these posts: PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] , PHP - define static array of objects but no help. Kindly help what should i do?
You cannot do
$array[$i++]
this will always be $array[1]
instead do
$i++;
$array[$i]= $value;
P.S. $array is a terrible name for a variable...
if (isset($_GET['submit'])) {
$example = $_GET['t'];
$i=0;
$arrayA = array();
foreach ($example as $value) {
$arrayA[$i] = ($value);
$i++;
}
print_r($arrayA);
}
if you do
$array[$i++] ;
it wont work , just try this and it wont replace your old value
$array[$i] = $value;
$i++;
You must increment your variable first, then use the variable as the array key.
Edit: this is what you're looking for:
$i = 0;
foreach ($example as $value) {
$array[$i] = $value;
$i++;
}

Netbeans says PHP function has too many lines

I have a function and netbeans is saying I can only have 20 lines in my code.
Why is this and how could I fix this. I have another function with the same problem. Dreamweaver doesn't say anything so I don't know if this is a big problem.
my code:
function dispalyEvent($weekNr, $week, $year){
echo "<p>";
$gendate = new DateTime();
$gendate->setISODate($year,$week,$weekNr);
$month = $gendate->format('m');
$day = $gendate->format('d');
$event_query = mysql_query("SELECT * FROM calendar ORDER BY starttime");
while($event = mysql_fetch_array($event_query)) {
$startYear = $event['startyear'];
$startMonth = $event['startmonth'];
$startDay = $event['startdate'];
$endYear = $event['endyear'];
$endMonth = $event['endmonth'];
$endDay = $event['enddate'];
$period = new DatePeriod(
new DateTime($startYear.$startMonth.$startDay),
new DateInterval('P1D'),
new DateTime($endYear.$endMonth.$endDay +1)
);
$currentDate = $year."-".$month."-".$day;
foreach ($period as $savedDate) {
if ($currentDate == $savedDate->format('Y-m-d')){
if ($event['Approved'] == "Approved"){
echo "</p>";
echo "<p>";
if ($event['ad']) {
echo "<img src='images/".$event['ad']."' alt='event-ad' width='300' height='100' />";
} else { echo " "; }
echo "</p>";
echo "<p> </p>";
echo "<div class='toggleLink' style='cursor: pointer; color: #333;'>";
echo $event['starttime']." ".$event['title'];
echo "</p>";
echo "</div>";
echo " <div class='toggle'>";
echo "<p class='toggleLink'>";
echo "(".$event['starttime']."-".$event['endtime'].") ".$event['location']." - ".$event['address']." - Admission Price: $".$event['price']."<br>".$event['description'];
echo "</div>";
}}}}
echo "</p>";
}
?>

retrieve data based on date range using mysql ,php

I am working on WPF where I have two datepickers when I try to retrieve the information on date range it displays only one record on all dates(same record displaying multiple times eg : date chosen from 01/10/2013 - 3/10/2013) where I have 3 different records on each day but my output is the first record displayed 3 times with same date and time.
function cpWhitelistStats() {
$startDate = $_POST['startDate'];
$startDateTime = "$startDate 00:00:00";
$endDate = $_POST['endDate'];
$endDateTime = "$endDate 23:59:59";
$cpId = $_POST['id'];
$cpName = etCommonCpNameById($cpId);
print "<h2 style=\"text-align: center;\">Permitted Vehicle Summary</h2>";
print "<h2 style=\"text-align: center;\">for $cpName</h2>";
$tmpDate = explode("/", $startDate);
$startYear = $tmpDate[2];
$startMonth= $tmpDate[1];
$startDay = $tmpDate[0];
$tmpDate = explode("/", $endDate);
$endYear = $tmpDate[2];
$endMonth= $tmpDate[1];
$endDay = $tmpDate[0];
$startDateTime = "$startYear-$startMonth-$startDay 00:00:00";
$endDateTime = "$endYear-$endMonth-$endDay 23:59:59";
$custId = $_SESSION['customerID'];
$realCustomerId = $_SESSION['realCustomerId'];
$maxVal = 0;
if ($custId != "") {
$conn = &newEtConn($custId);
// Get the whitelist plates
$staticWhitelistArray = etCommonMkWhitelist($conn, $cpId);
array_shift($staticWhitelistArray);
$startLoopDate = strtotime($startDateTime);
$endLoopDate = strtotime($endDateTime);
$oneDay = 60 * 60 * 24;
// Get the entries
$plateList = array_keys($staticWhitelistArray);
$plate_lookup = implode('","', $plateList);
$sql = "SELECT plate, entry_datetime, exit_datetime FROM stats WHERE plate IN (\"$plate_lookup\") AND entry_datetime > \"$startDateTime\" AND entry_datetime < \"$endDateTime\" AND carpark_id=\"$cpId\" ";
$result = $conn->Execute($sql);
if (!$result) {
print $conn->ErrorMsg();
exit;
}
$rows = $result->fields;
if ($rows != "") {
unset($myArray);
foreach($result as $values) {
$plate = $values['plate'];
$new_platelist[] = $plate;
$inDateTime = $values['entry_datetime'];
$outDateTime = $values['exit_datetime'];
$tmp = explode(' ', $inDateTime);
$inDate = $tmp[0];
$in_ts = strtotime($inDateTime);
$out_ts = strtotime($outDateTime);
$duration = $out_ts - $in_ts;
$dur_array = intToDateArray($duration);
$dur_string = '';
if ($dur_array['days'] > 0) {
$dur_string .= $dur_array['days'] . ' days ';
}
if ($dur_array['hours'] > 0) {
$dur_string .= $dur_array['hours'] . ' hours ';
}
if ($dur_array['mins'] > 0) {
$dur_string .= $dur_array['mins'] . ' minutes ';
}
if ($dur_array['secs'] > 0) {
$dur_string .= $dur_array['secs'] . ' secs ';
}
$myArray[$plate][] = array($inDateTime, $outDateTime, $inDate, $dur_string);
}
}
while ($startLoopDate < $endLoopDate) {
$dayString = strftime("%a, %d %B %Y", $startLoopDate);
$dayCheck = strftime("%Y-%m-%d", $startLoopDate);
print "<h2>$dayString</h2>";
print "<table width=\"100%\">";
print " <tr>";
print " <th>VRM</th>";
print " <th>Permit Group</th>";
print " <th>Entry Time</th>";
print " <th>Exit Time</th>";
print " <th>Duration</th>";
print " </tr>";
foreach($new_platelist as $wlPlate) {
if ($myArray[$wlPlate][0][2] == $dayCheck) {
print "<tr>";
print "<td>$wlPlate</td>";
if (isset($myArray[$wlPlate])) {
print "<td>".$staticWhitelistArray[$wlPlate]['groupname']."</td>";
print "<td>".$myArray[$wlPlate][0][0]."</td>";
print "<td>".$myArray[$wlPlate][0][1]."</td>";
print "<td>".$myArray[$wlPlate][0][3]."</td>";
}
else {
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
}
print "</tr>";
}
}
print "</table>";
$startLoopDate = $startLoopDate + $oneDay;
}
}
}
Can you echo this query so we can see what's actually being sent...
$sql = "
SELECT plate
, entry_datetime
, exit_datetime
FROM stats
WHERE plate IN ('$plate_lookup')
AND entry_datetime BETWEEN '$startDateTime' AND '$endDateTime'
AND carpark_id= '$cpId';
";
(This isn't an answer, but I wanted to make use of the additional formatting options)

Categories