如何使用class从select查询中获取结果

时间:2018-05-24 10:11:25

标签: php mysqli

我正在尝试用class学习select查询。 下面是index.php,它有一个显示结果的表单,我在PHP中调用类操作,这是在operations.php中

<?php
        session_start();
        include('operations.php');
        $userprofileobj = new operations();
        $userprofileobj->showuserprofile($_SESSION['user_email']);
        $row = $userprofileobj->fetch_assoc();
?>

<form class="form-horizontal" method="post" action="#" name="number_validate" id="number_validate" >
          <div class="control-group">
            <label class="control-label">Admin Name</label>
            <div class="controls">
              <input type="text" name="min" id="min"  value="<?php echo $row['user_name']; ?>" required />
            </div>
          </div>
          <div class="control-group">
            <label class="control-label">User Email</label>
            <div class="controls">
              <input type="text" name="max" id="max" value="<?php echo $row['user_email']; ?>" required />
            </div>
  <div class="form-actions">
            <input type="submit" value="Update" class="btn btn-success">
          </div>
   </form>

operations.php是:

class operations{

public $user_email;
public $error;
public $con;


public function __construct()
{       
    $this->con = new mysqli("localhost","root","","admin_with_oops");
}
public function showuserprofile($user_email)
{
    $result = $this->con->query("select * from user_table where user_email='$user_email'");
    if($result->num_rows > 0)
    {

        return $result;
    }
    else
    {
        $this->error = "User not exist";
    }
}
 }

我是正确的吗?如果是,那么上面的代码有什么问题?

错误是:致命错误:在第16行的F:\ xampp \ htdocs \ admin_with_oops \ HTML \ index.php中调用未定义的方法操作:: fetch_assoc()

1 个答案:

答案 0 :(得分:1)

$userprofileobjoperations类的一个实例。它没有fetch_assoc()方法。你应该替换

$userprofileobj->showuserprofile($_SESSION['user_email']);
$row = $userprofileobj->fetch_assoc();

$row = $userprofileobj->showuserprofile($_SESSION['user_email'])->fetch_assoc();

或者您可以将结果分配给变量,然后调用其上的fetch_assoc()函数:

$result = $userprofileobj->showuserprofile($_SESSION['user_email']);
$row = $result->fetch_assoc();