0

我在 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”?

4

2 回答 2

1

db_connect()返回$link, 或使$link全局 indb_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);
}
于 2013-03-12T20:51:55.957 回答
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);
于 2013-03-12T20:53:11.370 回答