[英]How do I pull data from the my database using a php function
This is what I have in my main page: 这是我主页上的内容:
$foo = new Foo();
$strQry=$foo->Client();
$user_data=mysql_fetch_object($user_res);
echo $user_data->clientid;
This is what I have in my class file: 这是我的班级文件中的内容:
class Foo
{
function Client()
{
$strQry = "SELECT clientid FROM users";
$user_res = mysql_query($strQry) or die("Unable to select, Error: ".mysql_error());
return $user_res;
}
}
I am not very good at using classes and functions with PHP and so I'm getting this error "Unable to select, Error: Access denied for user 'nobody'@'localhost' (using password: NO)" 我不太擅长在PHP中使用类和函数,因此出现此错误“无法选择,错误:用户'nobody'@'localhost'的访问被拒绝(使用密码:NO)“
Any help would be greatly appreciated! 任何帮助将不胜感激!
It looks like you are not even making a connection to the database. 看来您甚至都没有与数据库建立连接。
Here's a nice step-by-step walk through, that should show you how to connect to a mysql database using either mysqli or pdo, which are both more safe ways to talk to mysql. 这是一个很好的分步介绍,应该向您展示如何使用mysqli或pdo连接到mysql数据库,这两种方式都是与mysql进行通信的更安全的方法。
There aa number of issues with your code: 您的代码有很多问题:
mysql_*
functions. mysql_*
函数。 They are deprecated. mysqli
or PDO
. mysqli
或PDO
。 Client()
method call. Client()
方法调用中返回数据库结果。 But you are not using the variable your returned the results into. This code: 这段代码:
$strQry=$foo->Client();
$user_data=mysql_fetch_object($user_res);
Should be: 应该:
$strQry=$foo->Client();
$user_data=mysql_fetch_object($strQry);
because $strQry
gets the result set resource. 因为
$strQry
获取结果集资源。
mysql_fetch_object()
once. mysql_fetch_object()
。 You could have any number of rows in the result set based on your query. mysql_fetch_object()
on each row. mysql_fetch_object()
。 Perhaps something like this: 也许是这样的:
$user_data= array();
while($row = mysql_fetch_object($strQry)) {
$user_data[] = $row;
}
mysql_*
functions, you might at least want to get in the habit of passing the DB connection as a parameter in your functions, to make it clear which DB connection you are working with. mysql_*
函数进行mysql_*
,则可能至少要养成将DB连接作为函数中的参数传递的习惯,以明确使用的是哪个DB连接。 So do something like: 因此,请执行以下操作:
mysql_query($strQry, $dbConn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.