简体   繁体   English

PHP将MySQL查询结果读入数组

[英]PHP reading MySQL query results into an array

I am currently running a MySQL query to return song titles from a database. 我目前正在运行MySQL查询,以从数据库返回歌曲名称。 Each song title returned displays on a different line when I echo the results. 当我echo显结果时,返回的每个歌曲标题将显示在不同的行上。 I would like to return the song titles as an array and then echo that array. 我想将歌曲标题作为数组返回,然后echo该数组。

Example output: songTitle1 songTitle2 songTitle3 输出示例:songTitle1 songTitle2 songTitle3

What I am looking for: Array ([1] => songTitle1 [2] => songTitle2) and so on 我正在寻找的是:数组([1] => songTitle1 [2] => songTitle2),依此类推

Thanks. 谢谢。

Here is my PHP script: 这是我的PHP脚本:

<?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. 您可以在while循环运行之前创建一个array ,然后使用array_push将每个歌曲项(或只是标题)添加到array 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). 从那里使用print_r($array)var_dump($array)json_encode($array)回显数组(因为您不能直接回显数组)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM