我刚刚从mysqli准备好的声明转到PDO预备声明,因为它会让我觉得更容易
我试图只更新等facebook如果facebook不是空的,但是目前它会更新表格提交的所有内容也是空变量,我该如何解决?
PHP
if (isset($_POST['submit'])) {
$facebook = $_POST['facebook'];
$twitter = $_POST['twitter'];
$youtube = $_POST['youtube'];
$stmt = $dbCon->prepare(" UPDATE login_media "
. " SET login_media_youtube = :youtube, "
. " login_media_facebook = :facebook, "
. " login_media_youtube = :youtube, "
. " login_media_twitter = :twitter ");
$stmt->bindParam(":facebook", $facebook);
$stmt->bindParam(":twitter", $twitter);
$stmt->bindParam(":youtube", $youtube);
$stmt->execute();
}
?>
HTML
<form class="multiForm" action="" method="POST">
<input type="text" name="youtube" placeholder="Youtube">
<input type="text" name="facebook" placeholder="Facebook">
<input type="text" name="twitter" placeholder="Twitter">
<input type="submit" name="submit">
</form>
如果条件满足,我不想制作很多if语句并更新/查询每个语句,我认为有可能使其成为动态,但是如何?
答案 0 :(得分:2)
第一名:简单使用!empty()
第二名:这一行多次出现. " login_media_youtube = :youtube, "
<?php
if (isset($_POST['submit'])) {
$facebook = $_POST['facebook'];
$twitter = $_POST['twitter'];
$youtube = $_POST['youtube'];
if(!empty($facebook ) || !empty($twitter) || !empty($youtube)){
if(!empty($youtube )){
$query_string[]= " login_media_youtube = :youtube ";
}
if(!empty($facebook)){
$query_string[]= " login_media_facebook = :facebook "
}
if(!empty($twitter )){
$query_string[]= " login_media_twitter = :twitter "
}
$stmt = $dbCon->prepare(" UPDATE login_media SET ".implode(' , ',$query_string));
if(!empty($facebook)){
$stmt->bindParam(":facebook", $facebook);
}
if(!empty($twitter)){
$stmt->bindParam(":twitter", $twitter);
}
if(!empty($youtube)){
$stmt->bindParam(":youtube", $youtube);
}
$stmt->execute();
}
else {
echo "nothing to update ";
}
}
?>
答案 1 :(得分:1)
尝试此解决方案。
$socialMedias = ['facebook','twitter','youtube'];
$preparedStatment = "UPDATE login_media SET";
foreach($socialMedias as $socialMedia){
if($_POST[$socialMedia]){
$preparedStatment .= " login_media_{$socialMedia} = :{$socialMedia}";
$stmt = $dbCon->prepare($preparedStatment);
$stmt->bindParam(":$socialMedia",$_POST[$socialMedia]);
}
}
$stmt->execute();
这样,只会更新已填充的文件。