We have a script that generate invoice once a month (cron). But we would like to add feature, that we would be able to select date range "from - to" and then generate invoice only for the date selected.
I guess making input fields with calendar pop-up isn't hard, but filtering with PHP is a bit bigger challenge, so if anyone want to take a look at my code and give me some tips, I would be grateful.
function genInvoice($clientID, $orderID=0, $paid=false)
{
if($orderID == 0)
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and status='closed' and tblusers.clientid=" . $clientID;
else
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and tblusers.clientid=" . $clientID . " and tblorders.id=" . $orderID;
$res = full_query($sql) or die(mysql_error());
// If no closed orders uninvoiced, just return
if(!mysql_num_rows($res))
return 0;
$amount = 0;
$orders = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
// print_r($row);
// print "<br><hr>";
$amount += $row['amount'];
$orders[] = $row['id'];
}
$date = date("Y-m-d");
$status = $paid ?'Paid' : 'Unpaid';
$sql = "insert into tblinvoices (clientid, date, duedate, subtotal, total, status) values (" . $clientID . ",'" . $date .
"','" . $date . "'," . $amount . "," . $amount . ",'" . $status . "')";
$res = full_query($sql) or die(mysql_error());
$invoiceid = mysql_insert_id();
$sql = "update tblorders set invoiceid=" . $invoiceid . " where id in (" . implode(",", $orders) . ")";
$res = full_query($sql) or die(mysql_error());
$sql = "select tblorders.id as ReportID, FirstName, LastName, SearchName, CountyID, StateID, bl_orderitems.userid, bl_orderitems.amount, " .
"bl_orderitems.notes from tblorders, bl_orderitems left join bl_search on bl_search.id=packageid where tblorders.id in (" .
implode(",", $orders) . ") and bl_orderitems.orderid=tblorders.id order by tblorders.id,bl_orderitems.id";
$res = full_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
if($row['CountyID'] != 0)
$locale = getCounty($row['CountyID']);
else if($row['StateID'] != 0)
$locale = getState($row['StateID']);
if($row['SearchName'] != "")
$description = mysql_real_escape_string($row['FirstName'] . " " . $row['LastName'] . " " .
$row['SearchName'] . " " . $locale . " (Order #" . $row['ReportID'] . ")");
else
$description = "Search Package: " . mysql_real_escape_string($row['notes'] . " (Order #" . $row['ReportID'] . ")");
$sql = "insert into tblinvoiceitems (invoiceid, userid, type, description, amount, duedate) values " .
"(" . $invoiceid . "," . $row['userid'] . ",'search','" . $description . "','" .
$row['amount'] . "','" . $date . "')";
// print $sql . "<br>";
full_query($sql) or die(mysql_error());
}
sendmessage ('Invoice Created', $invoiceid);
return $invoiceid;
}
not going to look through all that code, but filtering results by a date range is easy.
SELECT id FROM some_table WHERE some_date_field BETWEEN $first_date AND $second_date
Related
I am making e-commerce site and add to basket script not doing anything
I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
header("Location: " . $config_basedir);
} else {
if($_POST['submit'])
{
if($_SESSION['SESS_ORDERNUM'])
{
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", "
. $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
if($_SESSION['SESS_LOGGEDIN'])
{
$sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
. $_SESSION['SESS_USERID'] . ", 1, NOW())";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM']
. ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
$sql = "INSERT INTO orders(registered, date, session) VALUES("
. "0, NOW(), '" . session_id() . "')";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
}
}
$totalprice = $prodrow['price'] * $_POST['amountBox'] ;
$updsql = "UPDATE orders SET total = total + "
. $totalprice . " WHERE id = "
. $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);
header("Location: " . $config_basedir . "showcart.php");
} else {
require("header.php");
echo "<form action='addtobasket.php?id="
. $_GET['id'] . "' method='POST'>";
echo "<table cellpadding='10'>";
echo "<tr>";
if(empty($prodrow['image']))
{
echo "<td><img src='./productimages/dummy.jpg' width='50' alt='"
. $prodrow['name'] . "'></td>";
} else {
echo "<td><img src='./productimages/" . $prodrow['image']
. "' width='50' alt='" . $prodrow['name']
. "'></td>";
}
echo "<td>" . $prodrow['name'] . "</td>";
echo "<td>Select Quantity <select name='amountBox'>";
for($i=1;$i<=100;$i++)
{
echo "<option>" . $i . "</option>";
}
echo "</select></td>";
echo "<td><strong>£"
. sprintf('%.2f', $prodrow['price'])
. "</strong></td>";
echo "<td><input type='submit' name='submit' value='Add to basket'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
}
require("footer.php");
error_reporting(E_ALL);
?>
there are two redirects that makes your user return to your home page
first:
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
make sure $_GET['id] has valid value
second:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$numrows = mysqli_num_rows($prodres);
// ...
if($numrows == 0)
{
header("Location: " . $config_basedir);
}
check your query in this line:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
make sure it returns not an empty results ( $numrows == 0 )
Test it first on your DBMS front-end
What am I missing?
I have a drop down with values. I think everything is working fine, except when I post the results to another table I can't seem to get the gameID from the first table to post, it just goes through as blank. Am I missing an association with the team and the gameID?
Query to get data for drop down:
$sql = "select s.*, (DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > gameTimeEastern or DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > '" . $cutoffDateTime . "') as expired ";
$sql .= "from " . DB_PREFIX . "schedule s ";
$sql .= "inner join " . DB_PREFIX . "teams ht on s.homeID = ht.teamID ";
$sql .= "inner join " . DB_PREFIX . "teams vt on s.visitorID = vt.teamID ";
$sql .= "where s.weekNum = " . $week . " ";
$sql .= "order by s.gameTimeEastern, s.gameID";
//echo $sql;
$query = $mysqli->query($sql) or die($mysqli->error);
if ($query->num_rows > 0) {
$i = 0;
while ($row = $query->fetch_assoc()) {
$sGameID = (int)$row['gameID'];
$homeTeam = new team($row['homeID']);
$visitorTeam = new team($row['visitorID']);
$surv_pick_options_h[$i]=$row['homeID'];
$surv_pick_options_v[$i]=$row['visitorID'];
if ($row['expired']){
$surv_pick_expired_h[$i]=$row['homeID'];
$surv_pick_expired_v[$i]=$row['visitorID'];
}
$surv_gameID[$i] = (int)$row['gameID'];
$i++;
$rowclass = (($i % 2 == 0) ? ' class="altrow"' : '');
}
};
Drop down select option:
$sWeek = (int)getCurrentWeek()+1;
if ($week < $sWeek){
$survpicks_to_disable = array_slice($survpicks,0,$week-1);
$disabled = array_merge($survpicks_to_disable,$surv_pick_expired_h,$surv_pick_expired_v);
echo '<select name="survpick" id="survpick">
<option default>Select</option>';
foreach($surv_pick_options_h as $home){
echo '<option value="'.$home.'"'.(in_array($home,$disabled)?' style="background-color:pink" disabled':'').($home == $currentID?' selected':'').'>'.$home.'</option>';
}
foreach($surv_pick_options_v as $visitor){
echo '<option value="'.$visitor.'"'.(in_array($visitor,$disabled)?' style="background-color:pink" disabled':'').($visitor == $currentID?' selected':'').'>'.$visitor.'</option>';
}
}
echo '</select>';
}
And finally update a table with results:
$sql = "insert into " . DB_PREFIX . "picksurvivor (weekNum, userID, user, gameID, picksurv, showPicks) values (" . $_POST['week'] . ", " . $user->userID . ",'" . $user->userName . "', '" . $surv_gameID . "', '" . $_POST['survpick'] . "', ". (int)$_POST['showPicks'] . ");";
$mysqli->query($sql) or die('Error deleting survivor pick: ' . $mysqli->error);
I found a different approach, doing an update after the insert to basically brute force the gameID in there.
So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>
I'm creating an appointment plugin, in that for already members and new members are there. in already member area the date entry is not entring into db. but when displaying the variale contains the date. i'm have been checking this from morning but didn't get what is the error. my code is:
$source = mysql_real_escape_string(trim($_POST['apdatetime']));
$datetime = explode(',', $source);
$dates = $datetime[0];
$app_time = $datetime[1];
if($app_time < 12){
$app_session = 'am';
}
else{
$app_session ='pm';
}
$splitdatet = explode('/', $dates);
$yyear = $splitdatet[2];
$mmonth = $splitdatet[1];
$ddate = $splitdatet[0];
$app_date = $yyear . "-" . $mmonth . "-" . $ddate;
if ($_POST['isnewpatient'] == "false") {
//$cSql = "select * from " . WP_contact . " where appointments_c_patientid='" . trim($_POST['ptntid']) . "' ";
$cSql = "select * from " . WP_eemail_TABLE_SUB . " where eemail_patient_id='" . trim($_POST['ptntid']) . "' ";
$data = $wpdb->get_results($cSql);
if (empty($data )) {
$err = 1;
echo "<div id='message' class='aerror'>No such patient ID exists....</div>";
} else {
#$mobile = htmlspecialchars(stripslashes($data[0]->eemail_mobile_sub));
#$email = htmlspecialchars(stripslashes($data[0]->eemail_email_sub));
#$name = htmlspecialchars(stripslashes($data[0]->eemail_name_sub));
$sqlss = "insert into " . WP_Appointments .
" (`appointments_patient_id`,`appointments_date`,`appointments_time`,`appointments_session`,`appointments_reg_date`) VALUES ('" .
mysql_real_escape_string(trim($_POST['ptntid'])) . "','" .
$app_date . "','" .
$app_time . "','" .
$app_session . "',CURRENT_TIMESTAMP() )";
$dd=$wpdb->get_results($sqlss);
var_dump($dd);
echo 'Date:'.$app_date;
// return $suc;
echo "<div id='message' class='asuccess' >Request has been sent for appointment</div>";
}
}
The output of the var_dump is array[0] and $app_date is Date:2014-10-22
The db entry is
appointments_id :393
appointments_patient_id : 9999999999
appointments_date : 0000-00-00
appointments_time : 9:00
appointments_session : am
appointments_reg_date : 2014-09-25 14:21:35
could anyone please point out the mistake in the code if any??
You should convert your string into date object like this:
$app_date = date('Y-m-d',strtotime($app_date));
On my main page, when someone signs-in, i have jQuery using AJAX to 'talk' to a PHP file, and the same for when they sign-out. But, when they sign out, it is supposed to update a database index with the time they left. If they database entry for their last name doesn't exist (meaning, they didn't sign-in), it is supposed to return an error. Instead, the PHP file is saying that it IS updating a non-existant database index. i am using IF statements to achieve this. and for some reason it thinks the index does exist. I've checked the database that it is writing to and the indexes it's supposed to be updating don't exist.
Here's my code:
if ($Type == 1)
{
$mysqli = new mysqli("localhost","----","----", "----");
if (!$mysqli)
$Type = 3;
$Select = $mysqli->query("SELECT Time_Out FROM " . $Date . " WHERE Last_Name = '" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_Out'];
if ($Row2 !== "-1") $Type = 4;
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
$Select = $mysqli->query("SELECT Time_In FROM " . $Date . " WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_In'];
$Time2 = explode(":",$Row2);
$Hour2 = $Hour - $Time2[0];
if ($mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'"))
{$Select = $mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row3 = $Row['Hours'];
$Auto += 1;}
$Time3 = 60-$Time2[1];
if ($Hour != 21) $Time4 = $Min;
$Time5 = $Time3+$Time4;
if ($Time2[0]+1 != $Hour)
{$Time5 = $Time5+60;}
$Total = $Time5+intval($Row3);
if ($Type == 1)
{
if ($mysqli->query("UPDATE Names SET Hours = '" . $Total . "' WHERE Last_Name = '" . $LName . "'"))
{$Auto += 1;}
else
{$mysqli->query("INSERT INTO Names (Last_Name, First_Name, Hours) VALUES ('" . $LName . "', '" . $FName . "', '" . $Total . "')");}
}
$mysqli->close();
}
if ($Type == 1) echo "Thank you " . $FName . " " . $LName . " for signing out! See you next time!";
if ($Type == 2) echo "The entered Student ID# is invalid. Please try again!";
if ($Type == 3) echo "An unexpected error has occured. Please try again!";
if ($Type == 4) echo "You have already signed out today!" . $Auto;
if ($Type == 5) echo "You didn't sign in today.";
The UPDATE sql statement will return true, even if it doesn't find any matches (it still runs correctly, it just updates 0 rows).
Change this:
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
To this:
if ($Type == 1) {
if ($mysqli->query("SELECT * FROM " . $Date . " WHERE Last_Name='" . $LName . "'")->num_rows > 0)
$mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'");
else
$Type = 5;
}
You run the select query to first determine if the record exists (if num_rows property of the result is > 0) and based on that either update the record or set your return value to 5.