【问题标题】:how to use 2 inserts in the same record PHP SQL如何在同一条记录中使用 2 个插入 PHP SQL
【发布时间】:2020-09-30 04:47:52
【问题描述】:

我正在使用下面的代码从另一个表中获取用户 ID 并在该表中创建一个新记录。在同一行中有一个名为 action 的字段,我想在该字段中为同一记录插入“登录”或“注销”。

我的问题是我不确定如何在没有数据库创建新空行的情况下将其与下面的代码合并

try{
    // check for user ID in sessions table and apply to new session_log record

    $sql = "INSERT INTO session_logs (USER_ID, first, last, email) SELECT USER_ID, first, last, email FROM sessions WHERE email=:email";

    $stmt = $pdo->prepare($sql);

    // Bind parameters to statement
        $stmt->bindParam(':email', $_REQUEST['email']);


    // Execute the prepared statement
    $stmt->execute();
} catch(PDOException $e){
    die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

【问题讨论】:

    标签: php mysql sql database


    【解决方案1】:

    不幸的是,Table and Column names CANNOT be replaced by parameters in PDO 所以你不能只将 SELECT 列绑定为一个值或类似的值,但是,你可以自己操作字符串以添加所需的值,如下所示:

    $action = 'Log-In'; // if you get this value from user input in any way, be sure to sanitize it with something like `mysqli_real_escape_string`
    
    $sql = "INSERT INTO session_logs (USER_ID, first, last, email, action) SELECT USER_ID, first, last, email, '$action' FROM sessions WHERE email=:email";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 2012-10-22
      • 2021-11-25
      相关资源
      最近更新 更多