你的問題是有點混亂,但根據我的經驗用PHP在這裏工作是我們$_POST
數據以及如何使用$_SESSION
的簡單的方法
編輯:在你的問題,我們不知道你是否知道如何使用session_start()
或不。我們也不知道程序中的文件和文件夾是如何設置的,以給出正確的答案。但通常(以及我)我創建了一個包含數據庫信息的文件,然後將該文件包含在頭文件(header.php
)中,因爲程序中通常包含header.php
。我創建的文件示例假設您使用的是mysqli
。
的config.php
if (session_status() == PHP_SESSION_NONE) {
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'my_database_name');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
header.php文件(包括本文件無處不在,你需要或者包括的config.php)
header('Content-Type: text/html; charset=iso-8859-1');
ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);//handle php errors
ob_start();//prevent header from being sent twice
require_once('config.php');
形式
require_once('header.php');
<form action="s2q2.php" method="POST">
<p>Enter your name:</p>
<input type="text" name="name"><br>
<button type="submit" name="s2q1"><span>Next </span></button>
</form>
s2q2.php
if (isset($_POST['s2q1'])) { // Retrieve form
$name = $_POST['name']; // retrieve data name
$_SESSION['name'] = $name; // pass data in session
}
使用$_SESSION
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
} else {
//do something else;
}
這段代碼是用轉移法POST到一個名爲s2q2.php網站的變量。你也可以發佈這個網站嗎? –
另外,你引用了[sessionStorage.setItem()](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem),但我不認爲'input'元素有'腳本「屬性。那有什麼打算做的? – showdev
[手冊](http://php.net/manual/en/function.session-start.php)的會話始終是一個很好的開始。 – Qirel