Loop through database and update a field with a foreach loop - php

I am trying to round a decimal from a table and update another field in the same table with the new rounded value, but I just cant seem to hack it.
The rounding script works perfectly, but I am stuck trying to run the rounding script and update the database accordingly.
The table consist of over 10,000 entries, thus I request only data of a specific given date, which narrows down to about 1,200 entries at a time...
Here is my foreach loop (which works well on its own), but this is not working:
<?php
include("XXXX");
$cxn = mysqli_connect($host,$user,$password,$dbname)
or die ("Couldn't connect to server.");
$query = "SELECT `sub_hrs`, `id` FROM `attend` WHERE `date` = '$date'";
$result = mysqli_query($cxn,$query)
or die ("Couldn't execute query.");
while($row = mysqli_fetch_assoc($result))
{
extract($row);
$n = array($sub_hrs);
foreach($n as $i) {
$new[] = (fmod($i, 1) > 0.5
? sprintf("%2.f", (float) (int) $i + 0.5)
: sprintf("%2.f", (float) (int) $i)) . PHP_EOL;
$mysql_query("UPDATE `attend` SET `total_hrs` = $new WHERE `id` = $id");
}
}

You are assigning an array $new[] in below line.
$new[] = (fmod($i, 1) > 0.5
? sprintf("%2.f", (float) (int) $i + 0.5)
: sprintf("%2.f", (float) (int) $i)) . PHP_EOL;
But in query you are passing only $new variable which will not work as you will not get any value in $new variable.
$mysql_query("UPDATE `attend` SET `total_hrs` = $new WHERE `id` = $id");

Thanx for all the help guys, but I figured out that a simple query does the trick...
UPDATE `attend`
SET `total_hrs` = if((`sub_hrs` - truncate(`sub_hrs`,0)) < 0.5, truncate(`sub_hrs`,0), ((truncate(`sub_hrs`,0)) + 0.5))
WHERE `date` = '$date'

Related

How to calculate the sum of number array elements from multiple database rows using php?

I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;
Replace your code with the following:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;

can't get the logic to restart looping

I have 15 databases 1,2,3,4, ... 15
and I have the variable $i default at 1 and each time the $i count gets to 3, $i restarts the looping from 1 again until 3 and it will stop until value from database is done counting.
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
while($detail = mysql_fetch_array($detailPsycho)){
for($i = 1;$i<=3;$i++){
echo $detail['sequence']."&".$i." <br>";
}
}
and run over like this :/
1&1
1&2
1&3
2&1
2&2
2&3
You try to do a loop (for{}) in a loop (while{}) which is a complicated way of doing something trivial. This is the "while+for" result :
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
i = (int) 1;
while($detail = mysql_fetch_array($detailPsycho)) {
echo $detail['sequence']."&".$i." <br>";
$i++;
if ($i > 3) $i = 1;
}

PHP array for loop

I want to show the array value $result[] from the for loop calculation. However, it shows me nothing on the page. Is there is anything wrong in the below code?
$sql= "SELECT * FROM items where itemID =3 ";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_array($result1)){
$quantity[] = $row ['quantity'];
$month[] = $row ['month'];
}
$alpha = 0.3;
for($i = 1; $i > 12; $i++){
$result[$i] = ($quantity[$i] - $result[$i-1]) * $alpha + $result[$i-1];
}
foreach ($result as $key => $value ){
echo "$value";
}
Your for loop has an error. You have
for($i = 1; $i > 12; $i++)
but it should be
for($i = 1; $i < 12; $i++)
This is not directly the answer to your question, but there are few things that hasn't been mentioned that concern the way you query and process your data:
Your SELECT statement doesn't have specific order specified. Since order of records is not preserved you can get records out of correct order and get invalid calculations. Use ORDER BY (e.g. ORDER BY month) or make use of month values and extract exactly previous month's value from array(s) (if it is what you're doing in your code).
Your current code relies on the fact that the resultset from DB will contain (at least) 12 records. If for some reason it will produce less records your for loop will brake.
It's uncertain from the information in the question but it looks like you might need a year in your query unless the table contains records only for one year.
Now, you can calculate the whole thing on DB side with a query like this
SELECT i.month,
COALESCE((i.quantity - p.quantity) * 0.3 + p.quantity, 0) value
FROM items i LEFT JOIN items p
ON i.itemID = p.itemID
AND i.`year` = p.`year`
AND i.month = p.month + 1
WHERE i.itemID = 3
AND i.`year` = 2013
ORDER BY month
SQLFiddle
That's assuming (and I'm not sure about that) you actually need to read previous month's quantity values for your calculations and month column is of integer type
There is an obvious flaw in the logic. You try to get the $i index form $quantity. However, you can't be sure $quantity will have this index.
Supposing that itemId is not the primary key, I would do something like this:
$sql = "SELECT * FROM `items` WHERE `itemID` = 3";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_assoc($result1)){
$quantity[] = $row ['quantity'];
}
$alpha = 0.3;
$i = 1
foreach ($quantity as $elem) {
if ($i >= 12)
break;
$result[$i] = ($elem - $result[$i-1]) * $alpha + $result[$i-1];
$i++
}
foreach ($result as $value ){
echo $value;
}

Updating mySQL INT with new INT

Okay so for a basic outline I'm trying to update a column in my mySQL database dependent on the outcome of my code.
Basically it's rolling dice, if you beat the house it increases your INT by 5 if you loose to the house, it decreases by 5. This is for my own educational purposes and will not be used publicly.
The part that isn't working is the mysq_query("UPDATE") with both win and lose.
if (isset($_POST['roll'])) {
$rand = rand(1, 6);
$rand1 = rand(1, 6);
$rand2 = rand(1, 6);
$rand3 = rand(1, 6);
$score = $rand + $rand1;
$score1 = $rand2 + $rand3;
echo 'You rolled a '.$rand.' and a '.$rand1.' Totalling '.$score;?><br><?
echo 'Your opponent rolled a '.$rand2.' and a '.$rand3.' Totalling '.$score1;?><br><br><?
if ($score > $score1){
echo 'Win';
$coins = $user_data['coins'] + 5;
mysql_query("UPDATE `users` SET `coins` = '$coins' WHERE `user_id` = $user_id");
} else {
echo 'Loose';
$coins1 = $user_data['coins'] - 5;
mysql_query("UPDATE `users` SET `coins` = '$coins1' WHERE `user_id` = $user_id");
}
}
?>
<form action="playdice.php" method="POST">
<input type="submit" name="roll" value="Roll Dice.">
</form>
You dont need the ' around $coins. Those specify that the input is a CHAR, so MySQL is probably trying to insert a CHAR and refusing as it's an INT column.
You also don't appear to have defined a connection to query on.
$mysqli = new mysqli("localhost", "user", "password", "database");
...
if ($score > $score1){
echo "Win";
$coins = $user_data['coins'] + 5;
$mysqli->query("UPDATE `users` SET `coins` = $coins WHERE `user_id` = $user_id");
} else {
echo "Lose";
$coins = $user_data['coins'] - 5;
$mysqli->query("UPDATE `users` SET `coins` = $coins WHERE `user_id` = $user_id");
}
This should work. (Sorry for switching you from the deprecated mysql syntax but I honestly don't remember it, if you're learning you're better off using mysqli anyway).
Put a ' around the $user_id, it's probably a string. removing the quote tells MySQL that it is an integer.

for loop, $i equals two different values in the same loop

I have a small form that is generated from a mysqli->query and I've set each inputs name to be an array, such as name="Shift_ID[]". Then I have a for loop that is meant to UPDATE the records one at a time as it loops through. The problem I have is that the $i variable is a different value within the same loop and I don't understand why. This is my code:
if(isset($_POST['update_submit']))
{
$id = $_POST['Shift_ID'];
$name = $_POST['Shift_Name'];
$short_name = $_POST['Shift_Short_Name'];
$color = $_POST['Shift_Color'];
$shift_total_records = "5";
for($i = 0; $i <= $shift_total_records; $i++)
{
$sql = ("UPDATE shift SET Shift_ID = '$id[$i]', Shift_Name = '$name[$i]', Shift_Short_Name = '$short_name[$i]', Shift_Color = '$color[$i]' WHERE Shift_ID = '$i'");
echo "SQL: " . $sql . "<br>";
if(!$result_shift_update = $mysqli->query($sql))
{
die ('There was an error updating the shift table [' . $mysqli->error . ']');
}
}
}
The echo returns this:
SQL: UPDATE shift SET Shift_ID = '1', Shift_Name = 'Morning', Shift_Short_Name = 'AM', Shift_Color = '#FF0000' WHERE Shift_ID = '0'
I was expecting Shift_ID = '1' and WHERE Shift_ID = '1'. Can someone explain why this is happening? Also, before someone says it, I do know this is open to injection attacks and I need to use prepared statements.
*EDIT: * The reason I had it Shift_ID = '$id[$i]' and WHERE Shift_ID = '$i' was because I wanted to user to be able to change the Shift_ID field if they wanted to. The point would be to have the option to rearrange the order. The Shift_ID is the PRIMARY KEY, so they would get an error if they tried to use the same number twice, but is there a way to make this do what I want?
The first '1' is $id[$i] not $i - there is no problem evident here.
for($i = 0; $i <= $shift_total_records; $i++)
sets $i to 0, when you echo $id[$i] you will get the content in $id[0], the first id, but when you only echo $i you print 0 because you made $id = 0.
You've used a different variable in each location. Do you mean this:
$sql = ("UPDATE shift SET Shift_ID = '$id[$i]', Shift_Name = '$name[$i]', Shift_Short_Name = '$short_name[$i]', Shift_Color = '$color[$i]' WHERE Shift_ID = '$id[$i]'");
The first time you use $i you use it as follows $id[$i] the second time you just use $i....

Categories