Home > Net >  mysql set null if variable not exist
mysql set null if variable not exist

Time:11-26

I would like to do a simple mysql update command:

$sql = "UPDATE `myTable` SET `rowA` = '".$varA ?? NULL."'
WHERE `id` = '1'"; 

If $varA has an value, take this, if not => NULL But with echo $sql it looks like this:

UPDATE `myTable` SET `rowA` =

An idea?

CodePudding user response:

With prepared statement:

$mysqli = new mysqli('host', 'user', 'password', 'database');
$stmt = $mysqli->prepare('UPDATE `myTable` SET `rowA` = ? WHERE `id` = ?;');

// Values to bind
$valueRowA = $varA ?? null;   // assuming $varA is a string or null
$valueId = 1;                 // assuming an int

// Bind the values to the SQL statement
$stmt->bind_param('si', $valueRowA, $valueId);
// 'si' tells bind_param() that $valueRowA is a string and $valueId is an int

// Execute the query
$stmt->execute();

CodePudding user response:

You need to do below to insert NULL in table:

$sql = "UPDATE `myTable` SET `rowA` = NULLIF('$varA','') WHERE `id` = '1'"; 
  • Related