简体   繁体   中英

PHP show records from mysql

Im blocked at following part of code...

i have config.php page, with following code inside:

<?php
// Start the session (pretty important!)
session_start();

// Establish a link to the database
$dbLink = mysql_connect('localhost', 'USER', 'PASS');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());

$dbSelected = mysql_select_db('DATABASE', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());

$isUserLoggedIn = false;  
$query      = 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';  
$userResult     = mysql_query($query);  
if(mysql_num_rows($userResult) == 1){  
$_SESSION['user'] = mysql_fetch_assoc($userResult);  
$isUserLoggedIn = true;  
}else{  
if(basename($_SERVER['PHP_SELF']) != 'index.php'){  
    header('Location: index.php');  
    exit;  
}  
}  
?>

Now i have another page, with following code inside:

<?php include_once('config.php'); ?>

<?php foreach($_SESSION['user'] as $key => $value){ ?>
<li><?php echo $key; ?> <strong><?php echo $value; ?></strong></li>
<?php } ?>

That code show me all informations stored in database, one by one..

I want to show informations, individualy in my page, something like:

<?php echo $email; ?>

etcetera..

Can someone explain me how to do that?

Thank you

You should output it like

<?php echo $_SESSION['user']['email'] ?>

assuming that 'email' is the column name in the users table.

只需解决关联数组中的相关字段:

  <?php echo $value['email';?>

Use this in the config file:

$_SESSION['user']['email'] = mysql_fetch_assoc($userResult); 

instead of this

$_SESSION['user'] = mysql_fetch_assoc($userResult); 

in your code. You can pass as many columns you want to pass from your table.

And in another page use

foreach($_SESSION['user']['email'] as $key => $value) 

instead of

foreach($_SESSION['user'] as $key => $value) 

in your code.

Remember number of columns you pass in config file, all those columns should be called in this page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM