我在db.php页面中有这个:
function db_connect(){ $link = new mysqli(localhost, user, pass, table); }
这是在其他页面中:
require_once("db.php");
function register($username, $email, $password){
global $link;
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}
但是当我调用“register”时它不起作用。我该如何调用函数“db_connect”?
答案 0 :(得分:1)
让db_connect()
返回$link
,或将$link
全局转换为db_connect()
function db_connect() {
return new mysqli(localhost, user, pass, table);
}
function register($username, $email, $password) {
$link = db_connect();
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}
答案 1 :(得分:1)
你可以这样做(PDO连接):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
然后初始化变量:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
现在您可以通过
访问您的数据库了$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
如果需要,您可以将其变为全局变量。
$GLOBALS['db'] = $db;
请注意,这是pdo,这是您的案例的PDO数据库操作的一个示例,请注意,这使用预准备语句,因此非常安全的sql注入,并且非常容易使用:
function register($username, $email, $password){
$query = "INSERT INTO user (username, password, email) VALUES (:username, :password, :email)"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':username' => $username,
':password' => $password,
':email' => $email
)); // Here you insert the variable, by executing it 'into' the prepared query.
if($result)
{
return true;
}
return false
}
你可以这样称呼它:
$registerSuccess = register($username, $email, $password);