duanhu7390
duanhu7390
2016-08-20 20:50

使用mysqli :: store_result()后获取数据

已采纳

I am selecting data from my database in the following way: As expected I get one row as result and want to extract the lat and lon data from it:

    $prep_stmt = "SELECT lat, lon FROM members WHERE id = ? LIMIT 1";   
    $stmt = $mysqli->prepare($prep_stmt);

      if ($stmt) {
        $stmt->bind_param('i', $user_id);
        $stmt->execute();
        $result = $stmt->store_result();

        if ($stmt->num_rows == 1) {
          logC("user exists");
          logC("extract lat, lon!");
        } 
      }

I tried using $stmt->fetch() and extracting it from the $result variable but without success. What is the proper way to do it?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dqyhj2014 dqyhj2014 5年前

    Since you're expecting just one result:

      if ($stmt = $mysqli->prepare($prep_stmt)) {
        $stmt->bind_param('i', $user_id);
        $stmt->execute();
        $stmt->bind_result($lat, $lon);
    
        if(($result = $stmt->fetch()) == true){
          echo "'$lat' and '$lon'";
        } elseif($result == false) {
          echo 'db error';
        } else {
          echo 'no results'; // $result == null
        }
    
    
      }
    

    If you have multiple rows, $stmt->fetch() will bind the next result to the same variables so you can do:

    while($stmt->fetch()){
      echo $lat, $lon;
    }
    

    It is just 1 way of many.. just read the documentation.

    点赞 评论 复制链接分享
  • doudong3570 doudong3570 5年前

    why don't you frame your query along with user_id and skip binding. Then you can directly execute your query and fetch result.

    $mysqli->query("SELECT lat, lon FROM members WHERE id = '".$user_id."' LIMIT 1")
    
    点赞 评论 复制链接分享