最后第一次跳进一些PHP,我写了这个程序,我被卡住了。我在整个地方搜索了大约2个小时才找到解决方案。
基本上我正在连接到我的本地数据库,并尝试从我的“歌曲”表中获取所有行,并按名称显示它们。而不是得到他们的名字,我收到一条通知,上面写着“注意:第47行的C:\ xampp \ htdocs \ musiclibrary \ index.php中的数组到字符串转换”
我目前的输出如下:
Title Artist Genre
Array Array Array
Array Array Array
Array
然后我的代码就是......
<?php
// Require configuration file
require_once 'config.php';
// Connect to the database
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
// Check for database connection error
if(!$db_server)
{
die("Unable to connect to MySQL: " . mysql_error());
}
// Select a database
// The mysqli_select_db() function is used to change the default database for the connection.
mysqli_select_db($db_server, $db_database);
$prompt = array('Story title', 'Time', 'Person');
$prompt = array('Story title', 'Time', 'Person');
// Page title
echo "<h1>My Music Collection</h1>";
// Get music collection
$query = "SELECT * FROM songs";
$result = mysqli_query($db_server, $query);
$rows = mysqli_num_rows($result);
// If rows exist
if($rows > 0)
{
// Create HTML table
echo "<table>";
echo "<tr><th>Title</th><th>Artist</th><th>Genre</th></tr>";
// Loop through each row in the database table
for($j = 0; $j < $rows; $j++)
{
// Build HTML table row
//PROBLEM LIES HERE ON THESE MYSQL_FETCH_ASSOC PARTS
echo "<tr>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'title') . "</td>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'artist') . "</td>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'genre') . "</td>";
echo "</tr>";
}
echo "</table>";
}
// If there are no songs in the database table
else
{
echo "There are currently no songs on file.";
}
?>
输出数据库中行名称的任何解决方案?谢谢!
答案 0 :(得分:1)
使用以下代码替换您的代码
显示表格行中的值
$values = mysqli_fetch_assoc($result);
echo "<tr>";
echo "<td>" . $values ['title']. "</td>";
echo "<td>" . $values ['artist'] . "</td>";
echo "<td>" . $values ['genre')]. "</td>";
答案 1 :(得分:1)
你需要循环 mysqli_fetch_assoc 函数来计算行然后循环行结果以获取值
以下是代码:
if($rows > 0){
echo "<table>";
echo "<tr><th>Title</th><th>Artist</th><th>Genre</th></tr>";
// Loop through each row in the database table
while($row = $result->mysqli_fetch_assoc()){
echo "<tr>";
foreach($row as $key => $value){
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
希望它有所帮助!
答案 2 :(得分:0)
mysqli_fetch_assoc()函数只接受一个参数。
数组mysqli_fetch_assoc(mysqli_result $ result)
正确的方法是:
$query = "SELECT * FROM songs";
if ($result = mysqli_query($db_server, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "</tr>";
}
mysqli_free_result($result);
}