php函数从db返回并从分离的视图文件调用值
最初,我试图使用php函数从数据库中提取数据 function.phpphp函数从db返回并从分离的视图文件调用值,php,mysql,arrays,function,Php,Mysql,Arrays,Function,最初,我试图使用php函数从数据库中提取数据 function.php function profileload($loginuser) { $data = array(); $result = mysql_query("SELECT fullname,username,contactno,email FROM account WHERE username = '" . mysql_real_escape_string($loginuser) . "'") or die(mysq
function profileload($loginuser) {
$data = array();
$result = mysql_query("SELECT fullname,username,contactno,email FROM account WHERE username = '" . mysql_real_escape_string($loginuser) . "'") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$row = array_map('stripslashes', $row);
$data[] = $row;
}
return $data;
}
php,一个一个检索我想要的数据的文件
echo profileload($login_session)->fullname; // retrieve fullname of current login user
echo profileload($login_session)->username; // retrieve username of current login user
echo profileload($login_session)->contactno; // retrieve contactno of current login user
echo profileload($login_session)->email; // retrieve email of current login user
每当我试图调用它时,它都会给我一个错误:“注意:试图获取非对象的属性”。目前我正在view.php上使用这段代码,它工作得很好,只是想知道我是否可以像上面的代码那样缩短代码
$info = profileload($login_session);
foreach($info as $data) {
$fullname= $data['fullname'];
$username= $data['username'];
$contactno= $data['contactno'];
$email= $data['email'];
}
echo $fullname; etc...
您的函数
profileload()
返回array
非object
:
尝试:
更好的方法是不要调用函数4次,只调用一次,然后反复使用。如果您调用函数4次,它将遇到4次相同的查询。使用以下内容:
$user = profileload($login_session);
echo $user[0]['fullname']; // retrieve fullname of current login user
echo $user[0]['username']; // retrieve username of current login user
echo $user[0]['contactno']; // retrieve contactno of current login user
echo $user[0]['email']; // retrieve email of current login user
如果要提取为对象,请使用函数返回的数组。你不应该把/access当作一个对象来对待。对不起,我对php很陌生,如何让它返回一个对象并查看全名作为示例?更新了我的答案。看一看
$user = profileload($login_session);
echo $user[0]['fullname']; // retrieve fullname of current login user
echo $user[0]['username']; // retrieve username of current login user
echo $user[0]['contactno']; // retrieve contactno of current login user
echo $user[0]['email']; // retrieve email of current login user