update multiple rows with calculated variable - php

The table_calc structure (minimized) is:
| id | value_1 | value_2 |
the number of rows is between 70 and 250 or more.
I want to update the fields in "table_calc" with values resulting from other calculations ($value_update_1 and 2, ...), values applied different to the fields in the table.
Before I used a table on the web page and from there I updated the table.
Now I want to update the values directly without having to take them in the page, as it should work.
I started to write the code below:
$stmt_update = $conn_bd->prepare('select * from table_calc');
$stmt_update->execute(array());
$result_stmt_update = $stmt_update->fetchAll();
foreach($result_stmt_update as $rrows_update) {
$cal_id = $rrows_update[id];
$cal_value_1 = $rrows_update['value_1'];
$cal_value_2 = $rrows_update['value_2'];
}
$value_update_1 = 100.25;
$value_update_2 = 150.25;
$count_id = count($cal_id);
$stmt = $conn_bd->prepare('UPDATE table_calc SET value_1 = :value_1, value_2 = :value_2 WHERE id = :id');
$i = 0;
while($i < $count_id) {
$stmt->bindParam(':value_1', '.$cal_value_1[$i].' * '.$value_update_2.');
$stmt->bindParam(':value_2', '.$cal_value_2[$i].' * '.$value_update_1.');
$stmt->bindParam(':id', $cal_id[$i]);
$stmt->execute();
$i++;
}
but it doesn't work
Can you help?

I can spot a few issues on your code:
On line 8:
$cal_id = $rrows_update[id];
^^
You need quotes there.
On line 20, you call your variable as if it were an array, but you don't set it as such on lines 9-10.
Again on line 20, you should bind the final value to the parameter, not leave it to be evaluated by MySQL.
So the corrected version would be:
$stmt_update = $conn_bd->prepare('select * from table_calc');
$stmt_update->execute(array());
$result_stmt_update = $stmt_update->fetchAll();
foreach ($result_stmt_update as $rrows_update) {
//Added array push operators. To make them arrays.
$cal_id[] = $rrows_update["id"];
$cal_value_1[] = $rrows_update['value_1'];
$cal_value_2[] = $rrows_update['value_2'];
}
$value_update_1 = 100.25;
$value_update_2 = 150.25;
$count_id = count($cal_id);
$stmt = $conn_bd->prepare('UPDATE table_calc SET value_1 = :value_1, value_2 = :value_2 WHERE id = :id');
$i = 0;
while ($i < $count_id) {
//Altered the binding so that you bind the final value.
//Also changed to bindValue.
$stmt->bindValue(':value_1', $cal_value_1[$i] * $value_update_2);
$stmt->bindValue(':value_2', $cal_value_2[$i] * $value_update_1);
$stmt->bindValue(':id', $cal_id[$i]);
$stmt->execute();
$i++;
}
Also, when making batch changes to the database, you may want to use Transactions, to make sure all changes are registered as expected.

Related

Store multiple row table into array to allow for user updates

I have struggled with this concept for a while and am hoping someone can help, please. I can query database records if all values are stored in one row. The challenge I have is when the quantity values are stored on multiple rows but with a common key (e.g. order_id). I want to store into an array and then assign each value to an on-screen variable to allow user updates so that I can update the table again.
For example, if the table looks as follows:
id line part qty
-- ---- ---- ---
1 1 63 2
1 2 104 3
1 3 54 2
1 4 50 1
I have not had success with the following where I establish the number of rows and then try to build a foreach loop to capture the data:
$sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}
If I can properly separate the values into an array and then reference them somehow, then I could do the following and get them displayed and easily update back to the database:
$var_1 = $data['63']; // part_id = 63
$var_2 = $data['104']; // part_id = 104
$var_3 = $data['54']; // part_id = 54
$var_4 = $data['50']; // part_id = 50
Change this:
$sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}
To something that makes sense like this
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
echo $row['qty'];
};
UPDATE
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$array['line_'.$row['line']] = $row;
};
UPDATE
The additional code that answers what I was looking for is as follows. Your answer was key to my understanding it all:
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$qty['line_'.$row['line']] = $row['qty'];
};
$var_54 = $qty['line_54'];
$var_63 = $qty['line_63'];

How do I get the leaderboard to grab the right data?

I am currently building a leaderboard (https://mgo.io/mgo3/leaderboard.php) and I'm having issues making it manually accept data. I want it to grab data from my MySQL database, and allow me to manually go in and enter data which it will in turn display as well. It currently grabs id, and clan names from the clans db.
How do I get it to read data I input from two new 'wins' and 'losses' columns I add in the db it already grabs data from?
Heres my code:
<?php
include_once "Log.class.php";
include_once "dbcon.php";
function getLeaders() {
global $dbh;
date_default_timezone_set('UTC');
$res = array();
$stmt = $dbh->prepare("SELECT id, name FROM clans ORDER BY id ASC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$clan_id = (int) $row['id'];
$clan_name = $row['name'];
$res[$clan_id] = array();
$res[$clan_id]['name'] = $clan_name;
$res[$clan_id]['rank'] = 0;
$res[$clan_id]['cp'] = 0;
$res[$clan_id]['win'] = 0;
$res[$clan_id]['loss'] = 0;
?>
Just add the fields to your SELECT statement and assign the retrieved values to the appropriate variables:
// Add wins & losses here:
$stmt = $dbh->prepare("SELECT id, name, wins, losses
FROM clans ORDER BY id ASC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$clan_id = (int) $row['id'];
$clan_name = $row['name'];
$res[$clan_id] = array();
$res[$clan_id]['name'] = $clan_name;
$res[$clan_id]['rank'] = 0;
$res[$clan_id]['cp'] = 0;
$res[$clan_id]['win'] = $row['wins']; // <<<< and here...
$res[$clan_id]['loss'] = $row['losses']; // <<<<

Show only the last result from mysql row

I have a table
id | field1 | field2 | ... | field[x-1] | field[x]
1 | val1 | val2 | ... | val[x-1] | val[x]
And I'm doing this search
for($i = 1; $i <= $x; $i++){
$getvalue = mysql_query("SELECT * FROM table WHERE id='1' AND field".$i." LIKE 'some_value%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$j=$i+1;
$val = $row['field'.$j.''];
}
}
Some values in the table (val[1-x]) will be the same but I need to get only the LAST value. Limit 1 doesn't seem to work.
Update.
Unfortunately as David suggested, I can't change the database. It has to be as it is. I have a text file (a settings dump from a sensor) that I insert it line by line into the db and do a check to see if there are any errors. Most check run ok but I have a few lines in that I need to choose only the last one to do the check.
I have about 10 lines like this
D?
String
R?
String
...
D?
String
R?
String
I'm interested in the last string after R?. I use explode () and each value checked that they are with in limits.
Using ORDER BY id DESC LIMIT 1:
To get last row (with highest=last=newest id), you should use this:
SELECT * FROM table ORDER BY id DESC LIMIT 1;
Your updated code (with mysqli_ extension) to get last row:
$query= mysqli_query("SELECT * FROM table ORDER BY id DESC LIMIT 1") or die (mysqli_error());
}
$lastRow = mysqli_fetch_row($query);
echo $lastRow['id']; //get the last id
Using MAX():
You also can do it using SQL MAX() function:
SELECT * FROM table WHERE id=(SELECT MAX(id) FROM table)
Managed to get it working as I need it by doing this:
for($i = 1; $i <= 250; $i++){
$getvalue = mysql_query("SELECT * FROM full_dump WHERE file_name='".$_FILES['datafile']['name']."' AND field_".$i." LIKE ' 100,%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$i_temp = $i;
}
}
if($i_temp != NULL){
$getvalue = mysql_query("SELECT * FROM full_dump WHERE file_name='".$_FILES['datafile']['name']."' AND field_".$i_temp." LIKE ' 100,%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$r = $row['field_'.$i_temp.''];
}
}

Insert SQL query results into separate PHP variables

I'm trying to make an ad system with PHP pdo. How can I get result id's of the following SQL query into my PHP variables?
SELECT id FROM ads, ( SELECT id AS sid FROM ads WHERE position="A" ORDER BY RAND( ) LIMIT 5 ) tmp WHERE ads.id = tmp.sid
I just don't know how to get those values in the variables like this:
$ad_1 = result[1]
$ad_2 = result[2]
$ad_3 = result[3]
$ad_4 = result[4]
$ad_5 = result[5]
With the help of those variables ($ad_1...5) I could display unique and random ads in different places, get correct data, and update ad clicks/views...
Best to get into the habit of using prepared statements like this:
<?php
$adIds = array();
$position = 'A'; // probably set dynamicaly
$stmt = $dbh->prepare("SELECT id FROM ads, ( SELECT id AS sid FROM ads WHERE position=? ORDER BY RAND( ) LIMIT 5 ) tmp WHERE ads.id = tmp.sid");
$stmt->bindParam(1, $position);
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$adIds[] = $row[0];
}
}
?>
$adIds is now an array containing all the ids returned from the select statement.
try this :
$begin = "ad_";
for($i = 0; $i < 6 ; $i++) {
$($begin.$i) = $result[$i];
}
(assuming you array $result is previously defined)

mysql query returns the value in the first column for all the other columns

Hi I made a query to a table below and when I tried to get the value in each column , it returns the same value from the first column for all the other columns.
To elaborate
In my database table I have the following:
owner_id = 21
pet_id = 1
name = fluffy
color = green
type = dog
sub_type = boxer
location = LA
however whenever I try to access one column, say the name column, it returns 21 which is the
value in the owner_id column corresponding to that pet_id. I am not sure why this is
happening.
$query = sprintf("SELECT * FROM `petAttributes` where pet_id ='%d'",$p_id);
$result = performQuery($query);
$owner_id = stripslashes(mysql_result($result,"owner_id"));
$pet_id = stripslashes(mysql_result($result,"pet_id"));
$name = stripslashes(mysql_result($result,"name"));
$color = stripslashes(mysql_result($result,"color"));
$type = stripslashes(mysql_result($result,"type"));
$sub_type = stripslashes(mysql_result($result,"sub_type"));
$loc = stripslashes(mysql_result($result,"location"));
Information on my environment
PHP Version 5.2.14
MYSQL version 5.0.67
I believe that if you use mysql_result you also have to specify the row index number (row 0 in your case?), before you specify the column.
$name = stripslashes(mysql_result($result, 0, "name"));
refering to http://php.net/manual/en/function.mysql-result.php mysql_result has it's parameters like this: mysql_result($result,$rownumber,$fieldname or $fieldnumber)
this should workd:
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
$owner_id = stripslashes(mysql_result($result,0,"owner_id"));
$pet_id = stripslashes(mysql_result($result,0,"pet_id"));
$name = stripslashes(mysql_result($result,0,"name"));
$color = stripslashes(mysql_result($result,0,"color"));
$type = stripslashes(mysql_result($result,0,"type"));
$sub_type = stripslashes(mysql_result($result,0,"sub_type"));
$loc = stripslashes(mysql_result($result,0,"location"));
BTW mysql_result is getting very inefficient if you take more than one row.
Then you should use mysql_fetch_row, mysql_fetch_array or mysql_fetch_assoc
Also you can;
for only first row
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
$row = mysql_fetch_array($result);
extract($row);
or all returned rows;
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
while($row = mysql_fetch_array($result))
{
foreach ($row as $value) echo $value."<br>";
}

Categories