Home » Php » Get all "username" and "id" in MySQL database and split using php

Get all "username" and "id" in MySQL database and split using php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have MySQL database like this.

id........username  
 1 .......rap
 2 .......dafy
 3 .......kay

I want to make them like thies

username-id,username-id,use...

for ex.

rap-1,dafy-2,kay-3

the code should use the param to prevent the sql injection, but i have no idea how to write code.

How to&Answers:
<?php
$mysqli = new mysqli("database","my_user","my_password","my_db");

if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}

// Obviously change this to match yours
$sql = "SELECT GROUP_CONCAT(CONCAT(username , '-',id) SEPARATOR ',') as grp FROM table";
$result =  $mysqli->query($sql);
$final_result = []
while($row = $result->fetch_assoc())
{
    array_push($final_result, $row['grp']);
}


$mysqli -> close();
?>

Answer:

Use this Query for a result

SELECT GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',')
FROm table1;

Result

GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',')
rap-1,dafy-2,kay-3 .

Example PHP Code wuth PDO

<?php
  try {
    $pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
  } catch (PDOException $e) {
    echo 'Verbindung fehlgeschlagen: ' . $e->getMessage();
  }

  $sql = "SELECT GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',') user FROM Table1";
  foreach ($pdo->query($sql) as $row) {
   echo $row['user']."<br />";
  }
  $pdo ->close(); 
?>