首页 > 解决方案 > PHP数组不在foreach循环之外打印

问题描述

我正在处理这个脚本的主要功能是从数据库中用逗号获取一个数字,并在 curl 中使用它来发送带有 api 的短信。

if(isset($_POST['getnumber']))

    {
        $matchid2 = $_POST['matchid2'];
        //connect db
        require_once __DIR__ . '/../db_connect.php';
        $db = new DB_CONNECT();
        $con = $db->connect();        
        $results = $con->query("SELECT DISTINCT ur.mobile FROM matchmst mst INNER JOIN matchdetail dtl on mst.matchid=dtl.matchid INNER JOIN user ur on ur.userid=dtl.userid WHERE mst.matchid = '$matchid2'");
        // look through query
        $datas = array();

        while($row = $results->fetch_assoc()){
                $datas[] = $row;                                
            }

        foreach ($datas as $data) {
            $mobiles = $data['mobile'].",";
        }

    }

当我试图在 html 中回显这一点时,我只从数组中获取一个值,即 84*******4,并且为空白,但我想在 html 中打印该 nubers 的完整行

<div class="form-group">
        <?php echo '<label for="msg">'.$mobiles.'</label>'; ?>

</div>

那么我该如何解决这个pelase帮助。提前致谢。

标签: phparraysapisms

解决方案


在读取数据的同时构建字符串比在更多循环中操作它更容易......

    $results = $con->query("SELECT DISTINCT ur.mobile FROM matchmst mst INNER JOIN matchdetail dtl on mst.matchid=dtl.matchid INNER JOIN user ur on ur.userid=dtl.userid WHERE mst.matchid = '$matchid2'");
    // look through query
    $mobiles = "";

    while($row = $results->fetch_assoc()){
            $mobiles .= $row['mobile'] . ",";                                
    }
    // Remove trailing , if needed
    $mobiles = substr($mobiles, 0, -1);

您还应该考虑使用准备好的语句来提高站点的安全性。


推荐阅读