我目前正在通过一个站点并替换所有用于返回mysql_fectch_array()结果的函数,这些函数放在其他地方的while循环中。我试图让它们以相同的格式返回相同的数据,但是使用mysqli预处理语句输出。我已成功使用下面的代码为单行结果生成相同的格式化输出。
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT * FROM email_setting WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $this->user);
$stmt->execute();
$stmt->bind_result(
$row['email_id'],
$row['user_id'],
$row['news'],
$row['new_message'],
$row['new_friend'],
$row['rule_assent'],
$row['agreement_ready'],
$row['agreement_all_assent'],
$row['time_cap'],
$row['donations']
);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $row;
}
但是如何在返回多行时让这段代码生效?我希望它能产生与我写过的相同的结果:
返回mysql_fetch_array($ result);
有可能吗?
答案 0 :(得分:0)
考虑以下调整,将查询结果传递给关联数组:
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT email_id, user_id, news, new_message,
new_friend, rule_assent, agreement_ready,
agreement_all_assent, time_cap, donations
FROM email_setting
WHERE user_id = ? ");
$stmt->bind_param("i", $this->user);
$stmt->execute();
// CREATE RETURN ARRAY
$row = [];
// OBTAIN QUERY RESULTS
$result = $stmt->get_result();
// ITERATE THROUGH RESULT ROWS INTO RETURN ARRAY
while ($data = $stmt->fetch_assoc()) {
$row[] = $data;
}
$stmt->close();
return $row;
}
您会注意到我明确选择了查询字段,以避免查询结果出现不确定的循环。
答案 1 :(得分:0)
好的,我已经设法在不使用get_result()
的情况下使其工作这就是我在Parfait和Example of how to use bind_result vs get_result
的帮助下做到的function saved_rules($user){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT R.rule_id, R.rule_title
FROM Savedrules S
LEFT JOIN Rule R
ON S.saved_rule_id = R.rule_id
WHERE S.saved_user_id = ?");
$stmt->bind_param("i", $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $rule_title);
while ($stmt->fetch()) {
$result[] = Array("rule_id"=>$id,"rule_title"=>$rule_title);
}
$stmt->free_result();
$stmt->close();
return $result;
}
它与使用mysql_fetch_array()的输出不完全相同,所以在使用它时我必须将循环更改为:
foreach($saved_rules AS $row){}
来自
while ($row = mysql_fetch_array($saved_rules){}