Simple UPDATE SQL Query - php

I'm doing a work for a client but since I haven't been using PHP/MySQL for a while I forgot some simple things, hope you can help me out.
I have the following SQL table:
ID (non-null, autoincrement) | credit (int)
My query should put the whole "credit" column to 0 except for the row that has the higher ID.
So I would do:
UPDATE $table SET credit = 0 WHERE... ?
Thanks in advance for any help :)

UPDATE $table SET credit = 0 WHERE ID > $ID
Will update any rows that have and ID greater than the variable $ID
If you only want to update the row with the maximum ID then use:
UPDATE $table SET credit = 0 WHERE ID = (select max(id) from $table)
Edit: As Eggyal correctly points out MySQL doesn't like a subquery on the same table as an update - but you can get around it nicely:
UPDATE $table
SET credit = 0
WHERE
credit='$credit'
AND statid='$statid'
AND userid='$userid'
AND ID = (select ID from (SELECT MAX(ID)as ID from $table) a)
And examples from my console:
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | eeee |
+------+-------+
5 rows in set (0.00 sec)
mysql> update first set title='ffff' where id=(select max(id) from first);
ERROR 1093 (HY000): You can't specify target table 'first' for update in FROM clause
mysql> update first set title='ffff' where id=(select ID from (select max(id) as ID from first) a);
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | ffff |
+------+-------+
5 rows in set (0.00 sec)
Note: As the subquery within a subquery trick unlocks the original table, it is a good idea to run this within a transaction - if the table is unlocked from a query, it might have changed by the time it is updated - so it will be a good idea to use this type of query within a transaction.

Related

order table when making an update

I have the following table where order by priority ASC
----------------------
|priority |activity |
|---------|-----------|
| 1 |act1 |
| 2 |act2 |
| 3 |act3 |
| 4 |act4 |
| 5 |act5 |
|---------|-----------|
JSON where I make an update.
Add Method but it does not work as I wish
<?php
//update.php
include_once('../include/conexion.php');
$query = "
UPDATE ACT_schedule SET ".$_POST["name"]." = '".$_POST["value"]."'
WHERE id_schedule = '".$_POST["pk"]."'";
$result=mysqli_query($conn, $query);
if ($result) {
$query2 = "UPDATE ACT_Agenda SET prioridad = CASE
WHEN prioridad >= " . $_POST['value'] . "
THEN prioridad + 1 ELSE prioridad END
WHERE id_agenda <> '" . $_POST['pk'] . "'";
mysqli_query($conn, $query2);
echo "YES";
} ?>
What I want to do is order the priority, if I update the act5 that has priority 5 to priority 1, the priority changes and that means that the priority of the act1 must change to 2 and so on until the act4 change to priority 5.
It works well if I update the last priority. But if I update the act4 to priority 1 the ones below should not be updated but they do it by adding +1 (act5 priority 5 is 6).
Something like that I would like if I update act4 to priority 1
----------------------
|priority |activity |
|---------|-----------|
| 1 |act4 |
| 2 |act1 |
| 3 |act2 |
| 4 |act3 |
| 5 |act5 |
|---------|-----------|
I hope I explained well. Greetings.
From your code it's not 100% clear which are the appropriate $_POST variables to use in the update query so here is a pure MySQL solution. First create the demo table:
CREATE TABLE agenda (`priority` int, `activity` varchar(4));
INSERT INTO agenda (`priority`, `activity`)
VALUES (1, 'act1'), (2, 'act2'), (3, 'act3'), (4, 'act4'), (5, 'act5');
SELECT * FROM agenda ORDER BY priority;
Output:
priority activity
1 act1
2 act2
3 act3
4 act4
5 act5
To update, use the following query. I have used variables #n for the new priority and #a for the activity to modify; in your PHP code you would remove the SET statements below and replace #n and #p in the update query with the appropriate $_POST values. In this example I am shifting act4 to priority 2:
SET #a = 'act4';
SET #n = 2;
UPDATE agenda SET priority = CASE WHEN priority BETWEEN #n AND (SELECT * FROM (SELECT priority FROM agenda WHERE activity=#a) a) AND activity != #a THEN priority + 1
WHEN activity = #a THEN #n
ELSE priority
END;
Now we can look at the modified table:
SELECT * FROM agenda ORDER BY priority;
Output:
priority activity
1 act1
2 act4
3 act2
4 act3
5 act5
SQLFiddle Demo
This can be achieved all inside the database. Please see the following example proof:
First the boring part where I created your table and inserted your sample data:
mysql> CREATE TABLE priority_demo (priority SMALLINT UNSIGNED, activity VARCHAR(4));
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO priority_demo VALUES (1, 'act1');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO priority_demo VALUES (2, 'act2'), (3, 'act3'),(4, 'act4'), (5,'act5');
Query OK, 4 rows affected (0.02 sec)
mysql> SELECT * FROM priority_demo;
+----------+----------+
| priority | activity |
+----------+----------+
| 1 | act1 |
| 2 | act2 |
| 3 | act3 |
| 4 | act4 |
| 5 | act5 |
+----------+----------+
5 rows in set (0.00 sec)
Now, as an example, I'm changing the priority of act4 (currently prio 4) to new value 2. As my example is generic then I'm gonna use internal variables for both current and new priority for the specific activity, whereas ideally instead of #activity_key and #new you'd use your php variables when constructing the query:
mysql> SET #activity_key := 'act4', #new = 2; -- variables from php
Query OK, 0 rows affected (0.00 sec)
For demo purposes I'm outputting them too:
mysql> SELECT #activity_key, #new; -- variables used below
+---------------+------+
| #activity_key | #new |
+---------------+------+
| act4 | 2 |
+---------------+------+
Ok, we're ready to act now.
First the most interesting query - the UPDATE with priority changes.
As pulling the current priority out of the database is un-necessary overhead and useless round trip, I've implemented 3rd MySQL variable here, called #cur which contains the current value, so the update query below would know if and where and what to change.
We run the 2 following queries (SET #cur ... and UPDATE ...) together as one batcho. This ensures that it's not gonna change anything if already changed:
mysql> -- both in one "batch"
-> SET #cur := (SELECT priority FROM priority_demo WHERE activity=#activity_key LIMIT 1);
-> UPDATE priority_demo SET priority=CASE
-> WHEN priority >= #new AND priority < #cur THEN priority+IF(#cur<>#new, 1,0)
-> WHEN activity = #activity_key THEN #new ELSE priority END;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 5 Changed: 0 Warnings: 0
Let's see the result:
mysql> SELECT * FROM priority_demo; -- result as is
+----------+----------+
| priority | activity |
+----------+----------+
| 1 | act1 |
| 3 | act2 |
| 4 | act3 |
| 2 | act4 |
| 5 | act5 |
+----------+----------+
5 rows in set (0.00 sec)
mysql> SELECT * FROM priority_demo ORDER BY priority; -- priority ordered view
+----------+----------+
| priority | activity |
+----------+----------+
| 1 | act1 |
| 2 | act4 |
| 3 | act2 |
| 4 | act3 |
| 5 | act5 |
+----------+----------+
5 rows in set (0.00 sec)
Even if you reran the query again, it wouldn't change anything. That's because of the IF(...) part of the UPDATE above.
EDIT: I just discovered that my answer is somewhat similar to #nicks, but that's ok, I guess, as my proposed implementation can be safely executed in a "shoot firt, ask questions later" manner ;)
I got your point... Basically you need to edit sort order numbers in your column Priority...
is your priority colum is primary ? or separate id column is there in your mysql table.. ? if separate primary id column doesn't exist.. create it and keep this priority column separate, so you can change/update sort numbers in this column....
in your ajax update script..i.e.... updatePriorityJSON.php.... you will need code somewhat like..
this is not tested.. but given as sample...
for($i=0; $i<count($_POST["priority"]); $i++) {
$query = "
UPDATE table
SET priority = '".$i."'
WHERE id = '".$_POST["id"][$i]."'";
}
more tutorial point of view, please view https://www.webslesson.info/2017/06/sorting-table-row-using-jquery-drag-drop-with-ajax-php.html?m=1
Please take care for prevention of any SQL injection through this code
After updating act5 priority to 1: (*)
UPDATE ACT_Agenda SET priority = 1 WHERE activity = 'act5';
Check to see the other records that need to be updated:
SELECT * FROM ACT_Agenda WHERE priority >= 1 AND activity <> 'act5';
Then update the priority: (*)
UPDATE ACT_Agenda SET priority = priority+1 WHERE priority >= 1 AND activity <> 'act5';
(*) last step is to implement this sql to your code

Join table fields with different ID in PHP

How to join many fields with different ID's in only one?
I have this MySQL table:
--------------------------------
| *UDH* | *Text* |
--------------------------------
| 050003B90301 | Hi my name is A|
--------------------------------
| 050003B90302 | rmin and I wan |
--------------------------------
| 050003B90303 | t be your frien |
--------------------------------
The UDH field is different but I need join the text field to copy to other table, the result must to be like this:
______________________________________________________________
| UDH | Text |
--------------------------------------------------------------
| 1 | Hi my name is Armin and I want be your frien |
---------------------------------------------------------------
Do you know a PHP sentence or other method to make something like this?
Use GROUP_CONCAT(). Like this:
select '1' as UDH, group_concat(`Text` separator '') as `Text` from myTable;
If you need to order by the UDH column, you can do that within the group_concat() call like this:
select '1' as UDH, group_concat(`Text` order by UDH separator '') as `Text` from myTable;
I just validated this query with the following test code based on your example:
mysql> create table myTable (UDH varchar(32), `Text` text) engine=innodb;
Query OK, 0 rows affected (0.05 sec)
mysql> insert into myTable (UDH, `Text`) values ('050003B90301', 'Hi my name is A'), ('050003B90302', 'rmin and I wan'), ('050003B90303', 't be your frien');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from myTable;
+--------------+-----------------+
| UDH | Text |
+--------------+-----------------+
| 050003B90301 | Hi my name is A |
| 050003B90302 | rmin and I wan |
| 050003B90303 | t be your frien |
+--------------+-----------------+
3 rows in set (0.00 sec)
mysql> select '1' as UDH, group_concat(`Text` order by UDH separator '') as `Text` from myTable;
+-----+----------------------------------------------+
| UDH | Text |
+-----+----------------------------------------------+
| 1 | Hi my name is Armin and I want be your frien |
+-----+----------------------------------------------+
1 row in set (0.01 sec)

Trigger- Update columns in one table on inserting in another table

So, I have 2 tables.
One is books, that has the following fields.
accno(Accession number), name(book name), status(Issued/Not Issued)
Second is total, that has the following fields.
name(book name), count(Number of books that are 'Not Issued' in the books table
I have a form that adds books in the books table, and the default status is 'Not Issued'.
I also have a form that issued books i.e. it changes the status to 'Issued'.
And I have a form that returns the books i.e. it changes the status back to 'Not Issued'.
I'm looking for a trigger that updates the count in the total table everytime the bookstable is updated. Count is the number of books that are available(Not Issued) in the books table, and it is different for different books(book names).
I am totally new to triggers. I have looked arond, but I can't seem to figure a way to implement this.
Any help is appreciated. Thank you.
Looks like its an inventory system, so every time a new book comes into the library you store the inventory number into the total table and when a book is issued against the accnum the inventory is decreased by one and then its returned its increased by one.
In this case the following trigger should do the job
delimiter //
create trigger book_available after update on books
for each row
begin
if new.status = 'Issued' then
update total set `count` = `count` - 1 where name = new.book_name ;
else
update total set `count` = `count` + 1 where name = new.book_name ;
end if ;
delimiter ;
Here is a test case
mysql> select * from books ;
+--------+-----------+------------+
| accnum | book_name | status |
+--------+-----------+------------+
| 1 | AA | Not Issued |
| 2 | AA | Issued |
| 3 | BB | Not Issued |
+--------+-----------+------------+
3 rows in set (0.00 sec)
mysql> select * from total ;
+------+-------+
| name | count |
+------+-------+
| AA | 20 |
| BB | 30 |
+------+-------+
2 rows in set (0.00 sec)
mysql> delimiter //
mysql> create trigger book_available after update on books
-> for each row
-> begin
-> if new.status = 'Issued' then
-> update total set `count` = `count` - 1 where name = new.book_name ;
-> else
-> update total set `count` = `count` + 1 where name = new.book_name ;
-> end if ;
-> end ;//
Query OK, 0 rows affected (0.13 sec)
mysql> delimiter ;
mysql> update books set status = 'Issued' where accnum = 1 ;
Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from total ;
+------+-------+
| name | count |
+------+-------+
| AA | 19 |
| BB | 30 |
+------+-------+
2 rows in set (0.00 sec)
mysql> update books set status = 'Not Issued' where accnum = 1 ;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from total ;
+------+-------+
| name | count |
+------+-------+
| AA | 20 |
| BB | 30 |
+------+-------+
2 rows in set (0.00 sec)

Group and Rank Rows in Mysql

I'm trying to build a ranking system in a mysql database.
I've found several tutorials on ranking and items here on StackOverflow about ranking individual rows against each other.
However, my issue is that I need to group rows by a user id column, add up the values to a second column grouped by user id, then rank them against other groups of a different user id.
Here's an example of the table I'm using:
user_id km_skied date_entered
1 34 2010-08-19
3 2 2010-08-23
1 3 2010-08-13
4 23 2010-08-01
3 5 2010-08-02
The result printout would be by rank:
Skier Rank:
Rank User ID Total KM
1 1 37
2 4 23
3 3 7
Also, I was wondering how I find the rank for a specific user. Meaning, if I know what the user id is, can I give them just their rank? Like say
"Your Rank: 2 of 345"
That is the second part of this.
Anyone know how to do that?
Thanks!
Troy
Your query should look something like this. Add the ranking logic to the outer loop.
select * from
(select user_id, sum(km_skied) as km from ski group by user_id) x
order by x.km desc;
Don't know if it's an option, but you can use a temporary table for rankings as follows:
create temporary table ranks (rank int primary key auto_increment, user_id int, km int);
insert into ranks (user_id, km)
select user_id, km from (
select user_id, sum(km_skied) as km from ski group by user_id
) x order by x.km desc;
This gives you what you want:
mysql> select * from ranks;
+------+---------+------+
| rank | user_id | km |
+------+---------+------+
| 1 | 1 | 37 |
| 2 | 4 | 23 |
| 3 | 3 | 7 |
+------+---------+------+
3 rows in set (0.00 sec)
One downside to this approach is that skiers who are tied won't get the same rank.
Do the grouping in subquery and ranking of the results (using any of the methods you've found before) in outer query.
Thanks for your help guys.
I was able to come up with an answer based on the following Query:
$totalQuery = "SELECT SUM(track_length) as usertracklength, username, MAX(track_create_time) as lasttrack, count(DISTINCT track_create_time) as totaldays FROM user_tracks GROUP BY username ORDER BY usertracklength DESC";
$totalResult = mysql_query($totalQuery);
$rankResult = mysql_query($totalQuery);
$totalNumEntries = mysql_num_rows($totalResult);
Then Ouputting that to an array
// rank position array
$rankArray = array();
while ($row1 = mysql_fetch_array($rankResult)) {
$rankArray[] = $row1['username'];
}
Then finding position of that username in the array by using a foreach in php
foreach ($rankArray as $rank => $user) {
if ($user == $username) {
$yourRank = $rank+1;
}
}
It's the long way around, but I suppose it works for what I'm going for.
Was kind of hoping to get it done within the mysql query for efficiency.
Thanks!
You could try grouping to sum the Km as a first query, then follow it by a correlated subquery to find the ranks. For instance, if your values are stored in a table called "test", sum the Km values into a table called testtbl and then do the ranking.
mysql> select * from test;
+------+--------+------+
| Id | km_run | name |
+------+--------+------+
| 1 | 34 | a |
| 3 | 2 | c |
| 1 | 3 | a |
| 4 | 23 | d |
| 3 | 5 | c |
+------+--------+------+
5 rows in set (0.00 sec)
mysql> create table testtbl as
(select Id, sum(km_run) as tot
from test
group by Id);
Query OK, 3 rows affected (0.04 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from testtbl;
+------+------+
| Id | tot |
+------+------+
| 1 | 37 |
| 3 | 7 |
| 4 | 23 |
+------+------+
3 rows in set (0.00 sec)
mysql> select t1.Id,t1.tot,
((select count(distinct t2.tot) from testtbl t2 where t1.tot < t2.tot)+1) as Rk from testtbl t1
order by Rk;
+------+------+------+
| Id | tot | Rk |
+------+------+------+
| 1 | 37 | 1 |
| 4 | 23 | 2 |
| 3 | 7 | 3 |
+------+------+------+
3 rows in set (0.00 sec)

Increase and decrease row value by 1 in MySQL

Hi I have a MySQL database table "points" the user can click a button and a point should be removed from their account, the button they pressed has an ID of another user, therefore their account must increase by one.
I have it working in jQuery and checked the varibles/posts in Firebug, and it does send the correct data, such as:
userid= 1
posterid = 4
I think the problem is with my PHP page:
<?php
include ('../functions.php');
$userid=mysql_real_escape_string($_POST['user_id']);
$posterid=mysql_real_escape_string($_POST['poster_id']);
if (loggedin())
{
include ('../connection.php');
$query1 = "UPDATE `points` SET `points` = `points` - 1 WHERE `userID` = '$userid'";
$result1=mysql_query($query1);
$query2 = "UPDATE `points` SET `points` = `points` + 1 WHERE `userID` = '$posterid'";
$result2=mysql_query($query2);
if ($result1 && result2)
{
echo "Successful";
return 1;
}
else
{
echo mysql_error();
return 0;
}
}
?>
Any ideas? Thanks :)
Two queries to increase/decrease field value are not necessary:
UPDATE table SET field = field + 1 WHERE id = 1
is a perfectly valid query as you can see next:
mysql> describe points;
+--------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| uid | int(11) | NO | PRI | NULL | |
| points | int(11) | YES | | 0 | |
+--------+---------+------+-----+---------+-------+
2 rows in set (0.05 sec)
mysql> insert into points VALUES (1,0),(2,0);
Query OK, 2 rows affected (0.14 sec)
mysql> select * from points;
+-----+--------+
| uid | points |
+-----+--------+
| 1 | 0 |
| 2 | 0 |
+-----+--------+
2 rows in set (0.05 sec)
mysql> update points set points = points+1 where uid = 1;
Query OK, 1 row affected (0.27 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from points;
+-----+--------+
| uid | points |
+-----+--------+
| 1 | 1 |
| 2 | 0 |
+-----+--------+
2 rows in set (0.00 sec)
Having that tested, are you sure you get into your if (loggedin()) clause?
I have to agree with KM, would be nice to see output of echo $query1; or echo $query2;
Here is the example query, tested by me and it is working 100%
$query="UPDATE table_name SET `hit_count`=(`hit_count`+1) WHERE `id` = '1'";
update table_name set col_name=col_name+1 where sqId = 12
But if your col_name by default value is null or empty it never works, so make sure that col_name default value is 0 or any integer value.
update 'tablename' set 'columnname1'='columnname1' + 1 where 'columnname2'='value';
eg: update students set englishmarks=englishmarks + 1 where name='Rahul';
Edit:(Explanation)
"UPDATE" keyword is used to update a vaule in the table. Here I am updating a value in the table "students". "SET" keyword updating the english marks by 1(just like in C language, how we increase the value of an integer, i=i+1) and condidtion is given where name is "Rahul".
So englishmarks of Rahul are incremented by 1
In laravel Migration do:
\DB::statement('SELECT #pos:=0;');
\DB::statement('UPDATE users SET company_id = ( SELECT #pos := #pos + 1 ) WHERE `id` = '1';');
If want to change all records, remove the WHERE id = '1'
It will insert number increment to your records like:
+-----+------------+
| id | company_id |
+-----+------------+
| 1 | 1 |
| 12 | 2 |
| 23 | 3 |
+-----+------------+

Categories