我刚刚计划制作一个程序,我需要使用DBHost,DBUser,DBPassword和DBName连接USER的数据库,以便在MySQL服务器上保存未来所需的值。 为此,我写了这样的代码:
<?php session_start(); ?>
<?php
require('functions.php');
iq_add_style( 'DBConForm_Styles' , 'assets/scripts/css/iq_styles' , 'stylesheet' , 'css' );
function IQ_DB_Form(){
?>
<form id="iq-dbconform" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<label>Server Host: <input type="text" maxlength="15" placeholder="localhost" name="host-name" /></label>
<label>Database User: <input type="text" maxlength="15" placeholder="root" name="user-name" /></label>
<label>Password: <input type="password" maxlength="15" placeholder="User Password" name="user-pass" /></label>
<label>Name of the Database: <input type="text" maxlength="20" placeholder="developing_house" name="db-name" /></label>
<input type="submit" value="Connect" name="dbconbtn" /> <input type="reset" value="Reset" name="dbresetbtn" />
</form>
<?php
}
IQ_DB_Form();
// Database connection
$dbhost = $_POST['host-name'];
$dbuser = $_POST['user-name'];
$dbpass = $_POST['user-pass'];
$dbname = $_POST['db-name'];
$db_details = array(
'host' => $dbhost,
'user' => $dbuser,
'password' => $dbpass,
'dbname' => $dbname,
);
$IQcon = mysqli_connect($db_details['host'],$db_details['user'],$db_details['password'],$db_details['dbname']);
// Check connection
if (mysqli_connect_errno())
{
echo "Looks like an Error connecting IQubex Database: " . mysqli_connect_error();
}
// Store Values in Session
foreach ($_POST as $key => $value) {
${$key} = $value;
$_SESSION[$key] = $value;
}
echo $_SESSION['db-name'];
echo $_SESSION['user-pass'];
echo $_SESSION['user-name'];
// Perform queries
if ($IQcon){
mysqli_query($IQcon,"CREATE TABLE `Persons` (
`FirstName` varchar(30) NOT NULL,
`LastName` varchar(60) NOT NULL,
`Age` int(255) NOT NULL,
);");
mysqli_query($IQcon,"CREATE TABLE `MadBoys` (
`FirstName` varchar(30) NOT NULL,
`LastName` varchar(60) NOT NULL,
`Age` int(255) NOT NULL,
);");
mysqli_close($IQcon);
}
else{
echo "There seems a problem with your server.";
}
?>
&#13;
我已在会话中保存了数据库配置表单值,因此当我写echo $_SESSION['db-name']
时,将打印插入的数据库名称。但是当页面重新加载,再回到页面上,或类似的东西时,所有的值都会重置!因此,我不希望我的用户一次又一次地连接数据库。我希望它能够永远保存,以便我可以为下一个程序步骤工作。
答案 0 :(得分:0)
您可以检查会话中是否保存了值。如果它们不连接到db,则获取值并将它们保存在DB中:
请参阅以下示例:
session_start();
if(isset($_SESSION['stored-in-db']))
{
//USE SESSION VALUES
}
else
{
$dbhost = $_POST['host-name'];
$dbuser = $_POST['user-name'];
$dbpass = $_POST['user-pass'];
$dbname = $_POST['db-name'];
$db_details = array(
'host' => $dbhost,
'user' => $dbuser,
'password' => $dbpass,
'dbname' => $dbname,
);
$IQcon = mysqli_connect($db_details['host'],$db_details['user'],$db_details['password'],$db_details['dbname']);
foreach ($_POST as $key => $value)
{
$_SESSION[$key] = $value;
}
$_SESSION['stored-in-db] = true;
}
答案 1 :(得分:0)
尝试添加
session_start();
在您使用会话的页面顶部。