I have a table named resources with the following columns:
ress1
ress2
prod1
prod2
I've tried the code indicated in the following links, but I'm still stuck...
How to find sum of multiple columns in a table in SQL Server 2005?
Auto update sum of rows & columns in a table
SQL How to Update SUM of column over group in same table
I want to run a script to UPDATE ress1 = ress1 + prod1 and the same with the ress2. So I want to update into a column the sum of the column itself and the corresponding column, doing that for every rows from the table.
Here is some code that seems easy for me, but not working...
$sql = "SELECT * FROM ro_map";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)){
$new_a = $row['a'] + $row['c'];
$new_b = $row['b'] + $row['d'];
"UPDATE ro_map SET a = '$new_a',b = '$new_b'";
}
Ah...really sorry, guys :D I use mysql (with wampp server and HeidiSQL). And running this code don t give me any error ( if($conn->$sql == TRUE) will give me TRUE...
SOLVED! Cool, thanks all, I've learned something :)
I think you're over-complicating it. If I understand you correctly, you can just do this in one transaction:
Update resources
Set ress1 = ress1 + prod1,
ress2 = ress2 + prod2
Related
I have a database where I want to read a table row by row and then for each row I want to update a cell. I have written the below code but is there a better way of doing this ? Better way I mean it takes less time than my code.
Here is my code :
$List = 'some text...';
$SQL = "SELECT * FROM TABLE";
$res = mysqli_query($database, $SQL);
while($row = mysqli_fetch_assoc($res)){
if(strpos($List,$row['name']) !== false){
mysqli_query($database, "UPDATE TABLE SET `yes`=1 WHERE name='".$row['name']."'");
}else{
mysqli_query($database, "UPDATE TA SET `yes`=0 WHERE name='".$row['name']."'");
}
}
That approach is not the best one, the idea of SQL is to manage and be able to do that in a more efficient way. Instead of iterating each row and executing total rows +1 queries you can do only 2 queries and update the information.
for Example:
-- Update all to 0
UPDATE TABLE SET `yes`=0 ;
-- Update the one on the list to 1
UPDATE TABLE SET `yes`=1 WHERE name in ('value1','value2','value3');
This approach could save you a lot of execution time and be more efficient event on very large datasets.
i have 2 solution here
Solution 1 :
Copy the table and perform the update and rename the orginal table and also rename copy 1 table to original 1
table_1 copy to table_2
perform the operation on table_2
then rename table_1 to bkp_table_1
then rename table_2 to table_1
Solution 2
with the user select insert the data in new table which you what to update.
I'm kinda of stuck here for a while maybe you guys can help me out? I want to highlight a table of database record, coming from one table, and check if the id out of this table also exists in the 2nd table.
Let me be more specific:
Table 1: Projects (projectid pk)
Table 2: Reservations (projectid fk)
A simple sample code, to keep this simple:
while( $record=mysql_fetch_array($result) )
{
$projectid=$record['projectid'];
echo "<tr>". $projectid ."</tr>;
}
So this is working great, I get all table rows with each projectid which exists in my DB, but how to pass this $projectid variables to another query which checks if this exists in the other table, and if it exists, echo out something different? Here's my code which probably doesn't make much sense, but at least the logic is there... I hope?:
while( $record=mysql_fetch_array($result) )
{
$projectid=$record['projectid'];
$hasreservationquery = ("
SELECT *
FROM reservelist rl
INNER JOIN project p on rl.projectid = p.projectid
WHERE rl.projectid = $projectid
");
$hasreservationqueryresult = mysql_query($hasreservationquery) or die(mysql_error());
if ($hasreservationqueryresult > 1)
{
echo "<tr id='hasreservation'>";
}
else
{
echo "<tr>";
}
echo "". $projectid ."";
}
Unfortunately this returns all tables highlighted, not just the one that really has a reservation in it. What am I doing wrong??
Thanks in advance.
You don't ever appear to be checking the row count. you need to change your if statement:
if (mysql_num_rows($hasreservationqueryresult) > 0)
This will now check if 1 or more results are returned (change it to be > x if you want x + 1 results returned before you highlight).
mysql_query doesn't return the amount of affected rows.
I think something like
if($hasreservationqueryresult && mysql_num_rows($hasreservationqueryresult) > 0)
Except for that I'd definitely arrange your code a bit better and rethink your variable names :)
How can I make a limit of showing the results? I need to limit it for 100 views.
In DB I have:
ID|NAME|PAGE|COUNT|DATE
In count I want to count untill 100 and then stop showing that ID. I could do it with count < 100. And then update the specific ID. I could get records with less than 100 views, but I couldn't manage to update count on the specific ID.
Row is showed with:
php code:
foreach($bannerGroups[0] as $ban) {
echo '<li class="right1">'.$ban->html().'</li>';
}
But I just don't know where to put the update in there. I tried, but all I got was to update only one ID. But it shows 4 on one page and randomizes them on refresh. So I don't know what to do.
Also I would like to say I am only learning php. Sorry for all the mess.
Code at http://pastebin.com/A9hJTPLE
If I understand correctly, you want to show all banners that have been previously-displayed less than 100 times?
If that's right, you can just add that to your WHERE clause:
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' WHERE `COUNT` < 100");
To update them all, you can either run a query while displaying each individual banner, or "record" the id of each and run a single query at the end, like:
$ids = array();
foreach($bannerGroups[0] as $ban) {
$ids[] = $ban['ID']; // record the ID; don't know how Banner
// class works, assuming uses indexes; maybe ID() method?
echo '<li class="right1">'.$ban->html().'</li>';
}
...
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
UPDATE:
Based off of a comment, your Banner class doesn't have a method to retrieve the individual banner's ID. In this case, you can record the ID values when you're building your banners array:
$ids = array();
while($row=mysql_fetch_assoc($bannerResult)) {
$banners[] = new Banner($row);
$ids[] = $row['ID']; // record the ID
}
// update the `count` on each record:
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
sorry, but I got your question wrong...
first you have to insert a new sql-column like "viewcount" to the db...
on every read, you have to increment the value in viewcount...
for that behaviour (because, mysql does not allow sub-selects on update-clause on the same table), you have to fetch the results from db, as you do that, and pass all the primary-keys of the records to an array...
after the view-logic you have to fire up a query like:
UPDATE foo SET viewcount = viewcount + 1 WHERE id IN (1,2,3,4,5,6...,100);
where the IN-clause can be easily generated using your primary-keys-array with "implode(',', $arr);"
hope this helps.
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' AND `count`<100");
#newfurniturey figured it out. in each foreach($banneruGroups added: $ids = $ban->getValue('id'); and then mysql_query("UPDATE dataa SET COUNT = COUNT + 1 WHERE id = '$ids'"); but is there any way to update them by adding query only once? And if the id is showed already 100 times i get Warning: Invalid argument supplied for foreach() in. Any idea how to fix it? I have 4 ids in DB . If one of them already have 100 views (count) then i get error!
Try to limit your data source for 100 items.
It's like OFFSET x LIMIT 100 in MySQL/PostgreSQL query or TOP 100 in MSSQL.
I try to build a variable that integrates some other variable.
one of that will be the number of an auto-increment-field where later on an insert-query will happens.
I tried to use:
$get_num = $db/*=>mysqli*/->query("SELECT COUNT (*) auto_increment_column FROM table1");
$num = $query->fetch_assoc($get_num);
$end = $num + 1;
I don't have any update/insert query before that so I can't use
$end = $db->insert_id;
that's why i thought i can just count the numbers of the auto_increment rows and have my last variable that is necessary to build my new variable.
for a reason this wonT count the entries and outputs 0. i dont understand why this happens.
i really would appreciate if there is someone who could tell me what am i doing wrong. thanks a lot.
UPDATE
For everyone who likes to know about what's the goal:
I like to create a specific name or id for a file that later on will be created by the input of the fields from the insert query. I like to have an unique key. this key consists of an user_id and a timestamp. at the end of this generated variable it should be placed the auto_increment nr. of the query that will be placed in the table. so the problem is, that I create an variable before the insert query happens so that this variable will be part of the insert query like:
$get_num = $db->query("SELECT COUNT (*) FROM tableA");
$num = $query->fetch_assoc();
$end = $num + 1;
$file_id = $id .".". time() .".". $end;
$insert = $db->query("INSERT INTO tableA ( file_id, a, b, c) VALUES('".$file_id."','".$a."','".$b."','".c."')");{
hope now, it will be clear what I like to approach.
If you need an auto-incrementing column in MySQL then you should use AUTO_INCREMENT. It implements it all for you and avoids race conditions. The manual way you are trying to implement it has a couple of flaws, namely
If two scripts are trying to insert concurrently they might both get the same COUNT (say 10) and hence both try to insert with ID 11. One will then fail (or else you will have duplicates!)
If you add 10 items but then delete item 1, the COUNT will return 9 but id 10 will already exist.
try
SELECT COUNT(*) FROM table1
I'm trying to use the following query syntax from a php file:
$sql = "UPDATE properties SET properties.ht_hs = 3.5 WHERE properties.oil_data_id = acea.oil_data_id AND (acea.ACEA_A3 = 1 OR acea.ACEA_B3 = 1 OR acea.ACEA_B4 = 1) AND properties.ht_hs < 3.5";
$result = mysql_query($sql) or die(mysql_error());
However, It's not doing what I want. I have two tables in my database, and I need to change the value of some of the records for one column within one of the tables (the ht_hs column/field within the properties table). However,the criteria for when to change that field is dependent upon both tables.
Each motor oil in the database has an id, which is listed in the "oil_data_id" column of each table.
I'm trying to find oils that meet the ACEA A3 or B3 or B4 spec (ie, they have a "1" in that column of the acea table) which also have a value of less than 3.5 in the ht_hs column of the properties table.
If they do, I want to update the value to 3.5.
How can I restructure my query so that it works?
I think you're looking for something like this:
UPDATE properties
SET properties.ht_hs = 3.5
WHERE properties.oil_data_id in
(select acea.oil_data_id
from acea
where (acea.ACEA_A3 = 1 OR acea.ACEA_B3 = 1 OR acea.ACEA_B4 = 1))
AND properties.ht_hs < 3.5;
You would need to include table acea in the JOIN like :-
UPDATE properties, acea
SET ...;
See the documentation
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;