I have problem with SQL DELETE in PHP language. I don't know where is the problem about delete sql operation.
Could you help me, please?
The code is:
$query = mysqli_query($connessione, "SELECT * FROM (SELECT date, time, temperature FROM streamcopy WHERE moteid = '".$sensor."' AND CONCAT(DATE, ' ',TIME) BETWEEN '".$i."' AND '".$f."' ORDER BY date DESC, time DESC) AS tab ORDER BY date, time");
$n = 0;
$m = 0;
while($row = mysqli_fetch_array($query)){
if($n == 0){
$num = $row['temperature']; //OK
$n = $n+1;
}
else{
$temp[$m] = $row; //OK
if(abs($num - $temp[$m]['temperature'])<0.5){ //OK
$queryFIXED = mysqli_query($connessione, "DELETE FROM streamcopy WHERE moteid = '".$sensor."' AND temperature = '".$temp[$m]['temperature']."' AND date = '".$temp[$m]['date']."' AND time = '".$temp[$m]['time']."')"); /* elimina dati di temperatura k vicini */
$n = $n+1;
$m = $m+1;
}
else{
$num = $temp[$m]['temperature'];
$n = $n+1;
$m = $m+1;
}
}
}
Related
I have two tables with the name of add_sell and add_expense.
I have inserted some of value into the tables. I wanted to get the total profit result. I did it myself but the result is showing 0 . Now how can I do that. I also give the total profit formula. Is anyone here to help me? Here is the code given below
function totalSell(){
global $conn;
$sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
$result = $conn->query($sql);
$getDate = date('d/m/Y');
if(mysqli_num_rows($result) > 0){
while($fetch = mysqli_fetch_array($result)){
echo "SR ".$fetch['Sumearning'];
}
}
}
function totalExpense(){
global $conn;
$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
$run_ex = $conn->query($ex);
if (mysqli_num_rows($run_ex) > 0) {
while ($tex = mysqli_fetch_array($run_ex)) {
echo "SR ".$tex['Sumexpense'];
}
}
}
function totalProfit(){
global $conn;
$sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
$result = $conn->query($sql);
$getDate = date('d/m/Y');
while($fetch = mysqli_fetch_array($result)){
$fetch['Sumearning'];
echo "Total Earning : ".$totalEarning = "SR ".$fetch['Sumearning'];
}
$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
$run_ex = $conn->query($ex);
while ($tex = mysqli_fetch_array($run_ex)) {
$tex['Sumexpense'];
echo "Total Expense : ".$totlaExpenss = "SR ".$tex['Sumexpense'];
}
echo "Your totla Profit is : ".$totalprofit = $totalEarning - $totlaExpenss;
}
Total profit result you can get from query itself.
$sql = "SELECT SUM(`sell_amount`)-(SELECT SUM(`expense_amount`) FROM `add_expense` WHERE expense_amount = `expense_amount`) AS `PROFITLOSS` FROM `add_sell` WHERE sell_amount = `sell_amount`";
Note: as Sumearning and as Sumexpense Removed instead you will get as PROFITLOSS
Do you mean getting the difference between the Sum earnings and the Sum expenses?
Because you can do it like this?
$Total = $tex['Sumexpense'] - $fetch['Sumearning'];
Echo $total;
Please I've been trying to create a function that would query a DB, select from the table, and if the row count is not equal to 6, then a row from the table and repeat (or maybe duplicate) until the row count is equal to 6. I've search for this here in StackOverflow, but didn't get anything close. Please if you have a similar link to this, please post it here, and I'll give it a go.
Here's my code:
//List All active adverts
function showActiveAdverts()
{
$status = 1;
//Build final queries.
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
# My question here, check if the $count >= 1 && $count != 6, then do getDefaultBannner() and repeat it until it runs for 6 times.
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Here's the code for getDefaultBannner()
function getDefaultBannner()
{
$status = 6;
$query = mysql_query("SELECT id FROM table WHERE status = '".mysql_real_escape_string($status)."' ")
or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Thanks in advance!
You can rewrite your code as this
//List All active adverts
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
if($count >= 1 && $count != 6)
$list = getDefaultBannner();
else
$list = showActiveAdverts($query);
function showActiveAdverts($query)
{
$status = 1;
//Build final queries.
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.
Okay so I am new to PHP and attempting to make a script that takes all of the data from a mysql database I have of stock prices and then looks to see if there was an increase in the stock price during after hours trading (by comparing one day's close price with the next day's open price). I have set up a few scripts like this that work, but for some reason this script isn't copying the data into my sql database and I am completely stumped as to why it won't.When I set up echo statements throughout I discovered that my code is seemingly being executed everywhere but the data isn't transferring. Any help is greatly appreciated.
<?php
include("../includes/connect.php");
function masterLoop(){
$mainTickerFile = fopen("../tickerMaster.txt","r");
while (!feof($mainTickerFile)){
$companyTicker = fgets($mainTickerFile);
$companyTicker = trim($companyTicker);
$nextDayIncrease = 0;
$nextDayDecrease = 0;
$nextDayNoChange = 0;
$total = 0;
$overnight_change = 0;
$overnight_change_pct = 0;
$sumOfIncreases = 0;
$sumOfDecreases = 0;
$sql = "SELECT date, open, close, percent_change FROM $companyTicker";
$result = mysql_query($sql);
if($result){
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$percent_change = $row['percent_change'];
$open = $row['open'];
$close = $row['close'];
$sql2 = "SELECT date, open, close, percent_change FROM $companyTicker WHERE date > '$date' ORDER BY date ASC LIMIT 1";
$result2 = mysql_query($sql2);
$numberOfRows = mysql_num_rows($result2);
if($numberOfRows==1){
$row2 = mysql_fetch_row($result2);
$tom_date= $row2[0];
$tom_open= $row2[1];
$tom_close= $row2[2];
$tom_percent_change= $row2[3];
if ($close == 0){
$close = $tom_open;
}
$overnight_change = $tom_open - $close;
$overnight_change_pct = ($overnight_change/$close)*100;
if($overnight_change_pct > 0){
$nextDayIncrease++;
$sumOfIncreases += $tom_percent_change;
$total++;
}else if($overnight_change_pct < 0){
$nextDayDecrease++;
$sumOfDecreases += $tom_percent_change;
$total++;
}else{
$nextDayNoChange++;
$total++;
}
}else if ($numberOfRows==0){
$total = 1;
$nextDayIncrease = 1;
$nextDayDecrease = 1;
}else{
echo "You have an error in analysis_c3";
}
}
}else{
echo "unable to select $companyTicker <br />";
}
$nextDayIncreasePercent = ($nextDayIncrease/$total) * 100;
$nextDayDecreasePercent = ($nextDayDecrease/$total) * 100;
$averageIncreasePercentage = $sumOfIncreases/$nextDayIncrease;
$averageDecreasePercentage = $sumOfDecreases/$nextDayDecrease;
insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage);
}
}
function insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage){
$buyValue = $nextDayIncreasePercent * $averageIncreasePercentage;
$sellValue = $nextDayDecreasePercent * $averageDecreasePercentage;
$trueValue = $buyValue + $sellValue;
$query="SELECT * FROM analysisOvernightGain5 WHERE ticker='$companyTicker' ";
$result=mysql_query($query);
$numberOfRows = mysql_num_rows($result);
if($numberOfRows==1){
$sql = "UPDATE analysisOvernightGain5 SET ticker='$companyTicker',daysInc='$nextDayIncrease',pctOfDaysInc='$nextDayIncreasePercent',avgIncPct='$averageIncreasePercentage',daysDec='$nextDayDecrease',pctOfDaysDec='$nextDayDecreasePercent',avgDecPct='$averageDecreasePercentage',buyValue='$buyValue',sellValue='$sellValue'trueValue='$trueValue' WHERE ticker='$companyTicker' ";
mysql_query($sql);
}else{
$sql="INSERT INTO analysisOvernightGain5 (ticker,daysInc,pctOfDaysInc,avgIncPct,daysDec,pctOfDaysDec,avgDecPct,buyValue,sellValue,trueValue) VALUES ('$companyTicker', '$nextDayIncrease', '$nextDayIncreasePercent', '$averageIncreasePercentage', '$nextDayDecrease', '$nextDayDecreasePercent', '$averageDecreasePercentage', '$buyValue', '$sellValue','$trueValue')";
mysql_query($sql);
}
}
masterLoop();
?>
you have missed , at ,sellValue='$sellValue'trueValue='$trueValue'
it should be ,sellValue='$sellValue',trueValue='$trueValue'
I'm using a shopping cart script from a tutorial I came across a while ago, and I need to modify it to calculate sales tax for my state (Pennsylvania). I want it to extract the state, compare it to either Pennsylvania or PA incase someone writes the state shorthand and then multiply the subtotal (for the items.. before shipping is added) by the sales tax for this state and add that to the subtotal. How should I go about doing this? Here is the script that does the calculation for grand total.
<?php
require_once 'config.php';
/*********************************************************
* CHECKOUT FUNCTIONS
*********************************************************/
function saveOrder()
{
$orderId = 0;
$shippingCost = 5;
$requiredField = array('hidShippingFirstName', 'hidShippingLastName', 'hidShippingAddress1', 'hidShippingCity', 'hidShippingPostalCode',
'hidPaymentFirstName', 'hidPaymentLastName', 'hidPaymentAddress1', 'hidPaymentCity', 'hidPaymentPostalCode');
if (checkRequiredPost($requiredField)) {
extract($_POST);
// make sure the first character in the
// customer and city name are properly upper cased
$hidShippingFirstName = ucwords($hidShippingFirstName);
$hidShippingLastName = ucwords($hidShippingLastName);
$hidPaymentFirstName = ucwords($hidPaymentFirstName);
$hidPaymentLastName = ucwords($hidPaymentLastName);
$hidShippingCity = ucwords($hidShippingCity);
$hidPaymentCity = ucwords($hidPaymentCity);
$cartContent = getCartContent();
$numItem = count($cartContent);
// save order & get order id
$sql = "INSERT INTO tbl_order(od_date, od_last_update, od_shipping_first_name, od_shipping_last_name, od_shipping_address1,
od_shipping_address2, od_shipping_phone, od_shipping_state, od_shipping_city, od_shipping_postal_code, od_shipping_cost,
od_payment_first_name, od_payment_last_name, od_payment_address1, od_payment_address2,
od_payment_phone, od_payment_state, od_payment_city, od_payment_postal_code)
VALUES (NOW(), NOW(), '$hidShippingFirstName', '$hidShippingLastName', '$hidShippingAddress1',
'$hidShippingAddress2', '$hidShippingPhone', '$hidShippingState', '$hidShippingCity', '$hidShippingPostalCode', '$shippingCost',
'$hidPaymentFirstName', '$hidPaymentLastName', '$hidPaymentAddress1',
'$hidPaymentAddress2', '$hidPaymentPhone', '$hidPaymentState', '$hidPaymentCity', '$hidPaymentPostalCode')";
$result = dbQuery($sql);
// get the order id
$orderId = dbInsertId();
if ($orderId) {
// save order items
for ($i = 0; $i < $numItem; $i++) {
$sql = "INSERT INTO tbl_order_item(od_id, pd_id, od_qty)
VALUES ($orderId, {$cartContent[$i]['pd_id']}, {$cartContent[$i]['ct_qty']})";
$result = dbQuery($sql);
}
// update product stock
for ($i = 0; $i < $numItem; $i++) {
$sql = "UPDATE tbl_product
SET pd_qty = pd_qty - {$cartContent[$i]['ct_qty']}
WHERE pd_id = {$cartContent[$i]['pd_id']}";
$result = dbQuery($sql);
}
// then remove the ordered items from cart
for ($i = 0; $i < $numItem; $i++) {
$sql = "DELETE FROM tbl_cart
WHERE ct_id = {$cartContent[$i]['ct_id']}";
$result = dbQuery($sql);
}
}
}
return $orderId;
}
/*
Get order total amount ( total purchase + shipping cost )
*/
function getOrderAmount($orderId)
{
$orderAmount = 0;
$sql = "SELECT SUM(pd_price * od_qty)
FROM tbl_order_item oi, tbl_product p
WHERE oi.pd_id = p.pd_id and oi.od_id = $orderId
UNION
SELECT od_shipping_cost
FROM tbl_order
WHERE od_id = $orderId";
$result = dbQuery($sql);
if (dbNumRows($result) == 2) {
$row = dbFetchRow($result);
$totalPurchase = $row[0];
$row = dbFetchRow($result);
$shippingCost = $row[0];
$orderAmount = $totalPurchase + $shippingCost;
}
return $orderAmount;
}
?>
You don't have to handle differing tax rates per municipality? Normally this would be looked up from a tax table by zip code, and maybe even for the street address + zip code (in some states).
It would look like this:
// is it a Pennsylvania zip code?
if ($zipcode < 15000 || $zipcode > 19699) // needs verification of the actual range
$taxrate = 0;
else
{
$rs = mysql_query ("select rate from taxtable where zipcode = '$zipcode'", $db);
if (!$rs)
{
// error looking up rate, maybe apply a default?
}
else
{
$row = mysql_fetch_assoc($rs);
$taxrate = $row['rate'];
}
}
$amount = $amount * (1 + $taxrate / 100.0);