使用 MySQL 设置 Web 应用程序

Setting up a web application using MySQL

我不熟悉设置基于 Web 的应用程序。我有一个带有数据库的 MySQL 设置的服务器。该网站是 运行 我的登录网页。目前,我有用户使用 MyPhpAdmin 进行设置,这很快就会证明很麻烦。更重要的是,一旦我 运行 命令 "$connection = mysqli_connect('1.2.3.4', $username, $password, 'databasename');",变量 $connection 就不会继续存在于其他 PHP 脚本中,即使我将它设置为全局并尝试 [=13] =]

是否有使用单个帐户登录 PHP 代码然后使用数据库 table 管理用户的标准做法?出于安全原因,我对这种方法有点怀疑。

我想你误解了$_GLOBALS。一旦你在函数或 class 之外声明了一个变量,它就已经在全局注册了。

<?php


$foo = "bar";

function foo(){
    global $foo;
    echo $foo;
}

echo $_GLOBALS["foo"]; // Output: bar
foo(); // Output: bar
  • 您可以阅读有关 PHP GLOBALS here 的更多信息。

我建议你不要使用 mysqli,最好像这样使用 PDO 连接

$Engine = 'mysql';
$Host = 'YOUR_HOST';
$Name = 'DB_NAME';
$User = 'YOUR_USER';
$Pass = 'YOUR_PASS';
$Charset = 'YOUR_CHARSET_DB';

$Connection = new PDO($this->Engine.':host='.$this->Host.';dbname='.$this->Name.';$this->Charset', $this->User, $this->Pass);

你可以这样使用

try {
    $Connection = new PDO('mysql:host=localhost;dbname=prueba', $User, $Pass);
    foreach($Connection ->query('SELECT * from FOO') as $fila) {
        print_r($fila);
    }
    $Connection = null;
} catch (PDOException $e) {
    print "¡Error!: " . $e->getMessage() . "<br/>";
    die();
}

查询完成后PDO连接关闭不需要手动关闭