Refresh request with conditional?

I am not sure if this is possible. If not, let me know.

I have a mysql PDO that updates 3 fields.

$update = $mypdo->prepare("UPDATE tablename SET field1=:field1, field2=:field2, field3=:field3 WHERE key=:key"); 

But I want field3 to field3 updated only when $update3 = true; (this means that the field3 update field3 controlled by a conditional expression)

Is it possible to execute one request?

I could do this with 2 queries, where I update field1 and field2 , and then check boolean and update field3 if necessary in a separate request.

 //run this query to update only fields 1 and 2 $update_part1 = $mypdo->prepare("UPDATE tablename SET field1=:field1, field2=:field2 WHERE key=:key"); //if field3 should be update, run a separate query to update it separately if ($update3){ $update_part2 = $mypdo->prepare("UPDATE tablename SET field3=:field3 WHERE key=:key"); } 

But hopefully there is a way to accomplish this in 1 query?

+4
source share
1 answer

You do not need to make multiple requests. Why don't you just structure your query string based on this conditional, and then just pass it to your DB adapter for execution? This may be as follows:

  $pdo = new PDO($dsn, $user, $password); $sql = "UPDATE table SET columnname1=:field1, columname2=:field2"; if ( $update ) $sql .= ",columname3=:field3"; $sql .= " WHERE key=:key"; $stmt = $pdo->prepare($sql); $stmt->bindParam(":key", $key, PDO::PARAM_INT); $stmt->bindParam(":field1", $field1, PDO::PARAM_STR); $stmt->bindParam(":field2", $field2, PDO::PARAM_STR); if($update) $stmt->bindParam(":field3", $field3, PDO::PARAM_STR); $stmt->execute(); 
+5
source

Source: https://habr.com/ru/post/1308201/


All Articles