简体   繁体   中英

MySQL updating records with condition

Table A

id | name | important |
-----------------------
 1   Abe        0
 2   Ann        1
 3   John       1
 4   Bill       0

I have a php array of id values

 $ids = [1, 4];

I want update table A setting important column equals 1 if id column value is in $ids array AND setting important column value equals 0 if not.

So for the example, the table after update would be:

id | name | important |
-----------------------
 1   Abe        1
 2   Ann        0
 3   John       0
 4   Bill       1

How to do?

Thanks for any help!

First make array safe before insert

$ids = array_map('intval', $ids);

Then insert with one query

<?php


"UPDATE TableA SET important=1 WHERE id in(" . implode(',',$ids) . ");"

Basically you need to run next query:

UPDATE TableA SET important = (id IN (1,4));

Below php implementation of this:

<?php
$ids = [1,4];

//prepare SQL statement with plaseholders
$placeholder =  implode(',', array_pad([], count($ids) , '?'));
$sql = "UPDATE TableA SET important = (id IN ($placeholder));";

// run update with ids
$pdo->prepare($sql)->execute($ids);

// Get updated data for check result
$sth = $pdo->prepare("SELECT * FROM TableA");
$sth->execute();

print_r($sth->fetchAll());

And here you can test the code.

i am update id value using php pdo . and its work successfully.

first i can try given id value update in 1. and then after try to all ids value update in 0.

so please try this code.

<?php

//This is a database connection

$host_name = 'localhost';
$db_name = 'stackoverflow';
$user_name = 'root';
$password = '';

$conn = new PDO("mysql:host=$host_name; dbname=$db_name;", $user_name, $password);
 
$ids = [1, 4]; //This is a id for update value is 1

$sqlforOneVal = "UPDATE important SET important = 1 WHERE id in (".(implode(', ', $ids)).")";
$updateforOne = $conn->prepare($sqlforOneVal);
$updateforOne->execute();

$sqlforZeroVal = "UPDATE important SET important = 0 WHERE id not in (".(implode(', ', $ids)).")";
$updateforZero = $conn->prepare($sqlforZeroVal);
$updateforZero->execute();

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM