如果/ else为INSERT查询

时间:2016-11-17 19:02:43

标签: php mysql sql pdo

我遇到的情况是我无法找出运行if / else查询的最佳方法。首先,我不确定是否可以使用sql语句运行if / else。以下是我目前的情况。通过这个过程,我只在查询周围添加了if / else。

基本上我想要做的是运行第一个查询,如果它等于$user_id,否则运行else,我想使user_id的值(数据库列 - 不是上面列出的变量)等于$profile_viewer

因此,简而言之,如果我能做到这一点,我只是不确定如何修改我的执行:

要包含$profile_viewer作为else查询的参数。

$select_img_stmt->execute(array($user_id));

    $user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
    $profile_viewer = $_GET['user'];
    if ($profile_viewer == $user_id) {
        $img_select_sql = "
            SELECT *
            FROM profile_img
            WHERE user_id = ?
            ORDER BY id DESC
            LIMIT 1
        ";
    }
    else {
        //echo "This is not your image";
        $img_select_sql = "
        SELECT *
        FROM profile_img
            WHERE user_id = ?
            ORDER BY id DESC
            LIMIT 1
        ";
    }
    if ($select_img_stmt = $con->prepare($img_select_sql)) {
        $select_img_stmt->execute(array($user_id));

更新代码:

    $user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
    $profile_viewer = $_GET['user'];
    if ($profile_viewer == $user_id) {
        /*$img_select_sql = "
            SELECT *
            FROM profile_img
            WHERE user_id = ?
            ORDER BY id DESC
            LIMIT 1
        ";*/
        $img_select_sql = "
            SELECT i.*
            FROM profile_img i
            WHERE user_id IN (?, ?)
            ORDER BY id DESC
            LIMIT 1;
        ";
    }
    else {
        //echo "This is not your image";
        echo $profile_viewer;
    }
    if ($select_img_stmt = $con->prepare($img_select_sql)) {
        $select_img_stmt->execute(array($user_id, $profile_viewer));

1 个答案:

答案 0 :(得分:0)

如何在一个查询中完成所有这些操作?

SELECT i.*
FROM profile_img i
WHERE user_id IN ($user_id, $profile_viewer)
ORDER BY (user_id = $user_id) DESC
LIMIT 1;

为了清楚起见,这已将变量值直接放在代码中。当然,我建议使用参数而不是使用值来修改查询字符串。

相关问题