无法检索数据库信息

时间:2013-06-13 01:20:58

标签: php mysql sql select

我需要帮助找出以下数据库查询无法正常工作的原因。我知道数据库连接很好。我也知道$referralname = $_SESSION['user_name'];正确渲染。它必须是我的代码。

我收到以下错误。也许这有助于解决这个问题。

[12-Jun-2013 21:13:54 America/New_York] PHP Warning:  mysql_query() expects parameter 1 to be string, object given in /x/x/public_html/americansolar/partner/classes/Referral.php on line 89
[12-Jun-2013 21:13:54 America/New_York] PHP Warning:  mysql_num_rows() expects parameter 1 to be resource, null given in /x/x/public_html/americansolar/partner/classes/Referral.php on line 90

P.S。我不确定while语句是否必要,因为它总是只返回一个结果???

我的代码:

// creating a database connection
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// if no connection errors (= working database connection)
if (!$this->db_connection->connect_errno) {


      $referralname = $_SESSION['user_name'];


      // get the referrer's id
      $query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
      $result = MYSQL_QUERY($query_get_referral_id);
      $numberOfRows = MYSQL_NUM_ROWS($result);
      $i = 0;
        while ($i<$numberOfRows)
        {
                  $thisId = MYSQL_RESULT($result,$i,"user_id");

                  $i++;
            }
}

我的解决方案:

$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
while($row = mysqli_fetch_array($query_get_referral_id))
  {
      $thisId = $row['user_id'];
  }

2 个答案:

答案 0 :(得分:3)

你混合mysqlimysql ......它们是两个完全不同且不兼容的界面。其次,您的$query_get_referral_id不是ID值...它是mysqli_result object。然后,您需要从该对象中提取值。

最后......不要使用mysql ...坚持使用mysqli,或使用PDO


此外,您应该使用prepared statement

$stmt = $this->db_connection->query("SELECT user_id From users WHERE user_name = ?");
$stmt->bind_param('s', $referralname);
$stmt->execute();

if($stmt->num_rows) {

   $stmt->bind_result($userId);

   while($stmt->fetch()) {
        // do something with $userId...
        // each iteration of this loop is a 
        // row of the result set, it will automatically
        // load the value of the user_id into $userId
   }
}

答案 1 :(得分:0)

我认为你应该像

一样查询
$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
$result = MYSQL_QUERY($query_get_referral_id);

好吧,你应该去

$result = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");