簡體   English   中英

我如何在訂單頁面中調用我的mysqli?

[英]How I call my mysqli in order page?

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

db_connect()返回$link ,或者在db_connect()創建$link全局

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);
}

你可以這樣做(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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM