Updating database with certain date - php

For my internship i'm almost done with a program though i need to make it so i can update my database. The problem here is that i can not update it using the date selected by the user due to the timestamp in the database. is there any way i can either add a time behind my variable or make it so i can have my update query ignore the time part?
Here is the current code for my program's update query.
if(isset($_POST['Pasaan']))
{
$Voor = $_POST['Voor0900'];
$Na = $_POST['Na0900'];
$Datum = $_POST['Datum'];
$Datum = DateTime::createFromFormat("d/m/Y" , $Datum);
$Datum->format('Y-m-d');
$Datum
$sql = "UPDATE `firsthousing` SET
`Voor0900` = '$Voor',
`Na0900` = '$Na'
WHERE Datum = '$Datum'";
if ($db->query($sql) === TRUE)
{
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $db->error;
}
}
With kind regards,
Daynie

you can use DATE() which will only return date part
$sql = "UPDATE `firsthousing` SET
`Voor0900` = '$Voor',
`Na0900` = '$Na'
WHERE DATE(Datum) = '$Datum'";

Related

PHP MySQL Update to 0 at End of foreach()

I'm trying to update multiple cells in a MySQL database based on a previous update date. I am having an issue with unchanged, trailing cells updating to 0.
Database table looks like this (default = 0 for Day#; N = last update date):
id--Run--Day1--Day2--Day3--Day4
1----N------1-----2-----3----4
The code below does the following:
Retrieves the database entry under column= Run, id=1
Subtracts that date from today's date.
Uses that difference to move database for Day1->Day4 to the left.
Example database table when the difference is 2 days:
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----3----4
My issue is that I need it to change all trailing Days to 0. So in this example, Day3 & Day4 should both be 0.
I've been trying out another foreach() statement within but can't get the logic behind it. Would someone please point me in the right direction?
$DaysColumnRange2 = range (1, 4);
foreach ($DaysColumnRange2 as $DaysColumnRangeLoop2){
$SubtractedDaysColumns2 = $DaysColumnRangeLoop2 - $diff2format;
$MoveToNewDay2 = ${$Day.$SubtractedDaysColumns2};
$OriginalOldDay = $diff2format + $SubtractedDaysColumns2;
$sql2 = "UPDATE users SET Day$MoveToNewDay2='$OriginalOldDay' WHERE id='$id'";
if ($conn->query($sql2) === TRUE) {
echo "RECORDS UPDATED SUCCESFULLY";
} else {
echo "Error updating record: " . $conn->error;
}
}
I'll update this first post with my attempts as I continue to work on it.
(this is not a great way of doing it, but this is what I was able to put together since Cron jobs wasn't reliable & I haven't yet figured out how MySQL Triggers work)
**
------------------UPDATE--------------
**
This section is to clarify my question.
Let's say this is my database right now:
id--Run--Day1--Day2--Day3--Day4
1----N------1-----2-----3----4
I run the code below where $diff2format = 2:
//>Database credentials + login here
//Retrieve database entry for Run
$id = 1;
$todaysdateupdate = date("Y-m-d");
$lastupdatequeryresult = mysql_query("SELECT Run FROM users WHERE id='$id'");
$lastupdaterow = mysql_fetch_assoc($lastupdatequeryresult);
//Compare Run date to today's date.
$date3=date_create($lastupdaterow['Run']);
$date4 = date_create(date("Y-m-d"));
$diff2=date_diff($date3,$date4);
$diff2format = $diff2->format("%a");
//Day1, 2, 3, etc...
$result1 = mysql_query("SELECT Day1 FROM users WHERE id='$id'");
$row1 = mysql_fetch_assoc($result1);
//Hard coded "Day#" variables
$Day = "Day";
$Day1 = $row1['Day1'];
$Day2 = $row2['Day2'];
$Day3 = $row3['Day3'];
$Day4 = $row4['Day4']; //etc
//MY QUESTION STARTS HERE****************
$DaysColumnRange2 = range (1, 4);
foreach ($DaysColumnRange2 as $DaysColumnRangeLoop2){
$SubtractedDaysColumns2 = $DaysColumnRangeLoop2 - $diff2format;
$MoveToNewDay2 = ${$Day.$SubtractedDaysColumns2};
$OriginalOldDay = $diff2format + $SubtractedDaysColumns2;
$sql2 = "UPDATE users SET Day$MoveToNewDay2='$OriginalOldDay' WHERE id='$id'";
if ($conn->query($sql2) === TRUE) {
echo "RECORDS UPDATED SUCCESFULLY";
} else {
echo "Error updating record: " . $conn->error;
}
}
The output for the database is below. Basically it copied Day3 moved it 2 times to the left, then copied Day4 and also moved 2 times to the left. Nothing changed with Day3 or Day4.
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----3----4
But I need it to output this instead:
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----0----0

running a query inside a loop to do another loop

Ok so what i am doing is getting member id's from 1 table and looping those ID's through another table to get values to output. I had it working going through the first loop, then notice the output was all screwy, so released I needed to loop it through again, since there will could be multiple entries in the 2nd query for MemID. now I put in the 2nd loop but its not even going through, not sure where I messed up the code, but doesn't seem to output now when running it through the 2nd loop. though it did output without the loop. but that won't work due to multiple rows for each $memid.
$qry_skamembers = "SELECT * FROM ap_skamembers ORDER BY id";
$qry_skamembers = $mysqli->real_escape_string($qry_skamembers);
if($result_skamembers = $mysqli->query($qry_skamembers)){
while($row_skamembers = $result_skamembers->fetch_array()){
$AffID = $row_skamembers['AffID'];
$MemID = $row_skamembers['MemberID'];
$skacon = new mysqli(OW_DB_HOST, OW_DB_USER, OW_DB_PASSWORD, OW_DB_NAME);
if ($skacon->connect_error) {
die('Connect Error');
}
$get_data = "SELECT * FROM ow_base_billing_sale WHERE userID = $MemID AND status = 'delivered' ORDER BY id";
$get_data = $skacon->real_escape_string($get_data);
if($result_data = $skacon->query($get_data)){
while($finish = $result_data->fetch_array()){
$test = $finish['status'];
if($test == 'delivered') {
$sale_amount = $finish['price'];
$product = $finish['transactionUId'];
$products = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_earnings where product = $product"));
if(mysqli_num_rows($products) > 0) { }
else {
echo "AFF: " . $AffID . " | ";
echo "Mem: " . $MemID . " | ";
echo "PRICE: " . $sale_amount . " | ";
echo "PRODUCT: " . $product . " -- ";
include('controller/record-sale.php');
echo "inserting record";
echo "run finished <br><br>";
}
}
}
}
}
}
I am still rather new at coding, so it might look a bit sloppy, my apologies for that.
I do not know if that is ist bu try to replace:
$get_data = $skacon-->real_escape_string($get_data);
with
$get_data = $skacon->real_escape_string($get_data);
i think there is an extra -
And as we found out in comments you need to change $product to '$product'
You can do all that in one query,nevermind it will be much faster
SELECT aps.AffID,aps.MemberID,owb.price,owb.transactionUId
FROM db1.ap_skamembers aps JOIN db2.ow_base_billing_sale owb
ON aps.MemberID = owb.userID AND owb.status='delivered'
JOIN db3.ap_earnings ape
ON ape.product = owb.transactionUId
ORDER BY aps.id

mysqli pull decimal value from db

I'm trying to pull a decimal from my database, but when I try it's trying to make it an int and I don't know how to fix it because I'm stupid and I don't even deserve to be called a programmer. Can someone please help?
if (isset($_POST['Add'])) {
$Date = $_POST['Date'];
$Amount = $_POST['Amount'];
$LegalFees = 0.00;
$CheckID = $_POST['Check_ID'];
$DateAdded = date("Y/m/d", strtotime($_POST['Date']));
$result = mysqli_query($conn, "SELECT CheckID FROM checks WHERE CheckID='" . $CheckID . "'");
$CurrentPayment = mysqli_query($conn, "SELECT payments FROM checks WHERE CheckID='" . $CheckID . "'");
$TotalPayment = $Amount + $CurrentPayment;
if (mysqli_num_rows($result) > 0) {
$sqlinsert = $conn->query("INSERT INTO payments (Date,Amount,LegalFees,CheckID)Values('{$DateAdded}','{$Amount}','{$LegalFees}','{$CheckID}')");
$sqlupdate = $conn->query("UPDATE checks SET payments=" . $TotalPayment . " WHERE checkID=" . $CheckID . "");
} else {
$_SESSION["CheckIDFail"] = "Yes";
}
}
So basically it's supposed to select the payment in the db which is a decimal and store it into $CurrentPayment, but it can't because it's trying to make the decimal an int.
The rest of the code I don't really have a problem with, it works as it should. Just need to know how to make it pull a decimal correctly. I think it has to do with fetch or something? I don't know, someone please help this pathetic person?
I think the problem is trying to convert a result set (an array) to a number. PHP doesn't care whether your number is a decimal or an integer.
$Date = $_POST['Date'];
$Amount = $_POST['Amount'];
$LegalFees = 0.00;
$CheckID = $_POST['Check_ID'];
$DateAdded = date("Y/m/d", strtotime($_POST['Date']));
$result = mysqli_query($conn,
"SELECT payments FROM checks WHERE CheckID='" . $CheckID . "'")
or die(mysqli_error($conn));
$currentPayment = 0;
if (mysqli_num_rows($result) > 0){
// Get the "row" from the "result set".
// While loop is only added to illustrate the method of iterating through the results
// If you only expect one row in the output, this should still work fine
while($row = mysqli_fetch_assoc($result)){
$currentPayment += $row['payments'];
}
$TotalPayment = $Amount + $currentPayment;
mysqli_query($conn, "INSERT INTO payments (Date,Amount,LegalFees,CheckID)
values('{$DateAdded}','{$Amount}','{$LegalFees}','{$CheckID}')")
or die(mysqli_error($conn));
mysqli_query($conn, "UPDATE checks SET
payments=" . $TotalPayment . " WHERE checkID=" . $CheckID . "")
or die(mysqli_error($conn));
}
else {
// No rows returned
$_SESSION["CheckIDFail"] = "Yes";
}
A couple of things:
Maintain consistency in the type of queries within a program (in fact, even within an application) as a whole. Try not to switch back and forth between procedural (mysqli_query()) and object oriented ($conn->query) approach.
Use Prepared Queries to prevent the threat of SQL injections in your query - How to create a secure mysql prepared statement in php?
It's all right to stumble once in a while :)

Update Automatic Mysql Values php

Hello I want to update MySQL table automatic at set time like i want to update table at 5:30 i have some values to update in my database at set time automatic. in PHP
$date = date('H:i:s');
if($date == "11:26:00") // 17:30:00 is equal to 5:30 but in 24 system
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
while($row= mysqli_fetch_assoc($result1))
{
$Foo= $row['foo'];
}
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
Just lie what Ashish said you can use CRON , and if you want you maybe can use this , i did not use before , try it . This code will works once ,so you have to find away to make loop cause the time will change every sec .
Note : Check the second code .
<?php
// Database connect
$date = date('H:i:s'); // Set the time to hours and minutes and seconds format
// you can echo $date to check how it looks but it will be something like this : 07:21:48
if($date == "17:30:00") // 17:30:00 is equal to 5:30 but in 24 system
{
// You can type your code here .
}
?>
Second Code :
<?php
// Remember to connect to your database
$date1 = date_create("00:00");
$date2 = date_create("23:59");
while($date1<=$date2)
{
date_add($date1,date_interval_create_from_date_string("1 sec"));
$a = date_format($date1,"H-i-s");
if($a =='17:30:00')
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
$row= mysqli_fetch_assoc($result1)
{
$Foo= $row['foo'];
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
die;
}
else
{
// you can type anything here , you can end the process by typing die; or anything you want
}
}
?>
You can check this and see how you can loop throw date in php :
I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
This can help you understand the time and date system and how to change the format for the date in php : How to get the current date and time in PHP?

table updates empty spaces when user do not enter anything to the textbox

i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.

Categories