Retrieve current users id from database to use in

2019-06-09 16:42发布

I have a profile page where I retrieve users information.

Profile.php

  <?php
require 'core/init.php';

if(!$username = Input::get('user')) {
    Redirect::to('index.php');
} else {
    $user = new User($username);

    if(!$user->exists()) {
        Redirect::to(404);
    } else {
        $data = $user->data();
    }
    ?>

    <h3><?php echo escape($data->username); ?></h3>
    <p>Membership No: <?php echo escape($data->id); ?></p>
    <p>Full name: <?php echo escape($data->name); ?></p>
    <p>Date of birth: <?php echo escape($data->dob); ?></p>
    <p>Location: <?php echo escape($data->location); ?></p>
    <p>Join date: <?php echo escape($data->joined); ?></p>



    <?php

I want to retrieve the id of my user to insert into another table in my order page, so far I have this

oerder.php

    <?php
session_start();
require 'core/init.php';

$Band_id = mysql_real_escape_string($_POST['band']);
$user_id = $_SESSION['id'];

 $sql = "INSERT INTO orders (band_id,user_id) VALUES('$Band_id', '$user_id')";
mysql_query ($sql, $linkme)
    or die ("could not add to database");
?>

currently $user_id = $_SESSION['id']; is not placing the users id in my table orders.

I tried

<?php echo escape($data->id); ?>

and

$user_id = $_GET['id'];

but it dose not work, dose anyone know how to retrieve the users id so I can insert it into the db?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-06-09 17:02

What you could do is save user data to the session

$_SESSION['user_data'] = $user->data();

you could assign it back to $data once you check $_SESSION['user_data'] is set, else re query the model.

And session_start() should also be at the top of every file you want to hold session for.

So something like:

Profile.php

<?php
session_start();
require 'core/init.php';

if(!$username = Input::get('user')) {
    Redirect::to('index.php');
    exit;
}

if(!isset($_SESSION['user_data'])){
    $user = new User($username);

    if(!$user->exists()) {
        Redirect::to(404);
        exit;
    }

    $_SESSION['user_data'] = $user->data();
}
?>

<h3><?php echo escape($_SESSION['user_data']->username); ?></h3>
<p>Membership No: <?php echo escape($_SESSION['user_data']->id); ?></p>
<p>Full name: <?php echo escape($_SESSION['user_data']->name); ?></p>
<p>Date of birth: <?php echo escape($_SESSION['user_data']->dob); ?></p>
<p>Location: <?php echo escape($_SESSION['user_data']->location); ?></p>
<p>Join date: <?php echo escape($_SESSION['user_data']->joined); ?></p>

oerder.php

<?php
session_start();
require 'core/init.php';

if(!isset($_SESSION['user_data'])){
    Redirect::to('index.php');
    exit;
}

$Band_id = mysql_real_escape_string($_POST['band']);
$user_id = $_SESSION['user_data']->id;

$sql = "INSERT INTO orders (band_id,user_id) VALUES('$Band_id', '$user_id')";
mysql_query ($sql, $linkme)
or die ("could not add to database");
?>

also you should move over to PDO or mysqli.

查看更多
登录 后发表回答