我试图根据数据库中的数据进行简单的youtube搜索。数据被放入一个表,我想有歌曲的名字是一个链接到youtube搜索那首歌。我们的想法是在youtube搜索URL的末尾添加艺人名和歌曲名。
问题是当艺术家的名字或歌曲的名字超过一个单词时,搜索只包括第一个单词。我现在使用下面的代码:
<table class="table table-striped table-hover table-bordered">
<th>Song Name</th>
<th>Artist</th>
<?php
// Create connection
$con=mysqli_connect("localhost","root","checkout","Music Database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MusicDB");
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><a href=https://www.youtube.com/results?hl=en&q=".$row['Song']."+".$row['Artist'].">".$row['Song']."</a></td>";
echo "<td>".$row['Artist']."</td>"."</tr>";
}
mysqli_close($con);
?>
</table>
例如,如果歌曲是"Michael Jackson"的"Beat It",它只会在搜索中添加"Beat"。
如果歌曲是"Thriller",它会添加"Thriller+Michael"。
如果我添加"Maclemore"的歌曲"Thrift Shop",它只会添加"Thrift"到搜索中。
使用urlencode
对查询字符串中的值进行编码。
"<tr><td><a href=https://www.youtube.com/results?hl=en&q=". urlencode($row['Song'] . " " . $row['Artist']).">".$row['Song']."</a></td>";
您也可以使用http_build_query
"<tr><td><a href=https://www.youtube.com/results?" . http_build_query(array(
"hl" => "en",
"q" => $row['Song'] . " " . $row['Artist']
)).">".$row['Song']."</a></td>";