How to update a row depending on a condition - php

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!!!

Related

How to update value of a column as difference between two variables in sql?

Here, update chooses bal(for balance) column of register table whose is to be changed to difference of bal and the value in variable $tax for only the row saisfying the condition. It's not working in following code.How to do it?
$query3 = mysql_query('update table register set bal=bal-'.$tax.' where name='.$user.')' , $connection);
You are using in an incorrect way.
Try this:
$query3 = mysql_query("update table register set bal=(bal-$tax) where name='$user'" , $connection);
It seems, there is extra ')' after user, that hasn't '('

Same Auto Incremental ID Should be insert into Insert Query

I need some help from you people. I don't know It's possible or not.
In PHP, When I insert new query into Database ID value will be auto increment. I have one more variable in that Query, which is parentID.
When Run the query, parentID should be equal to the auto Incremental ID.
I tried mysqli_insert_id($conn); this function. Get last ID. Add one with that value then assign that value to parentID and then insert into database.
But Some kind of time it may be give Isolate problem. So any one guide to provide some other solution to avoid Isolate problem. Isolate means when I try to insert, I got last ID from db. Now assign that value to ParendID variable. And then I try to insert Into DB. Assume it may take few minutes. Within that few minutes some other guys may insert their own regards. That time my last ID will be differed. So I Insert with wrong parendID value.
Please any one help me to solve this problem..!!
<?php
//My connection
$last_id = $conn->insert_id; //get last ID from DB
$parent_id = $last_id + 1;
$sql = "INSERT INTO MyGuests (firstname, lastname, email, ParentID)
VALUES ('John', 'Doe', 'john#example.com', $parent_id)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
First I get LastID and then add One with that value. Then I'll insert Into DB. Instead of this method, In query itself, Directly, can give any other possible solution to assign parent ID equal to current ID of the field?
This can be done with the help of the triggers,
all you need to do is copy the new value of the id into the parentID "AFTER" insertion.
CREATE TRIGGER ins_parentID
AFTER INSERT ON MyGuests
FOR EACH ROW SET
NEW.ParentId = NEW.ID;
Code should look something like this (THIS ONE IS NOT TESTED)

How to SELECT a record, UPDATE it and be sure it hasn't been updated in the mean?

I need to do something like that:
SELECT id FROM table WHERE option='1' ORDER BY time LIMIT 1
then with the id in $id
UPDATE table SET used='1' WHERE id='$id'
The problem is that this way another user can update the same record in the same time.
Is there a way to do that in one only operation ?
Thanks
UPDATE table SET used='1'
WHERE id=
(SELECT id FROM
(SELECT id FROM table
WHERE option='1'
ORDER BY time
LIMIT 1) AS tmptable
)
You need to use a three step query if you have concurrent access to the same row by different users.
First query has to reserve the row for a certain user (using a dedicated field).
Second query has to check if the row reservation is for that certain user.
Third query updates the row knowing there's no collision as that user reserved it.
Between step #1 and #2, multiple users can try to grab edit access to the row but in the end only one succeeds. The ones that failed will not reach step #3.
PS: This might be overkill for your needs but it's the best way to ensure multiple users work on tasks (rows) concurrently.
PPS: Or just combine the queries into a single one as another answer points out. But if your update requires some work done, it's best to decide upfront who will do the work before updating the value.
You could use: http://php.net/manual/en/mysqli.insert-id.php
mysql_insert_id
Finds the last id updated or set and stores it. We then check to make sure the last id does not exist.
so...
//last id being the id of the last query set or updated
$last_id = $mysql->insert_id;
if($last_id != $id) {
//execute code
{
else {
echo "last id already in database!";
}
If I misinterpreted the question you should still be able to see how to use that last id to do what you want.
Here is an example of it being used. First we update the table with the form data which created our ID. Then we add the input check boxes array to the last id updated.
//define input variables
$lesson_id = $_POST['lesson_id'];
$user_id = $_POST['user_id'];
$instructor_id = $_POST['instructor_id'];
$lesson_comments = $_POST['lesson_comments'];
$lesson_date = date("Y-m-d");
$video_ids = isset($_POST['checkbox']) ? $_POST['checkbox'] : array(); # this is called a ternary operator
//insert lesson information first
$query ="INSERT INTO swing_viewer_lessons (lesson_id, user_id, instructor_id, lesson_comments, lesson_date) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("iiiss", $lesson_id, $user_id, $instructor_id, $lesson_comments, $lesson_date);
$stmt->execute();
//printf($stmt->error);
echo "successful";
//echo "$last_id";
}
//insert lesson information
if (is_array($video_ids) && count($video_ids) > 0)
{
foreach($video_ids as $list);
}
// Make it into a comma separated list
$rec_ids = implode(',', $video_ids);
//get last inserted id from above
$last_id= $mysqli->insert_id;
//finally query and update lesson information based on the last id added from above
$query ="UPDATE swing_viewer_lessons SET video_ids=? WHERE id=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("si", $rec_ids, $last_id);
$stmt->execute();
}
Hopefully this helps you or anyone else for that matter, as at one point I was pulling hair at this.

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.

Update int in MySQL Field

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.

Categories