最初我试图使用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
每当我尝试调用它时,它就会给我一个错误:"Notice: Trying to get property of non-object"。目前我在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()