0

I am currently running a MySQL query to return song titles from a database. Each song title returned displays on a different line when I echo the results. I would like to return the song titles as an array and then echo that array.

Example output: songTitle1 songTitle2 songTitle3

What I am looking for: Array ([1] => songTitle1 [2] => songTitle2) and so on

Thanks.

Here is my PHP script:

<?php

$varusername = $_POST['username'];

//connection string
$connection=mysqli_connect(<server_details>);

//check connection
if(!$connection)

{die("Failed to connect to MySql:".mysqli_connect_error());}

else
$query = "SELECT Title FROM songs WHERE Uusername='$varusername'";

$result = $connection->query($query);

if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        echo $row["Title"]. "<br>";
    }       
}

else

{die('SQL Error:'.mysqli_error($connection));}

mysqli_close($connection);

?>
1u24life
  • 3
  • 2
  • do you have a sample of what you want to see? That way I can help you load it – Forbs Apr 15 '17 at 01:18
  • Put the example output in your question, not the comments. – Sloan Thrasher Apr 15 '17 at 01:24
  • I would like for it to look like this when I echo it back: Array( [1] => songTitle1 [2] => songTitle2 [3] => songTitle3) – 1u24life Apr 15 '17 at 01:26
  • Your code is vulnerable to [**SQL injection attacks**](https://en.wikipedia.org/wiki/SQL_injection). You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky Apr 15 '17 at 01:29

1 Answers1

0

You can create an array before the while loop runs and then use array_push to add each song item (or just the title) onto it. From there use print_r($array), var_dump($array) or json_encode($array)to echo the array (as you cannot echo an array out directly).

Example code snippet:

$result = $connection->query($query);

$songsArray = array();

if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        array_push($songsArray, $row);
    }       
}

echo print_r($songsArray);
echo var_dump($songsArray);
echo json_encode($songsArray);
Optimae
  • 942
  • 1
  • 12
  • 23