将php变量从不同的页面显示到html页面

时间:2014-08-31 02:46:18

标签: php html mysql web php-include

我在名为 navbar.php 的文件上有一个导航栏脚本。我将此文件包含在我网站所有其他页面的顶部。我现在要做的是自定义导航栏,其名称是谁登录。让我们说我有一个名为 account-process.php 的php文件,带有变量{{ 1}}。我无法在导航栏中显示此变量。

这是 account-process.php

$name = 'Bob'

我试图访问 navbar.php 中的<?PHP //VARS: gets user input from previous sign in page and assigns it to local variables //$_POST['signin-email']; //$_POST['signin-pass']; $signin_email = $_POST['signin-email']; $signin_pass = $_POST['signin-pass']; // connects to MySQL database include("config.inc.php"); $link = mysql_connect($db_host,$db_user,$db_pass); mysql_select_db($db_name,$link); // checking for user input in the table $result = mysql_query("SELECT * FROM table WHERE email = '$signin_email' AND password = '$signin_pass'"); if (mysql_num_rows($result) > 0) { // if the username and password exist and match in the table echo "Account Found"; $account_arr = mysql_fetch_array($result); // contains all the data from the user's MySQL row echo print_r($account_arr); } else { // if username and password don't match or they aren't found in the table echo "The email or password you entered is incorrect."; } ?> 变量,因此我可以在顶部显示用户的名称。我尝试在 navbar.php 中包含 account-process.php $account_arr,然后访问导航栏html中的变量,但页面只是转动当我尝试这个时,我一片空白。

navbar.php 只是为具有一些信息的固定导航栏提供了基本脚本。当我尝试将php文件包含在其中时,为什么会变成空白?

由于

1 个答案:

答案 0 :(得分:1)

将导航栏更改为PHP文件并使用会话。 -EDIT-花了很长时间才发布。保持它为PHP。

帐户process.php:

<?php
session_start();
//VARS: gets user input from previous sign in page and assigns it to local variables
//$_POST['signin-email'];
//$_POST['signin-pass'];
$signin_email = $_POST['signin-email'];
$signin_pass = $_POST['signin-pass'];

// connects to MySQL database
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name,$link);

// checking for user input in the table
$result = mysql_query("SELECT * FROM table WHERE email = '$signin_email' AND password = '$signin_pass'");   
if (mysql_num_rows($result) > 0) { // if the username and password exist and match in the table
    echo "Account Found";
    $account_arr = mysql_fetch_array($result); // contains all the data from the user's MySQL row
    echo print_r($account_arr);
    $_SESSION['name']=$account_arr['username'];
}
else { // if username and password don't match or they aren't found in the table
    echo "The email or password you entered is incorrect.";
}

?>

navbar.php:

<?php
session_start();
echo "<div><p>Hello, my name is " . $_SESSION['name'] . ".</p></div>";
?>

会话数据存储在名为PHPSESSID的cookie中,该cookie在浏览会话结束后到期。

使用session_start()功能启动或恢复会话。如果页面包含非PHP生成的HTML,则必须在<!DOCTYPE html>之前调用它。

数据存储在名为$_SESSION的超全局关联数组中。可以在任何调用session_start的页面上向此变量发送信息或从该变量发送信息。

如果您不想使用会话,可以创建自己的cookie并使用$_COOKIE超全局。

进一步信息:

http://php.net/manual/en/function.session-start.php

http://www.w3schools.com/php/php_sessions.asp

http://www.w3schools.com/php/php_cookies.asp