【问题标题】:how to add a if confition to a mysql query?如何在 mysql 查询中添加 if 条件?
【发布时间】:2013-04-02 18:28:39
【问题描述】:

我正在尝试向 mysql 查询添加 if 语句,以便在查询运行之前检查用户是否存在于 user_id 列中名为 ptb_users 的表中。

用户可以在其他用户墙上写字,在用户可以在用户墙上写字之前/在查询插入 ptb_wallposts 之前,我希望它检查 from_user_id = ptb_users.user_id。

我正在尝试这样做,但我的页面上到处都是语法错误,有人可以告诉我我需要如何构建这个:

 <?php 
// check if the review form has been sent
if(isset($_POST['review_content']))
{
    $content = $_POST['review_content'];
        //We remove slashes depending on the configuration
        if(get_magic_quotes_gpc())
        {
                $content = stripslashes($content);
        }
        //We check if all the fields are filled
        if($_POST['review_content']!='')
        {

如果存在(从 ptb_users 中选择 user_id,其中 user_id = @id) 开始

            {
            $sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
            mysql_query($sql, $connection);

            $_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Wall Post Added</strong> - Your comment was posted to {$profile[2]}'s wall.</div><div class=\"infobox-close4\"></div>"; 
header("Location: {$_SERVER['HTTP_REFERER']}");


        } }
}

结束 别的 开始 echo "错误用户不存在" 结束

?> 

【问题讨论】:

  • 请在你做任何事情之前阅读proper SQL escaping以避免严重损害职业生涯SQL injection bugs。不要在新代码中使用mysql_query,它很危险,已被弃用,并将从未来的 PHP 版本中删除。 PDO 只需要半个小时 to learn,所以除非你背负着一些遗留项目,否则请改用它。
  • 你有什么理由从头开始构建这个应用程序,而不是从 a popular framework 开始?您将犯无数错误,并且必须重新发明已经由专家编码、打包和记录的东西。

标签: php mysql


【解决方案1】:

这是 if 语句的示例(来自 MySQL 参考)

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF

让我解释得更好一点,我将比较 PHP 和 SQL 的 if 语句

PHP:

IF(variable > 0){
   anything..     
}

SQL:

IF variable > 0 THEN anything..

阅读更多:MySQL Reference - IF STATEMENT

【讨论】:

  • 在 MySQL 中执行IF 似乎是一个失败的原因。这是应用程序逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2013-10-11
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多