最初,我试图使用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(mysql_error());
while($row = mysql_fetch_array($result)) {
$row = array_map('stripslashes', $row);
$data[] = $row;
}
return $data;
}
view.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
:
尝试:
echo profileload($login_session)[0]['fullname']; // retrieve fullname of current login user
echo profileload($login_session)[0]['username']; // retrieve username of current login user
echo profileload($login_session)[0]['contactno']; // retrieve contactno of current login user
echo profileload($login_session)[0]['email']; // retrieve email of current login user
更好的方法是不调用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
如果要获取为对象,请使用mysql_fetch_object()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句