0

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!

user2671169
  • 203
  • 1
  • 10
  • 1
    Are you looking to achieve this in a single query specifically or it doesn't matter? Have you made any attempts to write the query/queries? It's `update... where...`, nothing more. – El_Vanja Nov 30 '20 at 19:11

3 Answers3

-1

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) . ");"
a55
  • 376
  • 3
  • 13
-1

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.

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
-1

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();

?>