我在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);
}
但是当我叫“注册”时,它不起作用。我应该怎么称呼函数“ db_connect”?
最佳答案
您可以这样做(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);
关于php - 我如何在订单页面中调用mysqli?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15371859/