0

I am working on this script main function is to take a numbers from database with commas and use it inside curl to send a sms with 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'].",";
        }

    }

When i tried to echo this in html i am only getting one value from array i.e. 84*******4, and blank but i want to print complete row of that nubers in html

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

</div>

So how can i solve this pelase help. Thanks in advance.

  • You could try using `GROUP_CONCAT()` in your SQL to retrieve the value directly from your SQL (https://stackoverflow.com/questions/3083499/mysql-distinct-on-a-group-concat). – Nigel Ren Mar 28 '20 at 07:52

1 Answers1

2

It would be easier to build the string whilst reading the data than to manipulate it in more loops...

    $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);

You should also look at using prepared statements to improve security of your site.

Nigel Ren
  • 51,875
  • 11
  • 34
  • 49
  • if OP want only mobile number then he need to do `fecth_all(MYSQLI_ASSOC)` to get all numbers at-once and use `implode()` to show it. then no need of `while` as well as `foreach()` – Serving Quarantine period Mar 28 '20 at 07:58
  • @AnantSingh---AlivetoDie - `fetch_all()` internally uses a loop, `implode()` uses another loop, `array_column()` uses another loop. Just because it is 1 command it doesn't mean that it is more efficient. Also you create 2 new arrays on top of all the arrays for each row and use more memory than just using 1 loop. – Nigel Ren Mar 28 '20 at 08:00