PHP MySQL Update to 0 at End of foreach() - php

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

Related

Stopping a PHP loop when updating MySQL database

I'm creating a basic main menu for a stock market simulator where the price of a company will be updated periodically. For testing purposes, I need to make a loop to display the price of a share on the website five times (with the website automatically updating without refreshing) and to update the database at the same time.
I have successfully wrote some code which will both update the database with the current share price and will also update the website as well. However, when I have tried to include a loop I have come to a problem. I have included a loop to iterate five times but the problem that I am having is that the code continues to iterate even after five tries.
PHP:
<?php
$conn = mysqli_connect("localhost", "root", "", "prices");
if ($conn->connect_error)
{
die("Connection error: ". $conn->connect_error);
}
$result = $conn->query("SELECT `price` FROM `priceTable` WHERE `company` = 'Bawden'");
$x = 0;
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
echo $row['price'];
echo '<br><br>';
echo $x;
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}
}
}
?>
The above code will be displayed in a separate document with Javascript code and I can post this if required in the original post however I originally chose not to as I believe this is a PHP only problem. I have chosen to display $x to see if the value will increment. However, when running, the value of $x will stay at 0.
My expected result is that, on the website, there will only be five different updates and in the database, the database will only be updated five times.
However, my actual result is that the website and database are both continuously being updated, not stopping after five times.
I'm trying to limit the update command to only 5 updates yes. At the
moment, for testing purposes, there is only one company in my database
with one price only. So I'm updating this one company's price five
times
If you need to do the update 5 times for each row returned from the database, change your if statement to a for loop. Change this :-
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}
to this
for ($x = 0, $x < 5, $x++)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
}
This will repeat the process exactly 5 times and not rely on a separate counter (remove the other references to $x). Not sure why you would want to update the same record 5 times with different random values though.
The else will break the first loop, the second one will stop on the first while loop.
while ($row = $result->fetch_assoc())
{
echo $row['price'];
echo '<br><br>';
echo $x;
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}else{
break;
}
break;
}
What makes you think the loop should stop after 5 iterations?
You need to add the condition $x<5 in the while ($row = $result->fetch_assoc())
Edit following your comment
What you initially wrote is something like loop hundreds of times if need be and do something in the first 5 occurrences (starting loop 6, keep looping but do nothing).
Now for the 2nd half of your comment, I'm not sure what you mean.
What I see in your code is:
Select all prices for company = 'Bawden'
Update all the prices for company = 'Bawden' 5 times (loop) with a random value, the same one, on all the records.
Not enough information to tell for sure but I don't think it makes sense: on one hand, you except to have several records under company = 'Bawden (= reason why you created a loop), on the other hand, your update feels like it is written under the assumption there would be 1 record only...
Are you missing something like a price date from your table? What is the primary key of priceTable?
Try to post more technical details about your table (definition, sample of data) or it will be complicated to help further.

Updating a 4th table using 3 different tables

I've got 3 different tables and I want to update the 4th table with some specific column from each of the 3 tables, they all have a common key. I can do this from the phpmyadmin, but I want to do it using a php script.
This is what I tried but it didn't work
if (isset($_GET)) {
$update = '';
$count="SELECT * FROM test2 ";
foreach ($connect->query($count) as $row) {
$term_total1=$row['english'];
$sql = "UPDATE total set `f_test` ='$term_total1' ";
foreach ($connect->query($count) as $row) {
echo "success<br>" . $term_total1;
}
}
}else{
echo "try another method" . mysqli_error($connect);
}
Have been trying for days now.
Repeated the same code for the other two tables but it won't work.
Is it possible to do it in a single query? If Yes, then how
I'm pretty sure your method of using foreach to loop the result set is incorrect. In your updated code you've also not got a unique identifier so your code is just going to mass update your table. Here's your current code fixed up so hopefully you can understand how to loop the dataset from mysqli
$count="SELECT * FROM test2";
if($res = $connect->query($count)){
while($row = $res->fetch_assoc()){
$term_total1 = $row['english'];
$sql = "UPDATE total set `f_test` = '{$term_total1}'";
if($res2 =$connect->query($sql)){
echo "success<br>" . $term_total1;
}else{
print_r($connect->error());
}
}
}else{
print_r($connect->error());
}

Datetime conversion php [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 5 years ago.
<?php
//Connection Variable to establish connection to the database parameters and localhost, user, password
$connection = mysql_connect("localhost","root","") or die(mysql_error());
//selects the database called trial and uses the connection details
mysql_select_db("bb",$connection);
//Checks to see if a file has been submitted
if(isset($_POST['submit'])){
// if submitted
/*Propriety Information if user needs to be added*/
/*
$gym=mysql_real_escape_string($_POST['Gym']);
$access=mysql_real_escape_string($_POST['accessID']);
$Chal=mysql_real_escape_string($_POST['Chal']);
*/
//Files path with the added extention of a random name at the end.
$file=$_FILES['file']['tmp_name'];
echo $file;
//Force Open the file in read state
$handle = fopen($file, "r");
fgetcsv($handle,1000,",");
fgetcsv($handle,1000,",");
fgetcsv($handle,1000,",");
//initates a check for the csv
if(($filedata =fgetcsv($handle,1000,",")) !== false )
{
//While loop with the ammount of data in the csv, fgetcsv grabs all the data that is open. Each cell is restricted to 1000 charachters, then seperated by a comma
while(($filedata =fgetcsv($handle,1000,",")) !== false )
{
//Cycles through the row and each cell is then put into an array
// Multidimensional array tutorial E- Excel, DBS - Database
$userIDP2 = $filedata[0]; // E 1. User ID , DBS - userid
$height = $filedata[1]; // E 2. Height, DBS - height
$genderIdentifier = $filedata[2]; // E 3. gender, DBS - gender (UserTable)
$testDateChange = $filedata[4]; // E 5. Test Date / Time, DBS - testDate
$weight = $filedata[5]; // E 6. Weight, DBS - weight
$bodyFatMass = $filedata[23]; // E 24. BFM (Body Fat Mass), DBS - bodyFatMass
$SkeletalMuscle = $filedata[32]; // E 33. SMM (Skeletal Muscle Mass), DBS - SkeletalMuscle
$bodyFatP = $filedata[38]; // E 39. BFP (Body Fat Percentage), DBS - bodyFatP
$lean_RA = $filedata[62]; // E 63. LM of Right Arm, DBS - lean_RA
$lean_LA = $filedata[64]; // E 65. LM of Left Arm, DBS - lean_LA
$lean_Trun = $filedata[66]; // E 67. LM of Trunk (Abdomin), DBS - Lean_Trun
$lean_RL = $filedata[68]; // E 69. LM of Right Leg, DBS - lean_RL
$lean_LL = $filedata[70]; // E 71. LM of Left Leg, DBS - lean_LL
$wc_TargetW = $filedata[73]; // E 74 Target Weight, DBS - wc_TargetW
$BMR = $filedata[77]; // E 78.BMR, DBS - BMR
$visceralFat1 = $filedata[81]; // E 82.Visceral Fat Level, DBS - visceralFat
/*Replaces specific characters strings for the associated data */
$userIDR2 = str_replace("<","",$userIDP2);
$userID = str_replace(">","",$userIDR2);
$visceralFat = str_replace("level","",$visceralFat1);
$HyphenDate = str_replace('.','-' , $testDateChange);
$date = DateTime::createFromFormat('d-m-Y H:i:s', $HyphenDate);
echo $date->format('Y-m-d h:i:s');
echo $date;
//Variable Declare
$Gender ='';
// To check if Male or Female
if($genderIdentifier == 'M' || $genderIdentifier == 'm'){
$Gender = "Male";
}else if($genderIdentifier == 'F' || $gender == 'f'){
$gender = "Female";
}else{
$gender = "intermittent";
}
//Change the Date Time format
echo"<br/>";
//sql query
$sqlBodyCompositionStart="
INSERT INTO `bodycomp`
(
`userid`,
`height` ,
`testDate` ,
`weight`,
`bodyFatMass`,
`SkeletalMuscle`,
`bodyfatP`,
`lean_RA`,
`lean_LA`,
`lean_Trun`,
`lean_RL`,
`lean_LL`,
`wc_TargetW`,
`BMR`,
`visceralFat`
)VALUES (
'".$userID."',
'".$height."',
'".$testDate."',
'".$weight."',
'".$bodyFatMass."',
'".$SkeletalMuscle."',
'".$bodyFatP."',
'".$lean_RA."',
'".$lean_LA."',
'".$lean_Trun."',
'".$lean_RL."',
'".$lean_LL."',
'".$wc_TargetW."',
'".$BMR."',
'".$visceralFat."'
);";
$sqlBodyCompositionEnd="
INSERT INTO `bodycomp`
(
`height_1` ,
`testDate_1` ,
`weight_1`,
`bodyFatMass_1`,
`SkeletalMuscle_1`,
`bodyfatP_1`,
`lean_RA_1`,
`lean_LA_1`,
`lean_Trun_1`,
`lean_RL_1`,
`lean_LL_1`,
`wc_TargetW_1`,
`BMR_1`,
`visceralFat_1`
)VALUES (
'".$height."',
'".$testDate."',
'".$weight."',
'".$bodyFatMass."',
'".$SkeletalMuscle."',
'".$bodyFatP."',
'".$lean_RA."',
'".$lean_LA."',
'".$lean_Trun."',
'".$lean_RL."',
'".$lean_LL."',
'".$wc_TargetW."',
'".$BMR."',
'".$visceralFat."'
);";
// Check for user name
$userNameSQL ="SELECT *
FROM user
WHERE username ='".$userID."'";
$userCheck = mysql_query($usernameSQL) or die(mysql_error());
if(mysql_num_rows($userCheck)==1) //If rows are return
{
$sqlBodyCompositionEnd;
$uploadData = mysql_query($sqlBodyCompositionEnd) or die(mysql_error());
if($uploadData)
{
echo"Data has uploaded";
}
else
{
echo "Data has not been uploaded";
}
}
else
{
// Adds a new User
// SQL Query
$sql =" INSERT INTO `user`(`UserName`,`gender`,)
VALUES
('".$userID."','".$gender."')";
$userID = mysql_insert_id();
$resultNA = mysql_query($sql) or die(mysql_error()); //run your SQL query
if($resultNA)
{
echo"A new User has been added";
// Once a new user has been added, it then tried to add data
$sqlBodyComposition;
$uploadData = mysql_query($sqlBodyCompositionStart) or die(mysql_error());
if($uploadData)
{
echo"Data has uploaded";
}
else
{
echo "Data has not been uploaded";
}
}
else
{
echo "There is no user";
}
}
}
}
}
/*
OBJECTIVE FOR FILE:
This file grabs the file that was posted and cycles the data in the csv; to avoid duplication of pages, the bottom half the code should check to see if an existing
user is there; if it is, it uses the same code that would be used if the listed memeber wasn't in the database. This means that $sqlBodyComposition should be a
universal variable which will limit duplication.
We need to create a function that checks for a user, returns true and inserts the
$sqlBodyComposition query. If a user doesn't exist, we need to remove "<" and ">"
in the ID insert a new user. When the user is inserted, it is to then insert that
data about the body composition to the user.
It is to return to a page and determine whether it succeeded or not.
*/
?>
So I have a date in a csv file and I need php to convert it to a more appropriate format which is Y-m-d h:i:s
the format I need to convert
10.05.2017 18:31:07
this is stored as a variable/string
I've used str_replace('.','-',$date);
and I now need to reverse the Year and Date to achieve the submit-able format
is it possible to grab some help with this?
It would probably be easier to create a date object rather than rearranging the string.
This code should work for what you want to do:
<?php
//Raw Input as string
$raw = "10.05.2017 18:31:07";
//Create date object
$date = DateTime::createFromFormat('d.m.Y H:i:s', $raw);
//Print out date object
echo $date->format('Y-m-d h:i:s');
?>
The documentation for createFromFormat can be found here: http://php.net/manual/en/datetime.createfromformat.php
Conor.
Solved this by removing the decimal but also spotted a misuse of the object.

Improve performance when copying records from table to another one

Hi buddies :) I was required to create a php code to handle some workers' data stored in DB. I got the desired result but it takes seconds and seconds (seconds and seconds! >.<) to finish, so I'm afraid I'm not doing something in a right way :(
The workers' data is stored in a mysql table (table1), something like this:
I'm given a pair of dates: initial_date (a) and final_date (b), so my goal is to copy the given workers' data in a new table (table2), day by day from a to b. The expected table should be as shown below (this table will be used later as a basis for further operations, which is not part of the question)
It's a requirement to overwrite any existing data between a and b dates, and 'jump' weekends and holidays.
To get my goal, I'm coding this (let's assume that the connection and all that is done and the checkworkingday function is given):
$initialdate = '2016-10-10';
$finaldate = '2016-10-12';
$x = $initialdate;
do {
if (checkworkingday($x) == true) {
$query = mysqli_query($connection,"SELECT name,task FROM table1");
while($row = mysqli_fetch_array($query)) {
$task = $row['task'];
$worker = $row['name'];
$query2 = mysqli_query($connection,"SELECT task FROM table2 WHERE name = '$worker' AND date = '$x'");
$row2 = mysqli_fetch_array($query2);
$existingtask = $row2['task'];
if (!isset($existingtask)) {
mysqli_query($connection,"INSERT INTO table2 (date,name,task) VALUES('".$x."','".$worker."','".$task."')");
} else {
mysqli_query($connection,"UPDATE table2 SET task = '".$task."' WHERE date = '".$x."' AND worker = '".$name."'");
}
}
}
$x = date('Y-m-d', strtotime($x . "+1 day"));
} while ($x <= $finaldate);
Just for 3 days as shown in the example, it takes a long to end; and for several weeks or months it takes very, very long (even max execution time is exceeded depending on dates range!).
I'm a newbie and I know the code is quite 'rustic', but I've revised and checked the code and info out there without getting a better performance. What am I doing wrong? Thanks :)
Instead of looping through the enitre data, try INSERT.. SELECT :
INSERT INTO table2 (date,name,task)
SELECT date,name,task
FROM Table1
WHERE < >;

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?

Categories