If you are using MySql 8.0+ you can create a CTE that returns the rows of the ids that you want to update and their marks and join it to the table:
WITH cte(studentId, marks) AS (VALUES
ROW(1, 25), ROW(2, 22), ROW(5, 27), ROW(7, 30), ROW(9, 24)
)
UPDATE tablename t
INNER JOIN cte c ON c.studentId = t.studentId
SET t.marks = c.marks
See the demo.
For previous versions, instead of the CTE you can join a query that uses UNION ALL:
UPDATE tablename t
INNER JOIN (
SELECT 1 studentId, 25 marks UNION ALL
SELECT 2, 22 UNION ALL
SELECT 5, 27 UNION ALL
SELECT 7, 30 UNION ALL
SELECT 9, 24
) c ON c.studentId = t.studentId
SET t.marks = c.marks
See the demo.
If you are using MySql 8.0+ you can create a CTE that returns the rows of the ids that you want to update and their marks and join it to the table:
WITH cte(studentId, marks) AS (VALUES
ROW(1, 25), ROW(2, 22), ROW(5, 27), ROW(7, 30), ROW(9, 24)
)
UPDATE tablename t
INNER JOIN cte c ON c.studentId = t.studentId
SET t.marks = c.marks
See the demo.
For previous versions, instead of the CTE you can join a query that uses UNION ALL:
UPDATE tablename t
INNER JOIN (
SELECT 1 studentId, 25 marks UNION ALL
SELECT 2, 22 UNION ALL
SELECT 5, 27 UNION ALL
SELECT 7, 30 UNION ALL
SELECT 9, 24
) c ON c.studentId = t.studentId
SET t.marks = c.marks
See the demo.
You could run one simple query five times, with different values:
UPDATE MyTable SET marks = ? WHERE studentId = ?
The idea is that you would write a loop in some application code, so you process the first element from each of your arrays. Then the second element of both arrays, and so on. For example in PHP:
$studentId = [1,2,5,7,9];
$marks = [25, 22, 27, 30, 24];
$stmt = $pdo->prepare("UPDATE MyTable SET marks = ? WHERE studentId = ?");
for (
i<5; ++$i) {
$stmt->execute([$marks[
studentId[$i]]);
}
From its earliest versions, SQL was always intended to be used in combination with an application language. Other languages have variables and loops and conditions and functions, which complement SQL. The easiest solution is to use these languages together.
If you really want to write a single UPDATE statement to update all five, it's possible, but it's really not as clear.
UPDATE MyTable
SET marks = CASE studentId
WHEN 1 THEN 25
WHEN 2 THEN 22
WHEN 5 THEN 27
WHEN 7 THEN 30
WHEN 9 THEN 24
END
WHERE studentId IN (1,2,5,7,9);
There are other clever ways of doing it in one statement, but all these solutions are hard to modify or maintain. They are needlessly complex.
I recommend doing it the simple way.
You can try building a single update with a CASE statement, like so:
UPDATE table1
SET column1 = CASE
WHEN cart_id = 1 THEN 11
WHEN cart_id = 2 THEN 12
...
ELSE cart_id = cart_id
END
INSERT INTO students
(id, score1, score2)
VALUES
(1, 5, 8),
(2, 10, 8),
(3, 8, 3),
(4, 10, 7)
ON DUPLICATE KEY UPDATE
score1 = VALUES(score1),
score2 = VALUES(score2);
mysql - Update multiple rows using for loop and array php - Stack Overflow
PHP MYSQL updating multiple rows using values from an array - Stack Overflow
mysql - Updating multiple rows with different values in one query - Database Administrators Stack Exchange
Mysql JSON update multiple object values in an array - Database Administrators Stack Exchange
You can execute one query only by using this :
$sql = "update live_tracking set swim_rank = '".$rank1[$i]."' WHERE id IN (";
for(
i<7;$i++){
$sql .=
i].",";
}
query = mysql_query($sql) or die("error : ".mysql_error());
if($query){
echo "success";
}
Execute the query within the loop itself.
for(
i<7;$i++)
{
mysql_query("update live_tracking set swim_rank = '".$rank1[$i]."' where id = '".
i]."'");
}
UPDATE mytable SET
fruit = CASE WHEN id=1 THEN 'orange' ELSE 'strawberry' END,
drink = CASE WHEN id=1 THEN 'water' ELSE 'wine' END,
food = CASE WHEN id=1 THEN 'pizza' ELSE 'fish' END
WHERE id IN (1,2);
Personally, using CASE WHEN THEN END looks clumsy.
You could code this using the IF function.
UPDATE mytable SET
fruit = IF(id=1,'orange','strawberry'),
drink = IF(id=1,'water','wine'),
food = IF(id=1,'pizza','fish')
WHERE id IN (1,2);
Give it a Try !!!
CAVEAT : CASE WHEN THEN END is only handy when dealing with multiple values (more than 2)
INSERT ... ON DUPLICATE KEY UPDATE
You will need to write very complicated conditions if you want to update more than two rows. In such a case you can use INSERT ... ON DUPLICATE KEY UPDATE approach.
INSERT into `mytable` (id, fruit, drink, food)
VALUES
(1, 'orange', 'water', 'pizza'),
(2, 'strawberry', 'wine', 'fish'),
(3, 'peach', 'jiuce', 'cake')
ON DUPLICATE KEY UPDATE
fruit = VALUES(fruit),
drink = VALUES(drink),
food = VALUES(food);
Finally i got it, after several tries i manage to get what i needed, so i'll share my answer.
First i made one procedure to update one single row in the column:
delimiter //
create procedure update_amount_products (in id int)
begin
update categories set products_amount=
(SELECT DISTINCT COUNT( products_to_categories.products_id )
FROM categories_description
INNER JOIN products_to_categories ON products_to_categories.categories_id = categories_description.categories_id
INNER JOIN products_description ON products_description.products_id = products_to_categories.products_id
WHERE categories_description.categories_id =id)
WHERE categories_id = id;
end
//
DELIMITER ;
Then i realized i could handle the whole column by calling the procedure with another procedure with a loop on it
DELIMITER $$
CREATE PROCEDURE update_products_amount()
BEGIN
DECLARE a INT Default 1 ;
DECLARE category_length int;
select max(categories_id) into category_length from categories_description;
simple_loop: LOOP
SET a=a+1;
call update_amount_products(a);
IF a >= category_length THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
DELIMITER ;
commit;
Finally, all i have to do now, is to call my last procedure and voilá, all my column will be automatically updated.
call update_products_amount();
Not quite sure what you are trying to achieve bit the UPDATE statement would appear to do the job
To update a single known product:
UPDATE PRODUCTS SET PRODUCT_AMOUNT = 42 WHERE PRODUCTS_ID = 1
You can update several at once depending on the WHERE clause and you can also set it to a value from another table.
just remove this from school from your update query and give a name to your table .
like that
$schoolinfo = mysqli_prepare($con, "UPDATE school SET firstname=?, lastname=? where foreignkey='$id'");
you mixed between SELECT and UPDATE.
i dont know if im wrong or , you have binded firstname and lastname before the loop .
try this
$schoolinfo = mysqli_prepare($con, "UPDATE school SET firstname=?, lastname=? WHERE foreignkey='$id'");
for ($i=0;$i<count($_POST['row']);$i++){
$firstname = $_POST['firstname'][$i];
$lastname = $_POST['lastname'][$i];
mysqli_stmt_bind_param($schoolinfo,'ss', $firstname, $lastname)
mysqli_stmt_execute($schoolinfo);
}
Try this:
$schoolinfo = mysqli_prepare($con, "UPDATE school SET firstname=?, lastname=?
WHERE foreignkey=? and rownumber = ?");
mysqli_stmt_bind_param($schoolinfo,'sssi', $firstname, $lastname, $id, $i);
for ($i=0;$i<count($_POST['row']);$i++){
$firstname = $_POST['firstname'][$i];
$lastname = $_POST['lastname'][$i];
mysqli_stmt_execute($schoolinfo);
}
You didn't have rownumber in the query. And it's best to use bind_param for all variables that you're substituting.
Hello,
Been stuck on this one for a while.
Using Mysqli, how can I insert (or update if the key already exists) multiple rows in one transaction?
I would like to loop over this array and execute the query only once, instead of on each iteration of the loop
foreach($challengeData as $challengeId => $status) {
$this->conn->execute_query('
INSERT INTO my_table
(
challenge_id,
status
)
VALUES
(
?,?
)
ON DUPLICATE KEY UPDATE
status = VALUES(status)
',
[
$challengeId,
$status
]
);
}You need to use prepared statements in order to avoid errors and vulnerabilities of all sorts and also to get some minor performance gain
$stmt = $db->prepare("UPDATE site_email_templates SET Content=? WHERE ID = ?");
$stmt->bind_param("ss", $content, $id);
foreach ($postdata as $id => $content)
{
$stmt->execute();
}
Reference: How can I prevent SQL injection in PHP?
Note: My answer is based on the PDO driver which in many aspects is better than mysqli. If you need mysqli solution please check the other answer provided by @Your Common Sense
The code below is tested on real environment and served with prepared statement preventing SQL-injection:
$sql = "UPDATE `site_email_templates` SET `Content` = (:content) WHERE `Id` = (:id)";
$stmt = $dbConn->prepare($sql);
foreach ($postdata as $id => $content)
{
$stmt->execute([':id' => $id, ':content' => $content]);
}
For more details about SQL injection you can read more:
https://www.owasp.org/index.php/SQL_Injection
Use this query:
UPDATE <TABLENAME> SET <COLUMNNAME>=REPLACE(<COLUMNNAME>, '.Z', 'OZ') WHERE <COLUMNNAME> LIKE '%.Z'
- is the name of the table you want to update (remove the <> chars)
- is the name of the column in the table you want to update (remove <>)
Replace is a MySQL function to replace characters in a string (https://www.w3resource.com/mysql/string-functions/mysql-replace-function.php)
LIKE is the search operator. You are only looking for values ending with .Z. The % is a wildcard to have anything at the beginning.
You can use an update as
You can use two separated query
update my_table
set my_col = '12 OZ'
where my_col = '12.Z'
;
update my_table
set my_col = '16 OZ'
where my_col = '16.Z'
;
or use a single query with case when
update my_table
set case when my_col = '12.Z' then '12 OZ'
when my_col = '16.Z' then '16 OZ'
where my_col in ('12.Z', '16.Z')
;