I want to insert into a database via pdo, but if some variables aren't set I won't write them into the database obviously.
Example:
$name is set
$surname isn't set
$query = $db->prepare("INSERT INTO customer SET name = ?");
$query->execute(array($name));
Example 2:
$name is set
$surname is set
$query = $db->prepare("INSERT INTO customer SET name = ?, surname = ?");
$query->execute(array($name, $surname));
How would I implement it with only one prepare and execute? Or what is the smartest way to implement it?
You can use an if condition to check if the variables are set
if(isset($name))
{
if(isset($surname))
{
$query = $db->prepare("INSERT INTO customer SET name = ?, surname = ?");
$query->execute(array($name, $surname));
}
else {
$query = $db->prepare("INSERT INTO customer SET name = ?");
$query->execute(array($name));
}
}
Edit: You can try this code if you want only a single prepare statement
if(isset($name))
{
$q="INSERT INTO customer SET name = ?";
$arr=array($name);
if(isset($surname))
{
$q="INSERT INTO customer SET name = ?, surname = ?";
$arr[]=$surname;
}
}
$query = $db->prepare($q);
$query->execute($arr);