(PHP)PDO使用不同的查询依赖于设置变量

时间:2016-04-16 14:03:56

标签: php mysql pdo prepare

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

示例:

$ name已设置

$ surname isn未设置

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

示例2:

$ name已设置

$ surname已设置

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

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

3 个答案:

答案 0 :(得分:0)

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

$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';
       }
    }

答案 1 :(得分:0)

您可以使用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);

答案 2 :(得分:0)

你可以尝试

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


?>