gpt4 book ai didi

php - Mysql PHP 拒绝用户 '' @'localhost' 访问数据库

转载 作者:行者123 更新时间:2023-11-29 02:25:53 25 4
gpt4 key购买 nike

使用以下代码,可以成功连接数据库。但是,当尝试使用函数 'executeNonQuery' 执行查询时,出现错误 { Access denied for user ''@'localhost' to database 'photobook' }。用户拥有全部权限,但奇怪的是查询“show grants”不会显示该事实。但是,当在 mysql workbench 的 GUI 中查看用户权限时,它是。可能是什么问题?我什至使用了 root,但查询被拒绝并出现相同的错误。用户可以连接,但不能发出查询。

文件:class.database.php

<?php
class Database {
function __construct(){
}

public function connect($host, $user, $pass){
$dbcnct = mysqli_connect($host, $user, $pass);
if(!$dbcnct){
die("Couldn't Connect: " . mysql_error());
}else{
echo "Connected Successfully";
}
}

public function disconnect(){
mysql_close($dbcnct);
if(!$dbcnct){
echo "Disconnected Successfully";
}
}

public function executeNonQuery($database, $sql){
mysql_select_db($database);
$retval = mysql_query($sql, $dbcnct);
if(!$retval){
die("Couldn't Update Data: " . mysql_error());
}
echo "Update Successful";
}
}
?>


<?php
include 'class.database.php';
$db = new Database;
$db->connect("localhost", "user", "pass");
$userdata=$_GET['data'];
$index=$_GET['index'];
echo $index . "<br/>";
foreach($userdata as $data){
$sql = "update photobook set photoName='" . $data . "' where photoPosition=" . $index;

$db->executeNonQuery("photoBook", $sql);
echo $data . "<br/>";
}
$db->disconnect();

?>

最佳答案

您的 $dbcnct 变量只为您使用它的函数定义,而不是为整个类定义。您需要使用类变量,以便您可以在不同的函数中共享变量:

<?php
class Database
{
public $dbcnct;

function __construct()
{
// Nothing
}

public function connect($host, $user, $pass){
$this->dbcnct = mysqli_connect($host, $user, $pass);
if(!$this->dbcnct){
die("Couldn't Connect: " . mysql_error());
}else{
echo "Connected Successfully";
}
}

public function disconnect(){
mysql_close($this->dbcnct);
if(!$this->dbcnct){
echo "Disconnected Successfully";
}
}

public function executeNonQuery($database, $sql){
mysql_select_db($database);
$retval = mysql_query($sql, $this->dbcnct);
if(!$retval){
die("Couldn't Update Data: " . mysql_error());
}
echo "Update Successful";
}
}
?>

现在您需要做的就是:

$database->connect("host", "user", "pass");
$database->executeNonQuery("database", "sql");

但首先你需要修复 mysql_ 和 mysqli_ 的混淆 :)

关于php - Mysql PHP 拒绝用户 '' @'localhost' 访问数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22191505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com