将用户id插入表单db submission php

时间:2017-07-15 07:24:12

标签: php mysql forms

我将此问题作为之前的延续发布,因为它可能尚不清楚。

我在系统(会话)中登录运行正常 - 我想捕获userID并将id插入表单提交

<?php echo $row['userID']; ?>

我可以获取id并在页面的任何位置显示它 - 但不能将id插入隐藏的表单字段 - 寻找指示如何执行此操作。

<div class="form-group">
<div class="col-sm-10"><input type="hidden" name="userId" id="userId" 
value="<?php echo $_SESSION['userID'];?>" /></div>

session_start();
require_once 'class.user.php';
$user_home = new USER();

if(!$user_home->is_logged_in())
{
    $user_home->redirect('login.php');
}

$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['userId'] = $userId;
?>

2 个答案:

答案 0 :(得分:0)

在尝试访问会话变量之前输入session_start()。像这样:

if ( !session_id() )
{
    session_start();
}

答案 1 :(得分:0)

应该在任何HTML标记甚至空格之前先调用

session_start();

<?php 
  session_start();
  require_once 'class.user.php';
  $user_home = new USER();
  if(!$user_home->is_logged_in())
    {
        $user_home->redirect('login.php');
    }

  $stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
  $stmt->execute(array(":uid"=>$_SESSION['userSession']));
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  $_SESSION['userId'] = $userId;
?>
<!DOCTYPE html>
...

然后,您可以在调用session_start()的网站的任何位置使用该会话值。

在你的情况下,insert.php看起来像是:

<?php
session_start();

$server = "localhost"; 
$user = ""; $pass = ""; 
$dbname = ""; 
$conn = new mysqli($server, $user, $pass, $dbname); 

if($conn->connect_error){ die("Connection failed:" . $conn->connect_error); } 

$userID = $_SESSION['userId']; // Just use session value and no escaping required
$b_name = mysqli_real_escape_string($conn, $_POST['b_name']); 
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']); 
$b_area = mysqli_real_escape_string($conn, $_POST['b_area']); 
$tel = mysqli_real_escape_string($conn, $_POST['tel']);

$sql = "INSERT INTO brands (userID, b_name, name, email, b_area, tel) VALUES ('$userID', '$b_name', '$name', '$email', '$b_area', '$tel')";