0

我需要帮助弄清楚为什么以下数据库查询不起作用。我知道数据库连接很好。我也知道$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

PS我不确定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'];
  }
4

2 回答 2

3

您正在混合mysqlimysql ...它们是两个完全不同且不兼容的接口。其次,你$query_get_referral_id的不是一个 id 值……它是一个mysqli_result对象。然后,您需要从该对象中提取值。

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


此外,您应该为此使用准备好的语句

$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
   }
}
于 2013-06-13T01:24:58.123 回答
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."';");
于 2013-06-13T01:27:20.360 回答