i would like to update a table with mySQL where rows got the same name as the name of given ID and increase and decrease their file_version.
The function should restore and older version of the file.
My table looks like this:
ID | name | file_version
1 | book-1 | 1
2 | book-1 | 2
3 | book-1 | 3
4 | book-2 | 1
The function gives the variables $docId and $fileVersion.
First i search for the max. file_version in the table and store it in a variable.
$query =
'SELECT max(file_version) FROM myTable where doc_name in (
SELECT doc_name FROM myTable
WHERE id = '.$docId.');';
$result1 = mysql_query($query);
$row = mysql_fetch_row($result1);
$maxVersion = $row[0];
After that i set the file_version of the desired ID to max.
$query2 = 'SELECT file_version FROM dscQm_docs WHERE id='.$docId.';';
$result2 = mysql_query($query2);
$row = mysql_fetch_row($result2);
$fileVersion = $row[0];
Now comes the tricky part.
I would like to set the file_version of all docs with the same name as the name of the given ID -1 if their file_version is higher than the file_version of the given ID.
Here's my approach:
$query4 = '
UPDATE myTable SET file_version = file_version -1 WHERE(
SELECT * FROM myTable
WHERE name in (
SELECT name FROM myTable
WHERE id = '.$docId.' AND file_version > '.$fileVersion.'
);
';
That doesn't work.
I'm sorry..i'm not good in SQL. I know this is crap.
Could you help me with the last SQL statement?
Thanks in advance.
Try this, you will avoid the much dreaded IN operator with subqueries (they can sometimes be inefficient, to say the least)!
update myTable as t1
left join myTable as t2 on (t1.name = t2. name)
set t2.file_version = t2.file_version -1
where t2.file_version > t1.file_version
and t1.id = *YOUR_ID*
$query4 = '
UPDATE myTable SET file_version = file_version -1 WHERE name like (
SELECT name FROM myTable
WHERE id = '.$docId.' AND file_version > '.$fileVersion.'
)';
Try this?
EDIT: If u know the name, why don't you just compare the name only?
Like:
$query4 = "UPDATE myTable SET file_version = file_version -1 WHERE name like '$name'";
EDIT2: Why don't you work OO? Instead of using so many different queries? To always get 1 value... Then you can store all the data related to 1 row at the same time.
Related
I have one table with event_id & image_id. I want to find the no of rows which with the same value -> max in this table.
means in this table output should like:
1508706279 -> image_id
4 -> no of rows
here is my table.
below is the code which i have tried.
$sql2 = "select image_id, COUNT(*) as count from user_likes where event_id = '$id' GROUP BY image_id";
if($result2 = mysqli_query($conn, $sql2)) {
$result1 = mysqli_fetch_array($result2);
$win = $result1['image_id'];
$count = $result1['count'];
}
Now, i can't understand what is issue but this code works fine when there are rows between id 52 to 60
it shows output:
1508706279 -> image_id
4 -> no of rows
but when i add two more rows with id 64 & 65
it shows output:
818525590 -> image_id
1 -> no of rows
help me in this what mistake i am doing here.!!
Your query return a collection of image_id and count.
The collection is not ordered so you have the first one from select
if you need the max try ordering by count(*) desc
$sql2 = "select image_id, COUNT(*) as count
from user_likes
where event_id = '$id'
GROUP BY image_id
ORDER BY count(*) DESC";
and you can limit to 1 if you need one row only
$sql2 = "select image_id, COUNT(*) as count
from user_likes
where event_id = '$id'
GROUP BY image_id
ORDER BY count(*) DESC LIMIT 1";
I'm currently working on my query. So I have two tables, tbl_room and tbl_reservation. I wanted to do an update query with the following conditions:
Decrement room counter by 1 in tbl_room if:
The first and last name of the customer matches the first and last name in the tbl_reservation
The tbl_reservation room ID matches with the tbl_room room ID
I'm currently stuck with this:
$result = mysql_query("UPDATE
tbl_room
JOIN tbl_reservation
ON tbl_room.roomID = tbl_reservation.roomID
AND tbl_reservation.cus_fname = '$cusFN'
AND tbl_reservation.cus_lname = '$cusLN' SET tbl_room.reserve = reserve - 1 ");
These are my tables:
----------
tbl_room
----------
roomID,
room_type,
capacity,
reserve <--- reservation counter
----------
tbl_reservation
----------
reserveID,
cus_fname,
cus_lname,
I already came up with the right query. Yehey! So I moved my query just after the while statement and used this syntax:
$result6 = mysql_query("UPDATE tbl_room
JOIN tbl_reservation ON tbl_room.roomID=tbl_reservation.roomID
AND tbl_reservation.cus_fname='$cusFN'
AND tbl_reservation.cus_lname='$cusLN'
SET tbl_room.reserve=tbl_room.reserve-1");
Try this...
$sql = "UPDATE `tbl_room`
SET `tbl_room`.`reserve` = `tbl_room`.`reserve` - 1
WHERE `tbl_room`.`roomID` = `tbl_reservation`.`roomID`
AND `tbl_reservation`.`cus_fname` = '$cusFN'
AND `tbl_reservation`.`cus_lname` = '$cusLN'";
I have a table that looks like this:
id | user_id | credits
----------------------
1 | 2 | 300
2 | 2 | 200
3 | 4 | 100
I need a select or way to add the credits from a specific user id
The select would be:
SELECT credit FROM myTable WHERE user_id ='2'
The result I would need in this case would be 500
How can I do this?
Use SUM() in your query will solve the issue.
SELECT SUM(`credits`) AS `total` FROM `myTable` WHERE `user_id` =2
Since you specify PHP tag, the below code will help you.
$mysqli=mysqli_connect("hostname","username","password","databasename");
$query = "SELECT SUM(`credits`) AS `total` FROM `myTable` WHERE `user_id` =2";
$processquery = $mysqli->query($query);
$result = $processquery->fetch_assoc();
echo $result['total'];
Use sum()
SELECT sum(credit) as sum_credit
FROM myTable
WHERE user_id = 2
Use aggregate function SUM():
SELECT SUM(credit) as TotalCredit
FROM myTable
WHERE user_id='2'
Read more about aggregate functions here.
Try SUM() in mysql
SELECT SUM(credit) as totalcredit FROM myTable WHERE user_id ='2'
will return you matched result sum according to condition
select sum(credit) as total from myTable where user_id = '2'
You can do this by summing the total of the credit column. Check out the MySQL reference manual for the official instructions.
SELECT SUM(credit) AS credit_total
FROM myTable
WHERE user_id = 2
You use the AS keyword to assign a name to your column, then in PHP you can access this column as you would any other by name, just using credit_total. E.g:
$query = "SELECT SUM(credit) AS credit_total
FROM myTable
WHERE user_id = 2";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
echo $row['credit_total']; // Will output 500
BEFORE
id | cat_id | order
33 | 1 | 1
34 | 1 | 2
AFTER
id | cat_id | order
33 | 1 | 2
34 | 1 | 1
Now using 4 query
$db is wrap $mysqli for using placeholder and injection defense
get first record by id
$curr = $db->q('SELECT id,order,cat_id FROM `tbl` WHERE id`=? FOR UPDATE',
33)->fetch_assoc();
if exist first record find next record by order field
if($curr){
$next = $db->q('SELECT id,order FROM `tbl` WHERE `cat_id`=? AND
`order`>? ORDER BY `order` LIMIT 1 FOR UPDATE',
$curr['cat_id'],$curr['order']));
if exist first and second recorn change order value
if($prev['id']){
$db->q("UPDATE `tbl` SET `order`=? WHERE `id`=?",$next['order'],$curr['id']);
$db->q("UPDATE `tbl` SET `order`=? WHERE `id`=?",$curr['order'],$next['id']);
}
}
Important! Checking exist two record, lock rows for update
MySQL doesn't support update with the same table in the FROM statement. So because of this there are (select * from TBL) as t2 in inner subqueries.
Also EXISTS condition in the first CASE WHEN is to prevent update if the second record doesn't exists ("if exist first and second records change order value")
Here is a SQLfiddle example
UPDATE tbl as t1
SET `order`=
CASE WHEN id = 33
and
EXISTS (SELECT ID from (select * from TBL) t2 where
cat_id=t1.Cat_Id
and `order`>t1.`order`
ORDER BY `order`
LIMIT 1)
THEN
(SELECT `order` from (select * from TBL) t2 where
cat_id=t1.Cat_Id
and `order`>t1.`order`
ORDER BY `order`
LIMIT 1)
WHEN id <>33 THEN
(SELECT `order` from (select * from TBL) t2 where
cat_id=t1.Cat_Id
and `order`<t1.`order`
ORDER BY `order` DESC
LIMIT 1 )
ELSE `order`
END
where id =33
or
(SELECT ID from (select * from TBL) t2 where
cat_id=t1.Cat_Id
and `order`<t1.`order`
ORDER BY `order` DESC
LIMIT 1) =33
With one query it's:
UPDATE
`tbl`
SET
`order`=CASE
WHEN `order`=2 THEN 1
WHEN `order`=1 THEN 2
END;
WHERE
`order` IN (1,2)
or, for id's condition:
UPDATE
`tbl`
SET
`order`=CASE
WHEN `order`=2 THEN 1
WHEN `order`=1 THEN 2
END;
WHERE
id = $id
To swap 2 fields by row id try:
UPDATE `tbl` AS tbl1
JOIN `tbl` AS tbl2 ON ( tbl1.id = 33 AND tbl2.id = 34 )
SET
tbl1.order = tbl2.order, tbl2.order = tbl1.order
Also you can set your desired value instead of swap between 2 fileds.
If needed, you can add a where clause like below to swap where cat_id are 1 in two rows:
WHERE
tbl1.cat_id = 1 AND tbl2.cat_id = 1
Update:
If your order numbers are unique for any cat_id you can try this way:
UPDATE `tbl` AS tbl1
JOIN `tbl` AS tbl2 ON ( tbl1.order = 1 AND tbl2.order = 2 )
SET
tbl1.order = tbl2.order, tbl2.order = tbl1.order
WHERE
tbl1.cat_id = 1 AND tbl2.cat_id = 1
It works if your order field is int, Otherwise you should quote order values in query.
See the result on SQLFiddle
Lets say I have 3 columns and 3 rows, the first column is for ID, the second is names, third is votes. like:
+----+------+-------+
| id | name | votes |
+----+------+-------+
| 1 | bob | 7 |
| 2 | jill | 2 |
| 3 | jake | 9 |
+----+------+-------+
How can I have PHP compare the values in the votes field and sort it by whichever had the highest number, and attach a rank of #1,2,3, etc. depending on how many votes it had?
Each value will be displayed on a separate page. For example, if I went to 'bob's page' with the ID of 1, I would need it to display '#2 bob' since he would be ranked 2nd by votes.
You can make a separate column rank and update it by running the following code whenever your vote changes. This method will make you more efficient as in this you wont be sorting the table again and again when user visits his page:
$q = "select * from tableName order by votes DESC";
$a = mysql_query($q);
$count = 1;
while($arr = mysql_fetch_array($a){
$up = "update tableName set(rank) VALUES($count) WHERE name=$arr['name']";
$aq = mysql_query($up);
$count++;
}
Now on individual pages, you can just retrieve the rank value and show
$user = "Bob";
$q = "select rank from tableName where name=$user";
$a = mysql_query($q);
$arr = mysql_fetch_array($a);
echo $arr[0];
Also this(a slight modification in other answer) should work for you :-
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) as P ORDER BY vote DESC
You could read the values returned by your query into an array and then sort said array.
You want a SELECT query doing an ORDER BY votes, and create a special variable to handle the rank of a row:
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) ORDER BY vote DESC
This query should let you fetch an array with the rank, name, and number of votes of each person of your table.
Alternatively, you can just sort by vote, and add the rank value yourself with PHP.
You can use the MySQL 'ORDER BY' and display those ranks using PHP:
For this example:
<?php
//connection
//DB selection
$query = "SELECT * FROM table_votes ORDER BY votes DESC";
$result = mysql_query($query);
for(int $i=1; $row = mysql_fetch_array($result);i++)
{
echo "#".$i.$row['name']."<br/>";
}
?>