gpt4 book ai didi

php - 无法检索数据库信息

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:05 25 4
gpt4 key购买 nike

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

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

最佳答案

你在混合 mysqlimysql ...它们是两个完全不同且不兼容的接口(interface)。其次,您的 $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
}
}

关于php - 无法检索数据库信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17077871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com