(PHP) PDO 根据设置的变量使用不同的查询

(PHP) PDO use different querys dependent on set variables

我想通过 pdo 插入到数据库中,但是如果没有设置某些变量,我显然不会将它们写入数据库。

示例:

$name 已设置

未设置$姓氏

$query = $db->prepare("INSERT INTO customer SET name = ?");
$query->execute(array($name));

示例 2:

$name 已设置

$姓氏已设置

$query = $db->prepare("INSERT INTO customer SET name = ?, surname = ?");
$query->execute(array($name, $surname));

我如何只用一个准备和执行来实现它?或者最聪明的实施方式是什么?

如果我理解你的问题,你想插入姓氏的值,即使它没有设置。

$db->exec('INSERT INTO `customer`(`name`,`surname`) VALUES('.$dbh->quote($name).','.$dbh->quote($surname).')');

代码将插入值,即使它是空的。

编辑:

如果您想得到回复,请使用:

if($db->exec('INSERT INTO `customer`(`name`,`surname`) VALUES('.$dbh->quote($name).','.$dbh->quote($surname).')')) {
   echo 'Success';
} else { 
    echo 'fail';
} 

编辑 2:

    /* if name is not set, insert ONLY surname */
    if(!isset($name)) {
       if($db->exec('INSERT INTO `customer`(`surname`) VALUES('.$db->quote('surname').')')){
          echo 'success';
       } else {
          echo 'fail';
       }
    /* if surname is not set, insert ONLY name */
    } elseif(!isset($surname)) {
       if($db->exec('INSERT INTO `customer`(`name`) VALUES('.$db->quote('name').')')){
          echo 'success';
       } else {
          echo 'fail';
       }
    /* if both are set, insert both */
    } else {
       if($db->exec('INSERT INTO `customer`(`name`,`surname`) VALUES('.$db->quote('name').','.$db->quote('surname').')')){
          echo 'success';
       } else {
          echo 'fail';
       }
    }

您可以使用 if 条件来检查变量是否已设置

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));
}
}

编辑: 如果你只想要一个准备语句

,你可以试试这个代码
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);

你可以试试

<?php 
if (isset($name)&&isset($surname)) {
    $query = $db->prepare("INSERT INTO customer SET name = ? , surname = ?");
    $query->execute(array($name, $surname));
}else {
    if (isset($name){
        $query = $db->prepare("INSERT INTO customer SET name = ? ");
        $query->execute(array($name));
    }else{
        $query = $db->prepare("INSERT INTO customer SET surname = ? ");
        $query->execute(array($surname));
    }
}


?>