Home > front end >  iterating through two columns of a mysql table with php
iterating through two columns of a mysql table with php

Time:10-19

I'm making a bot in PHP for telegram API and I'm using MYSQL. I have a table for every user that stores id, name, etc. I wrote a piece of code to send number of users and select the id of every user to make a link with it, using a loop. I was wondering how I can iterate through the names at the same time do I need another loop or I should use MYSQL code ? thanks in advance.

 $alltotal = mysqli_num_rows(mysqli_query($connect,"select id from user"));
    $ids=array();
    $idarray =mysqli_query($connect,"select id from user"); 
            api('sendmessage',[
            'chat_id'=>$chat_id,
            'text'=>"total users : $alltotal: ",
            ]);
    while($row= mysqli_fetch_array($idarray)){
        $ids[]=$row['id'];
            api('sendmessage',[
            'parse_mode'=>'MarkdownV2',
            'chat_id'=>$chat_id,
            'text'=>"(tg://user?id=".$row[0].")",
    ]);
    }

CodePudding user response:

you can select multiple columns in a single query.

Also, don't execute the query multiple times. You can use mysqli_num_rows($idarray) to get the number of rows.

$idarray = mysqli_query($connect,"select id, name from user");
$alltotal = mysqli_num_rows($idarray);
api('sendmessage',[
    'chat_id'=>$chat_id,
    'text'=>"total users : $alltotal: ",
]);
$ids_and_names = [];
while($row= mysqli_fetch_assoc($idarray)){
    $ids_and_names[] = $row;
    api('sendmessage',[
        'parse_mode'=>'MarkdownV2',
        'chat_id'=>$chat_id,
        'text'=>"(tg://user?id=".$row['id'].")",
    ]);
}
  • Related