Mysql查询变量里面的函数

时间:2015-05-31 14:25:55

标签: php mysql sql database mysqli

<?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 } ?>

1 个答案:

答案 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);