我有问题。现在需要大约5个小时,我没有解决它。
如果我设置$ dbName =" dbTest"直接在php文件中,它的工作原理。 (见代码中的评论)。
如果我通过$ dbName = $ _POST [" dbName"]传递我的数据库名称,我得到以下错误: " Ther是运行查询的错误[未选择数据库]"
我不相信这个!请帮忙。
<?php
if (isset($_POST['dbName'])) {
$dbName = $_POST["dbName"];
function db_connection($query)
global $dbName;
echo $dbName //dbTest
echo strcmp ($dbName,'dbTest') //always 0 (equal)
// $dbName ='dbTest' // if I comment this out, it works!
$db = new mysqli('localhost', 'user', 'password', $dbName);
if ($db->connect_errno > 0) {
die('Unable to connect to database [' . $db->connect_error . ']');
}
if (!$result = $db->query($query)) {
die('There was an error running the query [' . $db->error . ']');
}
}
}
?>
答案 0 :(得分:1)
试试这个:
<?php
$dbName = $_POST["dbName"];
$query = 'SELECT * FROM TABLE'; // query example or if comes via [$_POST][1] $query = $_POST['query'];
$connection = db_connection($query, $dbName);
function db_connection($query $dbName) {
global $dbName;
echo $dbName //dbTest
echo strcmp ($dbName,'dbTest') //always 0 (equal)
// $dbName ='dbTest' // if I comment this out, it works!
$db = new mysqli('localhost', 'user', 'password', $dbName);
if ($db->connect_errno > 0) {
die('Unable to connect to database [' . $db->connect_error . ']');
}
if (!$result = $db->query($query)) {
die('There was an error running the query [' . $db->error . ']');
}
}
?>
答案 1 :(得分:0)
添加isset
以验证您是否正在发送值:http://php.net//manual/en/function.isset.php
<?php
if (isset($_POST['dbName'])) {
$dbName = $_POST["dbName"];
function db_connection($query)
global $dbName;
echo $dbName //dbTest
echo strcmp ($dbName,'dbTest') //always 0 (equal)
// $dbName ='dbTest' // if I comment this out, it works!
$db = new mysqli('localhost', 'user', 'password', $dbName);
if ($db->connect_errno > 0) {
die('Unable to connect to database [' . $db->connect_error . ']');
}
if (!$result = $db->query($query)) {
die('There was an error running the query [' . $db->error . ']');
}
}
}
?>
希望这会有所帮助:)