从 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[].

我需要做的是解析数据库并查找“标签”列,拆分其字符串值(表中的“EXAMPLE1,EXAMPLE2,EXAMPLE3”),然后查看是否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 代码?

谢谢您的帮助。


萧十郎
浏览 87回答 1
1回答

慕工程0101907

经过一些测试和调试后,我的功能很容易运行。如果有人感兴趣: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            }        }    }}编码很有趣,期待新的体验!
打开App,查看更多内容
随时随地看视频慕课网APP