使用会话从查询中获取自动增量ID并将id用于另一个查询

时间:2015-07-06 15:41:11

标签: php html mysql mysqli prepared-statement

我有一个注册页面,我最初有一个查询转到名为'users'的db表。在'users'表中,我有一个名为'id'的列,它是主要的自动增量字段。

然后,我在原始文件下创建了一个新查询,该查询将发送到名为“付款状态”的数据库表。除了我尝试使用'users'表创建的'id'并将其放入'user_id'列的'payment_status'db表中之外,此查询中的所有内容都有效。它总是在其中输入0值。

if($validation->passed()) {
        $user = new User();

        $salt = Hash::salt(32);

        try {
            $user->create(array(
                'firstname' => Input::get('firstname'),
                'lastname' => Input::get('lastname'),
                'email' => Input::get('email'),
                'phone_number' => Input::get('phone_number'),
                'username' => Input::get('username'),
                'password' => Hash::make(Input::get('password'), $salt),
                'salt' => $salt,
                'joined' => date('Y-m-d H:i:s'),
                'group' => 1
            ));
            $success = "You have successfully created an account. We will notify you once the account has been approved. Then you will be able to login.";
            echo $success;

        } catch(Exception $e) {
            die($e->getMessage());
        }
    } else {
        foreach($validation->errors() as $error) {
            $error;
        }
    }

第二个问题......

if(isset($_POST['submit'])){
$id = ( isset( $_SESSION['id'] ) ? $_SESSION['id'] : "" );
$user_id = ( isset( $_SESSION['id'] ) ? $_SESSION['id'] : "" );
$firstname = Input::get('firstname');
$payment_name = "Owes";
$payment_id = 1;
$payment_amount = 0;

//Query to add user's name to owes db table

$con = mysqli_connect("localhost","root","","db");
/* check connection */
   if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
$stmt = $con->prepare("INSERT INTO payment_status (id, user_id, firstname, payment_name, payment_id, payment_amount) VALUES (?, ?, ?, ?, ?, ?)");

    if ( false===$stmt ) {
  // Check Errors for prepare
  die(' Owes DB prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('iissii', $id, $user_id, $firstname, $payment_name, $payment_id, $payment_amount);
    if ( false===$stmt ) {
      // Check errors for binding parameters
      die('Owes DB bind_param() failed: ' . htmlspecialchars($stmt->error));
    }
$stmt->execute();

    if ( false===$stmt ) {
      die('execute() failed: ' . htmlspecialchars($stmt->error));
    }   
  }

我试图从'用户'表中获取'id',就像这样......

$user_id = ( isset( $_SESSION['id'] ) ? $_SESSION['id'] : "" );

所以我想从'users'表中获取'id'并将其用于'payment_status'表中的'user_id'。

有人看到我做错了吗?

1 个答案:

答案 0 :(得分:0)

首先,您没有初始化(在您显示的代码中)新用户的SESSION_ID。您已成功将用户插入到表users中,但您没有为他启动会话。

其次,如果您想获取最后一位用户的ID,可能需要使用mysqli_insert_id