UPDATE command syntax - php

Everything here is working except the UPDATE command... The INSERT works fine but alas, I'm stuck.
$queryLastDateArray = "SELECT date FROM schedule ORDER BY ID DESC LIMIT 1";
$lastDateArray = mysql_query($queryLastDateArray);
while($row = mysql_fetch_array($lastDateArray))
{
$lastDate = $row['date'];
}
$lastDatePlusOne = date("Y-m-d", strtotime("+1 day", strtotime($lastDate)));
$newDatesArray = GetDays($lastDatePlusOne, $_POST[date]);
$i = 0;
while($i < count($newDatesArray))
{
if ((date('D', strtotime($newDatesArray[$i]))) == 'Fri')
{
$insDate = "INSERT INTO schedule (date) VALUES ('$newDatesArray[$i]')";
$result = mysql_query($insDate);
$insEmp = "UPDATE schedule SET schedule.jakes = schedule_default.jakes FROM schedule, schedule_default WHERE schedule.date = '$newDatesArray[$i]' AND schedule_default.ID = '5'";
$result2 = mysql_query($insEmp);
}
$i++;
}

Try writing the update like this:
"UPDATE schedule SET schedule.jakes = (SELECT schedule_default.jakes FROM schedule_default WHERE schedule.date = '$newDatesArray[$i]' AND schedule_default.ID = '5')";

Multiple table UPDATE syntax is:
UPDATE schedule, schedule_default
SET schedule.jakes = schedule_default.jakes
WHERE schedule.date = '$newDatesArray[$i]'
AND schedule_default.ID = '5'

Related

When I insert data using PHP it insert more than 10 same data in my table?

I'm trying to create a visitor counter, when user visit the page it will record the time and the number of visitor. But when I refresh the page, my database will be like this:
The code that I do is:
if (empty($counter)){
$counter = 1;
$total = 1;
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$date1 = strtotime("now");
$date2 = strtotime("tomorrow");
echo date("Y-m-d H:i:s", $date1);
echo "<br>";
echo date("Y-m-d H:i:s", $date2);
if ($date1 < $date2){
$plusCounter = $counter + 1;
$plusTotal = $total + 1;
$nextTime = date('Y-m-d H:i:s');
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
$result2 = mysqli_query($con, $sql2);
}
I was expecting that it will record the time of the user visit by every row.
This line of code is overwriting every row in the table with the current counter update:
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
you should instead insert a new row for each new visitor.
Also, this will always be true:
if ($date1 < $date2)
so you can remove the if statement.
You can do something like this:
//first fetch the last values from the database
$sql0 = "SELECT counter, totalHumanCount FROM humancount ORDER BY time DESC LIMIT 1";
$result = mysqli_query($con, $sql0);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$counter = $row['counter'] + 1;
$total = $row['totalHumanCount'] + 1;
} else {
$counter = 1;
$total = 1;
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
Use Where condition in UPDATE query. as per your query every time it will update all rows in table 'humancount'. so add UserID column for unique row and then update row for selected user.
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal' WHERE userID = ?";

How to update table using sequence in variable for each record one by one php

I have all records in sequence from 1 onwards for each record displayed but wish to update each one with that sequence in a field within the table.
Any help?
if(isset($_POST['setorder']))
{
$i = 1;
//$today = date('Y-m-d', strtotime('-1 day'));
$routesql = $mysqli->query("SELECT * FROM routes WHERE status = 1");
while ($routerows = $routesql->fetch_array())
{
$rname = $routerows['routename'];
$routejobs = $mysqli->query("select tracking.*, district.* from tracking left join district on tracking.street = district.street
where tracking.date = '$today' AND tracking.status = 2 and route = '$rname' order by district.sortorder asc");
while ($routejrows = $routejobs->fetch_array())
{
echo $i.' - '.$routejrows['joborder'].' - '.$routejrows['addressto'];
echo '<br/>';
$i++;
}
}
}

Not able to pass array data

I am trying to create an array in $data, but it is not happening. I am using this code to make a day wise sale chart.
$data = array();
for ($i = 0; $i <= 10; $i++) {
$billdate = date('d-m-Y', strtotime("-$i day"));
$sqlQuery = "select sum(amount),bill_date from msr_bills WHERE bill_date='$billdate' ";
$result = mysqli_query($con, $sqlQuery);
$fetchamount = mysqli_fetch_row($result);
$sum = $fetchamount[0];
$data = new \stdClass();
$data->bill_date = $billdate;
$data->amount = $sum;
$report_JSON = json_encode($data);
echo $report_JSON.",";
}
You can merge your loop into one query, and then iterate over the results instead:
$data = array();
$billdate = date('Y-m-d', strtotime('-10 day'));
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE bill_date >= '$billdate'
GROUP BY bill_date";
$result = mysqli_query($sqlQuery);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = (object)$row;
}
$report_JSON = json_encode($data);
echo $report_JSON;
}
Note that your date format is not compatible with MySQL dates, which are stored in Y-m-d format, and I have changed that in the code. If your bill_date column is actually a text field stored in d-m-Y format, you will need to convert it in the query like so:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= '$billdate'
GROUP BY bill_date";
Note also that you can in fact do the computation of $billdate internal to your SQL query using date arithmetic:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date";
And if you are running MySQL 8.0+, you can do the entire operation in MySQL:
$sqlQuery = "SELECT JSON_ARRAYAGG(data) AS data
FROM (SELECT JSON_OBJECT('bill_date', bill_date, 'amount', SUM(amount)) AS data
FROM msr_bills
WHERE bill_date >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date) d";
$result = mysqli_query($sqlQuery);
if ($result) {
$row = mysqli_fetch_assoc($result);
$report_JSON = $row['data'];
echo $report_JSON;
}
Demo on dbfiddle
Put your echo outside loop. remove code $report_JSON = json_encode($data);
$respnseArr = array();
{
.
.
.
$respnseArr[] = $data;
}
echo json_encode($respnseArr);

PHP chart diagram to display skipped entry

I'm trying to create a graph like this http://jsfiddle.net/9mmrbjt7/1/
I have a script created that will add the data to the graph. The date and the value is stored in db and it works just fine.
The php script counts the number of dates and uses it as a value and assign it to the date.
The problem is if someone miss one day it skips the value which I understand.
So how can I assign value zero to skipped day?
2014-07-23
2014-07-23 = 2,
2014-07-24 -> wasn't submitted so the 0 should be added to the graph with the date.
2014-07-25
2014-07-25
2014-07-25= 3,
php script
$user_curr_id = $_SESSION['user_id'];
$sql = mysqli_query($con,"SELECT * FROM rosary WHERE user_ids = $user_curr_id ORDER BY datum ASC");
$array1 = array();
while($row = mysqli_fetch_array($sql)){
$array1[] = '"' . $row['datum'] . '"';
}
$tags = implode(', ', array_unique(array_map('trim',explode(',',implode(',',$array1)))));
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) cnt
FROM rosary
WHERE user_ids = $user_curr_id
GROUP BY datum;");
$result = array();
while ($row = mysqli_fetch_array($sql)) {
$result[] = $row['cnt']; // add the content of field cnt
}
in js script
labels : ["Start",<?php echo $tags; ?>] -> list the dates from db
data : [0,<?php echo implode(',', $result); ?>]-> list values from db
php:
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) as cnt
FROM rosary
GROUP BY datum
ORDER BY datum ASC;");
$result = array();
$start = null;
$end = null;
while ($row = mysqli_fetch_array($sql)) {
$result['"'.$row['datum'].'"'] = $row['cnt'];
if(is_null($start)) $start = $row['datum'];
$end = $row['datum'];
}
$res_array = array();
if(!is_null($start)){
$i = strtotime($start);
while($i <= strtotime($end)){
$res_array['"'.date('Y-m-d',$i).'"'] = 0;
$i = strtotime("+1 day",$i);
}
}
foreach($result as $date => $val){
$res_array[$date] = $val;
}
in js script
labels : ["Start",<?php echo implode(',',array_keys($res_array)) ?>],
data : [0,<?php echo implode(',', array_values($res_array)); ?>],

PHP Optimizing a check

I'm trying to optimize this check I have. I need to check table called lines and see if any row has matching Earned and Maxearned values (only rows with Position 1,2,3,4). If they do, I need to grab Earned from that row, write it in a different table called bank and remove that row from table called lines. This is what I have:
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
foreach ($users as $user)
{
$sql6 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
$result4 = mysql_query($sql6);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
}
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql4 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('$user','$earned','$method','$today','$type','$status')";
$sql5 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
}
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
}
I'm trying to avoid having to run a different query ($sql6 and the while after that) to grab the value of Earned column. Is there a way to do this? I've tried everything and this is pretty much the best I came up with.
You can do something like this:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
$users_to_compare = "(" . rtrim(implode(",", $users),',') . ")";
$sql4 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result4 = mysql_query($sql4);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql5 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('{$row4['User']}','$earned','$method','$today','$type','$status')";
$result5 = mysql_query($sql5);
}
$sql6 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result6 = mysql_query($sql6);
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
$result7 = mysql_query($sql7);
if ($result5 && $result5 && $result7) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
}
Going one step further you can also use Batch INSERT for you insert queries
Note: Dont forget that mysql_* versions are depreceated you should use mysqli_*

Categories