Date sorting from input in php from sql? - php

I'm doing a sales recording for my own small shop using the combination of html and php.
I want to have a time selecting input (something like March 2014, April 2014 when selecting)Here is my index.php
<?php
$con=mysqli_connect("192.168.1.248","a","a","services");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM pcsales");
echo "<h3><marquee><b>====PC Sales====</b></marquee></h3>";
echo "<button type='button' name='add' onClick='add()'>Add</button>";
echo "<script type='text/javascript'>
function add()
{
window.location='./edit';
}
</script>";
echo "<button type='button' name='edit' onClick='edit()'>Edit</button>";
echo "<script type='text/javascript'>
function edit()
{
window.location='./edit/edit.html';
}
</script>";
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Type</th>
<th>If Others</th>
<th>Brand</th>
<th>Description</th>
<th>Date Sold</th>
<th>Serial No.</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td><p style='font-size:12px'>" . $row['ID'] . "</p></td>";
echo "<td>" . $row['Type'] . "</td>";
echo "<td>" . $row['Types'] . "</td>";
echo "<td>" . $row['Brand'] . "</td>";
echo "<td><p style='font-size:12px'>" . $row['Description'] . "</p></td>";
echo "<td><p style='font-size:12px'>" . $row['Selldate'] . "</p></td>";
echo "<td><p style='font-size:12px'>" . $row['Serial'] . "</p></td>";
echo "</tr>";
}
echo "</table>";
echo "<h3><marquee direction=right><b>====PC Sales====</b></marquee></h3>";
mysqli_close($con);
?>
I'm using TIMESTAMP in mysql.
Here is the output
ID Type If Others Brand Description Date Sold Serial No.
1 Notebook Acer E1 Add 2GB DDR3 1600 RAM 2014-06-25 11:57:58 123456789
2 Others AIO Asus N/A 2014-07-25 12:52:12 987654321
3 Desktop Trendsonic Full spec listed. 2014-07-30 09:55:10 N/A
When I put a range on a textbox (more expedient if selectable)
Example:
July 2014
Then the output shall be
ID Type If Others Brand Description Date Sold Serial No.
2 Others AIO Asus N/A 2014-07-25 12:52:12 987654321
3 Desktop Trendsonic Full spec listed. 2014-07-30 09:55:10 N/A
If only2014 is inserted, then it shall output everything from Year 2014
Is it possible to do that?
Note: I don't care about exploits, as it is used internally.

Better to take datepicker and fetch date from there in variable and make query some how like this.
SELECT *
FROM TABLENAME
WHERE MONTH(dateColumnname) = $month AND YEAR(dateColumnname) = $year;
EXAMPLE: SELECT *
FROM testerpractice
WHERE MONTH(datess) = '03' AND YEAR(datess) = '2017';
Best OF Luck...

Better use dropdown lists ( tag) for day, month and year (with defaults 01 for day, Jan for month, current year for the year) , and concatenate their values to get the search string. You'll have expediency and will be able to construct the query easy.

-Problem Solved-
My solution(not that "professional")
I do a sort.html and a sort.php
The sort.html contains
Year:<input type="text" value="" name="year"/>
Month:<input type="text" value="" name="month"/>
While the sort.php contains
$year = mysqli_real_escape_string($con, $_POST['year']);
$month = mysqli_real_escape_string($con, $_POST['month']);
$result = mysqli_query($con,"SELECT * FROM pcsales WHERE Selldate >= '$year-$month-01 00:00:00' AND Selldate <= '$year-$month-31 23:59:59'");
This might be a reference for other people who might encounter the same problem as me~

Related

MYSQL TIMESTAMP when adding DATE_FORMAT then the output is blank, PHP conflict?

Usingthe following shortcode function, I have the code building a table by querying the DB. That all works fine. BUT when I add any type of formatting to the TimeStamp column such as DATE_FORMAT or TIME the output for that column only goes blank. No errors are in the console to look at. I am trying to extract only the time and put it in a 12 hour format instead of the typical TIMESTAMP format of date and time in the 24hr set up.
Is there a conflict with some of the PHP that causes it not to display the timestamp?
function test2() {
global $wpdb;
$results = $wpdb->get_results("SELECT `name`, `partysize`, `phonenumber`, `emailaddress`, DATE_FORMAT(`Time_stamp`, '%h %i' ), `Wait`, `currentstatus` FROM mytablename m RIGHT JOIN (SELECT wdt_ID, CONCAT(ROUND(Time_to_sec(TIMEDIFF (NOW() ,`Time_stamp`))/60,0), ' Min') AS Wait FROM mytablename) as t on m.wdt_ID = t.wdt_ID WHERE Time_stamp >= date_sub(now(),interval 3 hour) ");
if(!empty($results))
{
echo "<table width='100%' border='0' style='display:inline-table'>
<th>Name</th>
<th>Party Size</th>
<th>Phone Number</th>
<th>Email Address</th>
<th>Time Stamp</th>
<th>Status</th>
<th>Wait</th>
<th>Action</th> ";
echo "<tbody>";
foreach($results as $row){
echo "<tr>";
//echo "<td>" . $row->wdt_ID . "</td>";
echo "<td>" . $row->name . "</td>";
echo "<td>" . $row->partysize . "</td>";
echo "<td>" . $row->phonenumber . "</td>";
echo "<td>" . $row->emailaddress . "</td>";
echo "<td>" . $row->Time_stamp . "</td>";
echo "<td id='tdid_".$row->wdt_ID."'>" . $row->currentstatus . "</td>";
echo "<td>" . $row->Wait . "</td>";
echo '<td> </td>';
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
add_shortcode('test2', 'test2');
EDIT 1
As per Eric7777777 I have added the print and its output is below when using just the Time_stamp:
Array
(
[0] => stdClass Object
(
[wdt_ID] => 9
[name] => test2
[partysize] => 3
[phonenumber] => 465
[emailaddress] => dis#doc.com
[Time_stamp] => 2020-09-24 19:02:47
[currentstatus] => Waiting
[Wait] => 138 Min
)
)
and with the DATE_FORMAT(Time_stamp:
Array
(
[0] => stdClass Object
(
[DATE_FORMAT(Time_stamp, '%h %i %p')] => 07 02 PM
)
)
In Database you need add a type of TIMESTAMP UTF8 general_ci. It may be help.
And show us what displaying in var_dump` or print_r of your array.
Special code is
print_r($your_array);
or
echo '<pre>';
print_r($your_array);
echo'</pre>';
Is there a conflict with some of the PHP that causes it not to display the timestamp?
What are you trying to output? $row->Time_stamp.
Now your original object had such a property, as your debug output showed:
[Time_stamp] => 2020-09-24 19:02:47
Now look closely at your second debug output, what’s in there now?
[DATE_FORMAT(Time_stamp, '%h %i %p')] => 07 02 PM
That is a totally different property name than before.
Now while you could try and access that via the curly braces syntax ($row->{' DATE_FORMAT(Time_stamp, '%h %i %p')'}), it makes much more sense, that you give this column a different name in your result set, by specifying an ALIAS in your query:
$results = $wpdb->get_results("SELECT …, DATE_FORMAT(`Time_stamp`, '%h %i' ) AS Time_stamp, …");
With that alias, you will be able to access the value as $row->Time_stamp again.
No errors are in the console to look at.
Browser console shows client-side errors, but yours here was on the server side.
You should enable proper PHP error reporting - in this case, PHP would have told you, that you are trying to access a non-existing object property. See How do I get PHP errors to display? for details.

php sql formatting SELECT columns numbers

I am retrieving various columns from an SQL table and some of those are numeric or currency, in a sample let’s say:
$sql="SELECT id_column, event_column, amount_column FROM table1";
Then I show them using that:
$result = mysqli_query($conn,$sql);
echo "<table border='1'>
<tr>
<th>id</th>
<th>event time</th>
<th>amount</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row[' id_column '] . "</td>";
echo "<td>" . $row[' event_column '] . "</td>";
echo "<td>" . $row[' amount_column '] . "</td>";
echo "</tr>";
}
echo "</table>";
Is it possible to change the format numbers get out in amount_column?
I saw should be possible to use a command to change a single number data the way I wuold like - number_format($number, 2, ',', '.') – but this seems not to apply for entire columns
What I do need is using comma for decimal under one (yy) and point for others grouped by 3 (x.xxx) thousands, something like xx.xxx.xxx,yy
Does some one have any suggestion? (including how to change the settings in PHP or SQL by the moment when I entry the data via form those have a comma instead of point for decimal but SQL save them in a different way – UK/USA decimal punctuation I guess while I need EU Italian/Germany punctuation or at least the ISO standard using comma for decimal and space for each group of three numbers).
Correct answer is my comment:
echo "<td>" . number_format($row['amount_column'], 2, ',', ' ') . "</td>";
You can not do:
$row[' amount_column ']
Spacing for array index count!
here is a proof https://ideone.com/FtPEc6
So technically the answer you've approved - is wrong.
UPDATE:
Yes, true money_format works not on windows. Thanks Dave. :)
Use number_format( $row[' amount_column '], 2, ',', '.')
It gives you something like 123.456.789,12
PHP number_format
(Not on windows!)
You can use php´s money_format('%i', $row[' amount_column '])
PHP money_format
<?php
setlocale(LC_MONETARY, 'en_US');
$result = mysqli_query($conn,$sql);
echo "<table border='1'>
<tr>
<th>id</th>
<th>event time</th>
<th>amount</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row[' id_column '] . "</td>";
echo "<td>" . $row[' event_column '] . "</td>";
echo "<td>" . money_format('%i', $row[' amount_column ']) . "</td>";
echo "</tr>";
}
echo "</table>";

How to display table row like this

i have this table in mysql
this is mycode
//generate report
<center>
<table border=1 cellpadding=10>
<tr>
<td rowspan="2">TANGGAL</td>
<td colspan="2" align="center">PAGI</td>
<td colspan="2" align="center">SORE</td>
<td rowspan="2">JML. JAM</td>
<td rowspan="2">JML. Rp</td>
</tr>
<tr>
<td>Masuk</td>
<td>Keluar</td>
<td>Masuk</td>
<td>Keluar</td>
</tr>
<?php
$qry_tgl=mysql_query("SELECT id_peg, date(waktu) Tgl from absen where id_peg=1 group by Tgl");
while($row=mysql_fetch_array($qry_tgl)){
echo "<tr>";
echo "<td>".$row['Tgl']."</td>";
echo "</tr>";
}
echo "</table></center>";
I want to display table in php like this
Please help me, I'm very confuse what to do
thankyou
Your HTML code seems to be fine, but SQL query not. I assume you were asking about how to make a correct query. When using GROUP BY you should (and in newer MySQL versions by default must) select only fields with either aggregate functions like SUM, AVG, etc., or select fields that are specified in GROUP BY. You cannot group by result of a select.
Your query should be like this:
SELECT DATE(waktu) Tgl FROM absen WHERE id_peg=1 GROUP BY DATE(waktu)
EDIT: Ok, according to google translate and other sites Masuk/Keluar are Since/Till. And using new provided information this should do the trick:
<center>
<table border=1 cellpadding=10>
<tr>
<td rowspan="2">TANGGAL</td>
<td colspan="2" align="center">PAGI</td>
<td colspan="2" align="center">SORE</td>
<td rowspan="2">JML. JAM</td>
<td rowspan="2">JML. Rp</td>
</tr>
<tr>
<td>Masuk</td>
<td>Keluar</td>
<td>Masuk</td>
<td>Keluar</td>
</tr>
<?php
function display_row($timeRanges) {
$pagi = isset($timeRanges[1]) ? strtotime($timeRanges[1]) - strtotime($timeRanges[0]) : 0;
$sore = isset($timeRanges[3]) ? strtotime($timeRanges[3]) - strtotime($timeRanges[2]) : 0;
$seconds = $pagi + $sore;
echo "<tr>";
echo "<td>" . substr($timeRanges[0], 0, 10) . "</td>"; // TANGGAL
echo "<td>" . substr($timeRanges[0], 11, 8) . "</td>"; // PAGI Masuk
echo "<td>" . (isset($timeRanges[1]) ? substr($timeRanges[1], 11, 8) : "") . "</td>"; // PAGI Keluar
echo "<td>" . (isset($timeRanges[2]) ? substr($timeRanges[2], 11, 8) : "") . "</td>"; // SORE Masuk
echo "<td>" . (isset($timeRanges[3]) ? substr($timeRanges[3], 11, 8) : "") . "</td>"; // SORE Keluar
echo "<td>" . round($seconds / 3600, 2) . "</td>"; // JML. JAM shows rounded number of hours
echo "<td>" . round($seconds * 5000 / 3600) . "</td>"; // JML. Rp number hours * 5000
echo "</tr>";
}
$qry_tgl=mysql_query("SELECT DATE(waktu) Tgl, waktu FROM absen WHERE id_peg=1 ORDER BY waktu");
$lastDate = null;
$timeRanges = array();
while($row=mysql_fetch_array($qry_tgl)){
if( $row['Tgl'] !== $lastDate ) {
if( $lastDate !== null )
display_row($timeRanges); // renders the row when the date changes, but only if we fetched at least one date
$lastDate = $row['Tgl'];
$timeRanges = array();
}
$timeRanges[] = $row["waktu"];
}
if( $lastDate !== null )
display_row($timeRanges); // renders the last row when the loop ends, but also only if we fetched at least one date
echo "</table></center>";
This algorithm reads dates into $timeRanges array until another date is encountered. So when display_row() function is called the $timeRanges will contain only ordered records for the same date.
I'm afraid doing it using only MySQL would be slow and a huge waste of resources.

Adding total of array in php?

I have a database and PHP file which outputs a module catogaries by the year the module was taken in. accompanying this is how much the module is worth.. eg Computer Science 10. The output on the screen needs to have the TOTAL of the points within that YEAR
So it looks like this:
2001/02
cs 10
bi 10
chem 10
total 30
This is all fine and works APART from if there is more years like this:
2001/02 0 points
2002/03 120 points
2003/04 120 points
But there is points in 2001/02 but the code seems to overwrite this before outputting it.
Here is the PHP code:
$points = array();
while ($row = mysql_fetch_array($result)) {
if ($year != $row["ayr"]) {
echo "<tr><th colspan='3'><b>" . $row["ayr"] . "</b></th></tr>";
$year = $row["ayr"];
echo "<td align='right'><b> Total Module Points: ".array_sum($points)."<td></b>";
$points = array();
}
if ($year = $row["ayr"]) {
array_push($points, $row["credits"]);
}
echo "<tr>";
echo "<td>" . $row["mid"] . "</td>";
echo "<td>" . $row["mtitle"] . "</td>";
echo "<td>" . $row["credits"] . "</td>";
echo "<tr>";
if ($year != $row["ayr"]) {
echo "<td align='right'> Total Module Points: ".array_sum($points)."<td>";
}
}
So the code gets the student number, output each module by year and then adds up the module points and gives a total but I cannot get the first table to work
regards
Maybe this causes your problem?
if ($year = $row["ayr"]) {
array_push($points, $row["credits"]);
}
Basically, $year will always be equal to $row["ayr"], is this a desired behavior?
The 'equal' comparison operator is '==' as stated before.

How to loop data for the same id without showing the id repeatedly using foreach?

I'm trying to display rental amount and days relevant to car id. I'm first displaying car names for car Make clicked by user.
When it displays car names,it must display number of rental days and rental amount as well.
But since I store days and amount for a car id in the backend three times, it also loop three times in front end.
To make it clearer:
// in the back end,
I stored the days and amount for a car multiple times instead of one time
carName days amount
carname1 1 50
carname1 7 650
carname1 30 2000
And I'm calling the carName,gallery,rental_days and rental_amount like this:
if(isset($q))
{
mysql_select_db($database);
/*$query_showmake="SELECT carName FROM car_name WHERE carMake_id='$q'";*/
$query_showmake="SELECT rental.rental_days,rental.rental_amount,rental.carName_id,car_name.carName_id,car_name.carName,car_name.carMake_id,gallery,gallery_id,gallery.gallery,gallery.carName_id,car_make.carMake_id FROM rental,car_name,gallery,car_make WHERE car_name.carName_id=gallery.carName_id AND car_name.carMake_id='$q' AND car_name.carMake_id=car_make.carMake_id AND rental.carName_id=car_name.carName_id ORDER BY rental_days ASC";
$result_showmake=mysql_query($query_showmake)or die(mysql_error());
while($row_showmake=mysql_fetch_array($result_showmake))
{
$carMake_show=$row_showmake['carName'];
$carmake[$row['carName_id']][]=$row_showmake;
/* echo $carMake_show.'<br/>';*/
}
?>
<table border="0" style="border-collapse:collapse">
<?php
foreach($carmake as $make=>$name)
{
foreach($name as $n)
{
echo "<tr>";
echo "<td class='carname'>".$n{'carName'}.'</td><td rowspan="2" valign="top" class="cardetail">Car Details</td></tr>';
/*echo $n{'carMake_id'}.'<br/>';
echo $n{'gallery'}.'<br/>';*/
echo"<tr><td class='img'><img src='management/uploads/{$n['carMake_id']}/{$n['gallery']}' width='400' height='200'>";
echo "</td></tr>";
echo"<tr><td colspan='2' class='days'>Days : ";
$days[]=$n['rental_days'];
foreach($days as $day)
{
echo $day." ";
}
echo "</td></tr>";
echo"<tr><td colspan='2' class='days'>Amount : ";
$amount[]=$n['rental_amount'];
foreach($amount as $amt)
{
echo "RM ".$amt." ";
}
echo "</td></tr>";
echo"<tr><td height='50' colspan='2'></td></tr>";
}
}?>
</table>
<?php
}
And it displays the result like this:
carName 1
image 1
days 1
amount 50
carName 1
image 1
days 7
amount 650
carName 1
image 1
days 30
amount 2000
AND I want to display like:
carname 1
days:1 7 30
amt: 50 650 2000
In your main fetch loop stack the values you want to display in an indexed array like this
while($row = mysql_fetch_array($result_showmake)) {
$carmake[$row['carName_id']]['amounts'][] = $row['rental_amount'];
$carmake[$row['carName_id']]['days'][] = $row['rental_days'];
$carmake[$row['carName_id']]['images'][] = $row['gallery'];
}
Then use implode to render the stacked values as a space separated string
foreach($carmake as $id => $make) {
print "carName $id\n"
. "images " . implode(' ', $make['images']) . "\n"
. "days " . implode(' ', $make['days']) . "\n"
. "amounts " . implode(' ', $make['amounts']) . "\n";
}
Btw, you shouldn't use mysql_* functions as they're deprecated. Consider moving to mysqli or PDO.

Categories