从GET请求分析数据库表



早上好
我最近一直在努力解决这个问题,因为我对PHP&MySQL。我有一个数据库,其中有一个表"视频",我在其中存储有关视频的有用信息,我有一份名为search.php的文档,它将根据GET请求显示特定的视频。请求如下:

http://example.ex/search.php?tag=EXAMPLE1

逻辑是这样存储标签值:

if(!empty($_GET["tag"])){
// Get videos from tag only
$curTag = strval($_GET["tag"]);
displayByTag($curTag); //the function that parse the database
}

我已准备好连接:

$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$response[] = $row;
}

从技术上讲,到目前为止,我的表存储在$response[].
我需要做的是解析数据库并查找"tags"列,拆分其字符串值(表中的"EXAMPLE1、EXAMPLE2、EXAMPLE 3"(,然后查看GET值是否与其中一个匹配。

那时我需要你的帮助。我理解其中的逻辑和步骤,但无法将其"翻译"为PHP。以下是我要做的(人类语言(:

function displayByTag($tag) {
for each $video-item inside $array {
$tagsArray = explodes(",", $video-item[tags-column]); //That's how I split the tags stored inside the table
for i as integer = 0 to $tagsArray.length {
if $tagsArray(i) == $tag {
//THATS A MATCH
}
}
}
}

这样做对吗?我该如何将这种"人类"语言翻译成PHP代码呢
谢谢你的帮助。

经过一点测试和调试,我的函数可以很容易地工作。如果有人感兴趣:

function searchVideos($search) {
$currentSearchQueries = explode(" ", strtoupper($search)); //Split the searched tags in a array and make them to uppercase for easier comparaison.
//Establish a connection the MySql Database
$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
//Select all the entries from my 'videos' table
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
$response[] = $row; //Place them into a array
}
//Parse the array for matching entries
foreach ($response as &$video){ //Each entries goes through the process
foreach ($currentSearchQueries as $t) {
//We compare if one the tags searched matches for this particular entry
if((strtoupper($video[tags]) == $t) {
//THAT'S A MATCH
}
}
}
}

编写代码非常有趣,期待新的体验!

相关内容

最新更新