0

I would like to make different actions based on the result on the same row in a foreach loop.

Based on the query data, I would like to decide to delete the row or update some of the row's data.

I am not a PHP and SQL expert, but I do have some experience.

The code runs without any error, but it looks do nothing to the database.

Any advice is much appreciated.

Here is the code:

try {
  $conn = new PDO("mysql:host=$sqlservername;dbname=$sqldbname", $sqlusername, $sqlpassword);
  $sql = ("SELECT * database WHERE data1=:data1"); // data1 declared previously
  $stmt= $conn->prepare($sql);
  $stmt->execute(['data1' => $data1]);
  $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

  foreach ($result as $row) {
    $data2 = $row['data2'];
    $data3 = $row['data3'];

    if (empty($data3)) {
    $sql = ("DELETE FROM database WHERE data2=:data2");
    $stmt= $conn->prepare($sql);
    $stmt->execute(['data2' => $data2]);      
    }

    elseif (!empty($data3)) {

      $data = [        
        'data2' => $data2,
        'data4' => '',
        'data5' => '',
        'data6' => '',
        
      ];
      $sql = ("UPDATE database SET data4=:data4, data5=:data5, data6=:data6, WHERE = data2:data2");
    $stmt= $conn->prepare($sql);
    $stmt->execute($data);   
    } 
    }
  $conn = null;

  } catch(PDOException $e) {
    echo $e;
  }

ConRaul
  • 1
  • 1

0 Answers0