2017-07-31 53 views
-6

我已經嘗試使用:如何將用戶ID會話變量插入到表

$name = $_SESSION['userid']; 

,但它不工作。我也嘗試了其他答案,但無濟於事。

編輯:是的,我使用session_start();S_SESSION用戶名工作正常,但用戶ID沒有返回。

這是整個代碼,對不起,不包括它前面:

<?php 
 
session_start(); 
 
if (isset($_SESSION['username'])){ 
 
$name = $_SESSION['userid']; 
 
} 
 

 
$conn = new mysqli('localhost', 'root', '', 'phvatsim') or die ('Cannot connect to db'); 
 

 
if(isset($_POST['confirm'])) 
 
{ 
 
$name = $_SESSION['userid']; 
 
$address = $_POST ['adr']; 
 
$product = $_POST ['product']; 
 
$contact = $_POST ['con']; 
 
$email = $_POST ['ema']; 
 
$prod_qty = $_POST['prod_qty']; 
 
$cash=$_POST['cs']; 
 
$username = $_SESSION['username']; 
 
    
 
$result = mysqli_query($conn,"SELECT `stocks` FROM `products` WHERE productname = '$product'"); 
 
$message = "<script>alert('Order Placed to our Database! We will contact you on the e-mail you provided for your order sumamry, Thank You!');</script>"; 
 

 
while($row = mysqli_fetch_array($result)) 
 
{ 
 
$_SESSION['stocks'] = $row['stocks']; 
 
} 
 

 
$newstocks = $_SESSION['stocks'] - $prod_qty; 
 

 
$update = mysqli_query($conn, "UPDATE products SET `stocks` = '$newstocks' WHERE productname = '$product'"); 
 

 

 
$sql = ("INSERT INTO `transactions`(`username`, `user_id`, `customer_address`, `customer_contact`,`customer_email`, `prod_name`, `prod_qty`) VALUES ('$username','$name','$address','$contact', '$email','$product', '$prod_qty')"); 
 
$result = $conn->query($sql); 
 
    
 
if($result === TRUE){ 
 
     echo $message; 
 
    } 
 

 
} 
 
?> 
 

 

 
<meta http-equiv="refresh" content="3;URL=../index.php"/> 
 
Redirecting to home page in 3 seconds. Or redirect <a href="../index.php">now.</a>

當我使用的名稱的userid = $ _ SESSION [ '用戶ID']不放置值,但是當我用戶名時,它顯示用戶名。

+1

我看不出有任何查詢插入。 – JYoThI

+3

你確定在你需要的地方使用了'session_start()'嗎? – Difster

+0

請更新您的問題並提供更多信息。 – Dave

回答

0

首先使用

在session_start啓動會話();

存儲會話變量

$名稱= $ _ SESSION [ '用戶id'];

$ _SESSION ['userid'] = $ name;

現在執行查詢

0
  1. 使用session_start(); ....只是<?php後...
  2. 我會提供了一個例子:

    <?php session_start(); $_SESSION['my_variable'] = $myvariable; ?>

將該文件命名爲'index.php'。

現在在另一個文件:

<?php 
    session_start(); 
    $myvariable = $_SESSION['my_variable']; 
    echo "<table><tr><td>$myvariable</td></tr><table>"; 
?> 
0

我認爲你正在尋找的東西是這樣的:

<?php 
session_start(); 
if (isset($_SESSION['userid'])) { 
    $userid = $_SESSION['userid']; 
    $db_host = "localhost"; 
    $db_name = "test"; 
    $db_user = "root"; 
    $db_pass = "toor"; 
    $db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8","$db_user","$db_pass"); 
    $stmt = $db->prepare(
     "INSERT INTO `tblusers`(`id`, `userid`) VALUES (:id, :userid)" 
    ); 
    $stmt->execute(
     array(
      'id' => NULL, 
      'userid' => $userid 
     ) 
    ); 
}