<?php
function get_msg($c_id_fk) {
$messages = $sql->query("SELECT * FROM conversation_reply WHERE c_id_fk = $c_id_fk");
return $messages;
}
?>
如何使用函数中的变量查询mysql数据库。我使用$ sql = new MySQLi($ host,$ username,$ password,$ database);连接我的数据库,但它肯定是连接的,因为我可以不使用函数查询它。
<?php $messages = get_msg(1);
foreach ( $messages as $message ) {
?>
<!-- Individual Message -->
<div class="bubble <?php
if ( $message['user_id_fk'] == $uid ) {
echo "from-me";
}
else {
echo "from-them";
}?>">
<?php echo $message['c_id_fk'];?><?php echo $message['user_id_fk'];?><?php echo $message['reply'];?>
</div>
<!-- End Individual Message -->
<div class="clear"></div>
<?php } ?>
答案 0 :(得分:2)
$sql
。您需要将$sql
传递给函数,避免使用全局变量。阅读 variable scope 。
function get_msg($sql, $c_id_fk) {
// Protect against injections
$c_id_fk = (int) $c_id_fk;
$messages = $sql->query("SELECT * FROM conversation_reply WHERE c_id_fk = $c_id_fk");
return $messages;
}
get_msg($sql, 1);