我想连接php和mysql.
这是代码:
<?php
$response=array();
require_once 'C:\wamp\www\android_connect\db_connect.php';
$db=new DB_CONNECT();
$result=mysql_query("select * from product")or die(mysql_error());
if(mysql_num_rows($result)>0)
{
$response["products"]=array();
while($row=mysql_fetch_array($result))
{
$product=array();
$product["pid"]=$row["pid"];
$product["name"]=$row["name"];
$product["price"]=$row["price"];
$product["description"]=$row["description"];
array_push($response["products"],$product);
}
$response["success"]=1;
}
else
{
$response["success"]=0;
$response["message"]="No products found";
}
echo json_encode($response);
?>
Run Code Online (Sandbox Code Playgroud)
当我尝试使用WAMP安装在我的计算机上打开文件时,它会抛出以下错误:
Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in C:\wamp\www\android_connect\get_all_products.php on line 8
Warning: mysql_query(): A link to the server could not be established in C:\wamp\www\android_connect\get_all_products.php on line 8
Run Code Online (Sandbox Code Playgroud)
在我的情况下,第8行是:
$result=mysql_query("select * from product")or die(mysql_error());
Run Code Online (Sandbox Code Playgroud)
和代码的db_connect如下:
<?php
class DB_CONNECT
{
function _construct()
{
$this->connect();
}
function _destruct()
{
$this->close();
}
function connect()
{
$con=mysql_connect('localhost','root','kamani') or die (mysql_error());
$db=mysql_select_db('mobileinventory') or die (mysql_error());
return $con;
}
function close()
{
mysql_close();
}
}
?>
Run Code Online (Sandbox Code Playgroud)
要完成此处的错误,请上传其快照.

我无法解决此错误.
您必须为魔术方法添加两个下划线:
function __construct() {
$this->connect();
}
Run Code Online (Sandbox Code Playgroud)
在其他地方构造函数,因此永远不会调用connect方法.与__destruct()方法相同.
并且您不应该使用PHP的mysql扩展,因为它已被弃用并在下一个PHP版本中被删除.请改用PDO或mysqli.