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);
?>
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.