php - 我如何在订单页面中调用我的mysqli?

标签 php mysql insert

我在 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 注入(inject)非常安全,并且非常易于使用:

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/

相关文章:

php - 向我的网站发出 HTTP GET 请求以获取未知的 .php 文件。为什么以及如何防止这种情况

mysql - Amazon RDS 双向复制

SQL语法(带多个外键的INSERTS)

php - 链接到新页面时显示MySQL数据

mysql - 多个表,同一列,使用where

java - jOOQ 和桥接表

c++ - std::unordered_map 插入错误 shared_ptr c++

php - WooCommerce:自动完成已付款订单

php - 将 ID 变量传递到模态页面以通过包含此 php 页面来执行日期过滤

php - 从自身内部调用 php 方法时出现问题