带有if-else条件的SQL UPDATE



如果表中的列不为空,我想用变量更新列post_authorpost_user。如果去掉这些特定条件,只留下一个,例如post_author,那么一切都正常,我只在sql的"case"部分有问题。

有这个问题:

注意:失败您的SQL语法有错误;查看手册对应于您的MariaDB服务器版本以获得正确的语法在'SET post_author=case附近使用post_author=则为null第1行处的'evgen'else null结束,SET p'

$query = "UPDATE posts SET post_title = '{$post_title}', 
post_tags= '{$post_tags}', 
post_date = now(), 
post_image = '{$post_image}', 
post_content = '{$post_content}',  
post_status = '{$post_status}', 
post_category_id = '{$post_category_id}', 
SET post_author = case when post_author !=null then '{$post_author}' 
else null end, 
SET post_user = case when post_user !=null then '{$post_user}' 
else null end 
WHERE post_id = $the_great_post_id ";

我有这个HTML:

<?php  
if(null !=  $post_user) {
?>
<div class="form-group">
<label for="post_user">User</label>
<input type="text" class="form-control" name="post_user" value="<?php echo $post_user; ?>">
</div>
<?php   }
if(null !=  $post_author) {
?>
<div class="form-group">
<label for="post_author">Author</label>
<input type="text" class="form-control" name="post_author" value="<?php echo $post_author; ?>">
</div>
<?php   }  ?>

最后两个值不需要SET

$query = "
UPDATE posts 
SET post_title = '{$post_title}', 
post_tags= '{$post_tags}', 
post_date = now(), 
post_image = '{$post_image}',
post_content = '{$post_content}', 
post_status = '{$post_status}', 
post_category_id = '{$post_category_id}', 
post_author = case when post_author !=null then '{$post_author}' else null end, 
post_user = case when post_user !=null then '{$post_user}' else null end 
WHERE post_id = $the_great_post_id ";

无论如何,您不应该在SQL中使用PHP变量,这样做会使您面临SQL注入的风险。为了避免这种情况,您应该查看为PHP数据库驱动程序准备的语句和绑定参数。

当您有时

SET post_author = case when post_author !=null then '{$post_author}' 
else null end,

有几个问题,首先你不需要SET。其次,使用else null会将值设置为null,而不是保留字段的原始值。

在这个版本中,它使用。。。

post_author = case when post_author is null then '{$post_author}' else post_author end, 

这些加在一起会给你。。。

UPDATE posts 
SET post_title = '{$post_title}', 
post_tags= '{$post_tags}', 
post_date = now(), 
post_image = '{$post_image}', 
post_content = '{$post_content}', 
post_status = '{$post_status}', 
post_category_id = '{$post_category_id}', 
post_author = case when post_author is null then '{$post_author}' else post_author end, 
post_user = case when post_user is null then '{$post_user}' else post_user end 
WHERE post_id = $the_great_post_id 

需要指出的另一件事是,您应该使用准备好的语句,因为这是不安全的,并且可能会出现各种问题。

最新更新