M
M
Mikhail Smirnov2021-08-28 23:29:52
PHP
Mikhail Smirnov, 2021-08-28 23:29:52

How to make a change to a database cell?

Help me figure out how to write the code correctly? There is an id variable, suppose it has a value of 11-2 , there are three columns in the database called count1, count2, count3.
It is necessary to read the value in the database in line 11 in the count2 column and add the value of the count variable.

function change(){
    $conn = connect();
    $data = $_POST ['getdata'];
    $stmt = $conn->prepare("UPDATE `sortlist` SET `count$id[1]` ='count$id[1]' + ? WHERE `id`= ? ;");
    $stmt->bind_param('is', $count, $id[0]);//Привязка параметров integer,string
    foreach ($data as $value) {
        $id = $value["id"];        
        $id=explode("-", $id);
        $count = $value["count"];
        $stmt->execute();
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-08-29
@Mehannik

Using dynamic queries can lead to a security breach, so I can advise the following approach to this problem:

$stmt = $conn->prepare(
  "UPDATE `sortlist` 
  SET 
    `count1` ='count1' + ? ,
    `count2` ='count2' + ? ,
    `count3` ='count3' + ? 
  WHERE `id`= ? ;"
);
$stmt->bind_param('iiis', $count1, $count2, $count3, $row);

foreach ($data as $value) {
  list($row, $col) = explode("-", $value['id']);
  
  $count1 = 0;
  $count2 = 0;
  $count3 = 0;
  
  $column = "count" . intval($col); 
  $$column = $value["count"];
  
  echo "$count1, $count2, $count3, $row";
  
  $stmt->execute();
}

Share PHP code online

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question