Update int in MySQL Field - php

How can I increment an int in a cell of a MySQL database? I know that auto-increment is no use because I never want to add a new row, just update an existing one. I'm currently using this (POST var used for clarify, is verified in the real code):
$columnToUpdate = 'type'.$_POST['voteid'];
$query = "UPDATE myTable $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
if(!mysql_query($query)) {
echo json_encode(array('success' => false, 'message' => 'Update failed: '.mysql_error()));
exit;
}
In the database I have 6 fields, id, type1, type2, type3, type4, type5, and a single row with id set to 1. The intention is to recieve a number (1-5), and build a reference to the correct column before updating the field. That results in Update failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=type4+1 WHERE id=1' at line 1, so I guess it's not getting the field value out properly before it increments.
Once this is working I'm also going to need to decrement a field in the same way, unless its value is 0. So for bonus points, can I do all this in one query or would it be better to split it up?

I think you've missed the keyword 'SET' from your query - try
$query = "UPDATE myTable SET $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
Edit:
To do the "decrement unless it's zero" you could use something like:
UPDATE myTable SET $columnToUpdate =
CASE $columnToUpdate
WHEN 0 THEN 0
ELSE $columnToUpdate - 1
END CASE
WHERE id=1;`

For bonus points, to decrement:
$query = "UPDATE myTable SET '$columnToUpdate' = '$columnToUpdate'-1 WHERE id=1 AND '$columnToUpdate' > 0";

Besides the injection issues, it seems as if your workflow may need some work. Are you sure you want to choose the column that will be updated based on POST variable? It seems like you would specify the column and use the variable to find the record that needs to be updated:
IE:
"UPDATE myTable SET votes=votes+1 WHERE id=$post_variable;"
Again you should send the variable as a parameterized query to protect yourself from SQL injection.

Related

How to update a row depending on a condition

I try to update a row in my database. i receive no error but the update does not happend
$sql = "UPDATE calendar_events
SET event_title='".$_POST["naam"]."'
WHERE id ='($event_id)'";
problem is by variable $event_id. If i place a nummber in place of $event_id ( WHERE id =6)
then it is ok and i have my update but any he do not accept any variable
I did change a lot of things. The type of variabls id and $event_id are the same. De value of the id and $event_id are de same . i did try with $event_id, and '".$event_id."'. every thing is ok
and no erroror from database bat the update do not happen.
can someone help me
thanks
Try with
$sql = "UPDATE calendar_events
SET event_title='".$_POST["naam"]."'
WHERE id ='$event_id'";
Otherwise, you are comparing it with (1), (2) or whatever number it has, but with parenthesis.
UPDATE: and, of course, SANITIZE your $_POST variables!!!

Update column if received x otherwise update y

If I have a table with 3 columns: id,column1,column2. If i want to update column1 just when receiving "column1" parameter in URL request otherwise update column2 when receiving "column2" parameter in URL adress. Is that possible? I made that but i think that's not correct:
$sql= "UPDATE people SET
answer_yes= '$answer_yes'+1,
answer_no='$answer_no'+1";
Thank you for helping.
EDIT: Now that is working (based on Richard Vivian answer)
If($answer_yes==1)
{
$sql= "UPDATE people SET answer_yes= answer_yes +1"or die(mysql_error());
mysql_query($sql);
}
else if ($answer_no==0)
{
$sql= "UPDATE people SET answer_no= answer_no+1" or die(mysql_error());
mysql_query($sql);
}
You can create 2 SQL statement options:
If($answer_yes)
{
$sql= "UPDATE people SET answer_yes= '$answer_yes'+1"
}
else
{
$sql= "UPDATE people SET answer_no= '$answer_no'+1"
}
I'm unsure which database model you are using, but the logic would be to pass a NULL value if you don't have a value to pass, and check that the values not null before updating.
SQL Server
UPDATE Table
SET Column1=ISNULL(#Column1,Column1),
Column2=ISNULL(#Column2,Column2)
MySQL
UPDATE Table
SET Column1=IFNULL($Column1,Column1),
Column2=IFNULL($Column2,Column2)
What is happening here is that ISNULL/IFNULL is checking whether the first value passed to it is NULL, and if it is, its returning the 2nd value. The 2nd value is the same value as the current value, and therefore it updates it with the same value (ie. Not changing the value).
You can do this:
UPDATE people
SET answer_yes = COALESCE($answer_yes + 1, answer_yes),
answer_no = COALESCE($answer_no + 1, answer_no);
The COALESCE returns the first non NULLable value in the values passed to it. If any of the parameters $answer_yes or $answer_no were passed with a NULL value, then $answer_yes + 1 and $answer_no + 1 will be evaluated to NULL also, there for the COALESCE will return the column value, and in this case the column will be updated with its value, i.e, it won't changed.

PHP/MySQL Concat to a single column and Update other columns in table

Am trying to only concat new updates to column updates and UPDATE the values in the rest of the columns but I've hit bit of a snag that I can't seem to workout.
My SQL looks like this:
$query="Update tickets SET product='$product',
p='$p',
i='$i',
summary='$summary',
workaround='$workaround',
concat(updates,'$additional_update'),
status='$status',
raised_by='$raised_by',
updated_by_user='$updated_by' WHERE id='$id'";
the updates column is like a comments column, where new updates are meant to be appended to the existing text.
The error I'm getting on the web server:
Update tickets SET product='T-Box', p='00000817766', i='-', summary='Testing update field
\r\nAdding an update\r\ntesting if null works for update', workaround='n/a', concat(updates,' ','test2#18:53:17:second update/n'), status='Open', raised_by='No', updated_by_user='test2' WHERE id='223'
Running the query directly in MySQL:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(updates,'test2#18:53:17:second update/n'), status='Open', raised_by='No', updat' at line 1
Help is much appreciated!
You need to specify where the value of this statement concat(updates,'$additional_update') to be set.
Update tickets
SET product = '$product',
p = '$p',
i = '$i',
summary = '$summary',
workaround = '$workaround',
updates = CONCAT(updates,'$additional_update'), // <== see this
status = '$status',
raised_by = '$raised_by',
updated_by_user = '$updated_by'
WHERE id = '$id'
try this:
$query="Update tickets SET product='$product',
p='$p',
i='$i',
summary='$summary',
workaround='$workaround',
updates=concat(updates,'$additional_update'),
status='$status',
raised_by='$raised_by',
updated_by_user='$updated_by' WHERE id='$id'";

Syntax error with IF EXISTS UPDATE ELSE INSERT

I'm using MySQL 5.1 hosted at my ISP. This is my query
mysql_query("
IF EXISTS(SELECT * FROM licensing_active WHERE title_1='$title_1') THEN
BEGIN
UPDATE licensing_active SET time='$time' WHERE title_1='$title_1')
END ELSE BEGIN
INSERT INTO licensing_active(title_1) VALUES('$title_1')
END
") or die(mysql_error());
The error is
... check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM licensing_active WHERE title_1='Title1') THEN ' at line 1
My actual task involves
WHERE title_1='$title_1' AND title_2='$title_2' AND version='$version' ...ETC...
but I have reduced it down to make things simpler for my problem solving
In my searches on this, I keep seeing references to 'ON DUPLICATE KEY UPDATE', but don't know what to do with that.
Here is a simple and easy solution, try it.
$result = mysql_query("SELECT * FROM licensing_active WHERE title_1 ='$title_1' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE licensing_active SET time = '$time' WHERE title_1 = '$title_1' ");
}
else
{
mysql_query("INSERT INTO licensing_active (title_1) VALUES ('$title_1') ");
}
Note: Though this question is from 2012, keep in mind that mysql_* functions are no longer available since PHP 7.
This should do the trick for you:
insert into
licensing_active (title_1, time)
VALUES('$title_1', '$time')
on duplicate key
update set time='$time'
This is assuming that title_1 is a unique column (enforced by the database) in your table.
The way that insert... on duplicate works is it tries to insert a new row first, but if the insert is rejected because a key stops it, it will allow you to update certain fields instead.
The syntax of your query is wrong. Checkout http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
Use the on duplicate key syntax to achieve the result you want. See http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
Another solution
$insertQuery = "INSERT INTO licensing_active (title_1) VALUES ('$title_1')";
if(!$link->query($insertQuery)){ // Insert fails, so update
$updateQuery = "UPDATE licensing_active SET time='$time' WHERE title_1='$title_1'";
$link->query($updateQuery);
}
Here is the example I tried and its works fine:
INSERT INTO user(id, name, address) VALUES(2, "Fadl", "essttt") ON DUPLICATE KEY UPDATE name = "kahn ajab", address = "Address is test"
I am amazed to see so many useless codes and answers...
Just replace INSERT with REPLACE.
¯\(ツ)/¯

How to return inserted row from INSERT statement with php, SQL SERVER 2005?

What is the easiest / most efficient way to get the entire row inserted after an INSERT statement?
I am pretty sure I could do this as follows:
$aQuery = "INSERT into myTable (a, b, c) VALUES (1, 'Hello', 'Goodbye')";
//the IDENTITY coloumn in myTable is named id
$result = sqlsrv_query($myConn, $aQuery );
if ($result) {
$res = sqlsrv_query('SELECT LAST_INSERT_ID()');
$row = sqlsrv_fetch_array($res);
$lastInsertId = $row[0];
$subQuery = "SELECT * FROM myTable where id = {$lastInsertId}";
$subResult = sqlsrv_query($myConn, $subQuery);
if ($subResult) {
while($subrow = sqlsrv_fetch_array($subResult)) {
echo($subrow ['id'] . ', '.
$subrow ['a'] . ', '.
$subrow ['b']); //etc...
}
}
}
However, I am concerned about the possibility of another insert occurring just before my SELECT LAST_INSERT_ID() and thus messing up my logic to boot. How can I be certain that the last inserted id is truly the INSERT I called previously, and not something happening somewhere else?
Is there a more appropriate way of doing this, perhaps a complete SQL solution (such that the query returns the row automatically rather than using PHP)?
UPDATE: myTable DOES have an explicitly defined (and auto-incremented) identity column, named id.
This will work:
"INSERT into myTable (a, b, c) OUTPUT Inserted.a, Inserted.b, Inserted.c VALUES (1, 'Hello', 'Goodbye')
In Sql Server, you would use select #lastID=SCOPE_IDENTITY()
And #LastID will have the last id inserted for the current scope; therefore, if there was another insertion in the middle, you would still get the correct record on your select.
Never use ##Identity for this or you may end up in a situation like you described.
If you were to use identity field (which maybe you should) there is a command called SCOPE_IDENTIY() which info you can find here:
http://msdn.microsoft.com/en-us/library/ms190315.aspx
Since you do not use it, you do not have to select latest data since you have it when you insert, so just use same data instead of selecting.

Categories