Mysql
 sql >> Database >  >> RDS >> Mysql

PHP MySQL - Come inserire il valore predefinito in un'istruzione preparata

Ho avuto lo stesso problema, quindi ho adattato questa risposta https://stackoverflow.com/a/13867665/ 1251063 all'istruzione preparata in php:

if(!($stmt = $this->conn->prepare("INSERT INTO mytable (myfield) VALUES (IFNULL(?,DEFAULT(myfield)))"))){
    throw new Exception("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
}

if(!($stmt->bind_param("s",$myfield))) { //$myfield is a variable that can be null, if so the default value for such field will be inserted
    throw new Exception("Bind_param failed: (" . $this->conn->errno . ") " . $this->conn->error);
}

if(!$stmt->execute()) {
    throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}