incrementing a table column's data by one || mySql - php

iam having a table with columns like
id || counter
if i do something (some event) i want the counter's value(at a particular id) to increase by one , currently iam doing this :
//get current value
current_value = select counter from myTable where id='someValue'
// increase value
current_value++
//update table with current value
update myTable set counter=current_value where id='someValue';
currently iam running 2 queries for this, please suggest me some way do it in one step.

Just run the math in the database:
update myTable set counter = counter + 1 where id = 'someValue';

Related

adding a passed in number to a MySQL cell with PHP

I am trying to add a number to a number already in a MySQL table. I am using POST to pass in the number.
<?php
require "connection.php";
$id = $_POST["id"];
$number = $_POST["number"];
Do I have to make 2 separate queries, one to retrieve the current value and set is as a variable and one to insert the new value by adding the number to the variable or can I accomplish this with one query with something like this:
$update_query = "update Table set value = (value + $number) where id like '$id';"
Yes, you can use one query UPDATE tbl_name SET value_col = value_col + :number WHERE id = :id
Notes
ID is unique, so you need id = :id to achieve faster queries and only update one field.
Use prepared statements instead of putting values directly to query
update field to add value to existing value:
UPDATE table SET value = value + $number WHERE id = $id;
update field to contact value to existing value:
use the CONCAT function :
UPDATE table SET value= CONCAT('$number',value) WHERE id=$id;

Creating a next and previous buttons

I'm trying to do a next and previous button based on records from database but i'm not really sure how to do it and which would be the best way.
The way that i was thinking to do it
would be to have a field in the table named position.
and the query would look like this:
SELECT * FROM t1 WHERE step = 1
then in the php i would have something like this
$step = $step + 1 // for the next button
if($step === 1) {
$step = 1;
} else {
$step = $step - 1;
}
But if i would delete a record then my position would be out of sync with the math and i won't be able to do + or - on step field because i would find the record.
Which means everytime i would delete something i would need to do a new increment on that field to keep it synced which might later become a problem.
How should i handle it ?
You can add a row number to a query like this:
select #qposn:=#qposn+1 posn, a.* from sometable a, (select #qposn:=0) x
You can select a specific row, in this case the 2nd row, like this:
select * from (
select #qposn:=#qposn+1 posn, a.* from sometable a, (select #qposn:=0) x
) x where posn=2
But be aware that if the data in the table changes the numbering will change also. If someone deletes the first record in the table then the data that used to be row 2 will now be row 1 and so paging may skip or repeat rows.
If your table is relatively small you might consider caching the table in a javascript array and then paging through the array.

php adding amount in rows

I want to add the rows that is being query in database. There is an amount paid, previous balance, new balance.. I want the previous balance to be added by paid amount.
Num|pay|old|new
1 |100|500|600
2 |120|600|720
3 |200|720|920
4 |300|720|920
5 |350|720|920
6 |500|720|920
The database query has data of amountPaid (pay), previous balance (old), new balance (new), but the data in column(new) is wrong.I want to correct it in forloop.Is there a way to help me in this? to get the column(new) value is
column(pay)100 + column(old)500 = column(new)600.
the column(new) in number two will be put in column(old)600 then added by column(pay)120 is equal to column(new)720 and so on.
Hope you can help me in this...
I suppose you are adding the amounts when user submits it
1) Use mysql UPDATE clause in order to change the value in the coloumns
2) use while loop to get the previous value selecting it with a specific id which I suppose you have in your table
3) add it with a new value and update the new amount coloumn
PHP
<?php
$id=$_POST['id'];
$amount=$_POST['amount'];
include("connection.php");
$sql="SELECT * FROM `tablename` WHERE `user_id` ='$id'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res){
$t2 = $row['previous_amount'];
$t3=$t2+$amount;
$sql="UPDATE `bank`.`tablename` SET `new_amount' = '$t3'";
}
?>

PHP/MySQL make top 10 out of selection

A user can input it's preferences to find other users.
Now based on that input, I'd like to get the top 10 best matches to the preferences.
What I thought is:
1) Create a select statement that resolves users preferences
if ($stmt = $mysqli->prepare("SELECT sex FROM ledenvoorkeuren WHERE userid = you"))
$stmt->bind_result($ownsex);
2) Create a select statement that checks all users except for yourself
if ($stmt = $mysqli->prepare("SELECT sex FROM ledenvoorkeuren WHERE userid <> you"))
$stmt->bind_result($othersex);
3) Match select statement 1 with select statement 2
while ($stmt->fetch()) {
$match = 0;
if ($ownsex == $othersex) {
$match = $match + 10;
}
// check next preference
4) Start with a variable with value 0, if preference matches -> variable + 10%
Problem is, I can do this for all members, but how can I then select the top 10???
I think I need to do this in the SQL statement, but I have no idea how...
Ofcourse this is one just one preference and a super simple version of my code, but you'll get the idea. There are like 15 preference settings.
// EDIT //
I would also like to see how much the match rating is on screen!
Well, it was a good question from the start so I upvoted it and then wasted about 1 hour to produce the following :)
Data
I have used a DB named test and table named t for our experiment here.
Below you can find a screenshot showing this table's structure (3 int columns, 1 char(1) column) and complete data
As you can see, everything is rather simple - we have a 4 columns, with id serving as primary key, and a few records (rows).
What we want to achieve
We want to be able to select a limited set of rows from this table based upon some complex criteria, involving comparison of several column's values against needed parameters.
Solution
I've decided to create a function for this. SQL statement follows:
use test;
drop function if exists calcMatch;
delimiter //
create function calcMatch (recordId int, neededQty int, neededSex char(1)) returns int
begin
declare selectedQty int;
declare selectedSex char(1);
declare matchValue int;
set matchValue = 0;
select qty, sex into selectedQty, selectedSex from t where id = recordId;
if selectedQty = neededQty then
set matchValue = matchValue + 10;
end if;
if selectedSex = neededSex then
set matchValue = matchValue + 10;
end if;
return matchValue;
end//
delimiter ;
Minor explanation
Function calculates how well one particular record matches the specified set of parameters, returning an int value as a result. The bigger the value - the better the match.
Function accepts 3 parameters:
recordId - id of the record for which we need to calculate the result(match value)
neededQty - needed quantity. if the record's qty matches it, the result will be increased
neededSex - needed sex value, if the record's sex matches it, the result will be increased
Function selects via id specified record from the table, initializes the resulting match value with 0, then makes a comparison of each required columns against needed value. In case of successful comparison the return value is increased by 10.
Live test
So, hopefully this solves your problem. Feel free to use this for your own project, add needed parameters to function and compare them against needed columns in your table.
Cheers!
Use the limit and offset in query:
SELECT sex FROM ledenvoorkeuren WHERE userid = you limit 10 offset 0
This will give the 10 users data of top most.
You can set a limit in your query like this:
SELECT sex FROM ledenvoorkeuren WHERE userid <> yourid AND sex <> yourpreferredsex limit 0, 10
Where the '0' is the offset, and the '10' your limit
More info here
you may try this
SELECT sex FROM ledenvoorkeuren WHERE userid = you limit 0, 10 order by YOUR_PREFERENCE

in PHP pdo how can i use an incremental identifier

I have the following challenge:
a "Tasks" table:
tasksId int
listId int
taskOrder float
in case i want to move all the tasks from list 2 to list 3 i would do something like:
// pseodo code //
#lastTaskOrder = last task order in list 3
loop - {
UPDATE tasks SET taskOrder = #lastTaskOrder + 1, listId = 3 WHERE listId = 2;
#lastTaskOrder++
}
thus the taskOrder stays unique.
in case i want to move all the tasks from list 2 to the beginning of list 3 i would do something like:
// pseodo code //
#firstTaskOrder = first task order in list 3
#delta = #firstTaskOrder / #numberOfTasksToMove
UPDATE tasks SET taskOrder = #firstTaskOrder + #delta, listId = 3 WHERE listId = 2;
#firstTaskOrder = #firstTaskOrder + #delta
is it possible with mySQL + PDO + PHP?
Short answer: yes.
Longer answer involves some code. To update your list_ids and increment them based on the highest current value in the old list, I had to use a subquery with a window function:
UPDATE tasks
SET list_id = :toList,
task_order =
(SELECT MAX(task_order) from tasks where list_id = :toList)
+ t2.task_sort_order
FROM ( SELECT task_id,
row_number() OVER (PARTITION BY list_id order by task_order)
AS task_sort_order
FROM tasks ) t2
WHERE tasks.task_id = t2.task_id AND tasks.list_id = :fromList
Edit This is heavily edited from the first version. I've thrown away all the PHP in favor of just showing the SQL. I changed the column names because my version of Postgres was complaining about the camel-case names.
this proved to be easier than i thought it would be.
It took me 2 hours but i got it figured out:
SET #start=100;
SET #delta=1.5;
UPDATE tasks SET taskOrder = #start:= (#start+#delta), listId = 3
WHERE listId=2
ORDER BY taskOrder
I PDOed this query with the correct values

Categories