PHP mysqli Select Add field - php

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

Related

Find the maximum value of a MySQL group by and assign it to a variable

I have a MySQL table called "cylinders". Two of the columns are pid and reportno.
pid | reportno
13-2021 | 1
14-2025 | 1
13-2021 | 2
13-2021 | 3
15-2034 | 1
14-2025 | 2
I want to find the highest reportno for a group so that I can add to the table using the next reportno.
I have this:
$query = "SELECT * FROM cylinders GROUP BY pid ORDER BY reportno DESC LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$lastrpt = $row["reportno"];
$nextrpt = $lastprt + 1;
But $lastrpt variable has value 0. What am I doing wrong?
I don't think the query will work because you have to add reportno to the group by clause or use it in aggregation. Try the following.
SELECT pid, MAX(ReportNo) FROM cylinders GROUP BY pid ORDER BY reportno DESC LIMIT 1
SELECT MAX(REPORTNO) FROM CYLINDERS;
You can add a row and look up the highest reportno in one query:
INSERT INTO cylinders (pid, reportno)
SELECT '13-2021', MAX(reportno) + 1 FROM cylinders
WHERE pid='13-2021';
You shouldn't use mysql_query, it's deprecated. Use mysqli_query instead.
Edit: changed based on comment
It can be done without the GROUP BY as you need the highest reportno -
SELECT * FROM cylinders ORDER BY reportno DESC LIMIT 1
Update
SELECT pid, MAX(reportno) max_reportno FROM cylinders GROUP BY pid ORDER BY max_reportno DESC LIMIT 1

Update table with same value based on given ID

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.

Mysql replace two value in one query?

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

Sorting and Ranking values of columns in mysql

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/>";
}
?>

WHERE id IN doesn't work in UPDATE

UPDATE statistics'
SET money = money + '$money'
WHERE member_id IN ((SELECT member_id FROM races WHERE l_id = '$mem_id'), $other_id)
What's wrong with that? I want to retrieve all member_ids from races and also include to member_id $other_id. Without $other_id it works.
By the way, it gives me "Subquery returns more than 1 row" error.
Try with:
UPDATE statistics
SET money = money + $money
WHERE member_id IN (
SELECT member_id
FROM races
WHERE l_id = $mem_id
)
OR member_id = $other_id
And suggestion - for int type columns do not use apostrophs.
subquery returns member_id and $other_id
Another way to do it:
(SELECT member_id FROM races WHERE l_id = '$mem_id'
UNION
SELECT $other_id)

Categories