将数组与数据库表进行比较,如果找到任何匹配项,则获取img url并插入PHP


Comparing array to database table, if any matches are found, get the img url and insert into PHP

所以基本上我的难题是:

我有一个这样的数据库:

Word   |   imgUrl   |   imgSize
volvo  | C:'Users'..|     15

我有一个这样的数组:

$cars = array("Volvo", "BMW", "Toyota");

我需要PHP比较数组中的内容与数据库列Word中的内容,然后检索相应的imgURL列值并将其存储在变量$img中。

然后我准备了这个功能来运行我的程序的其余部分:

$size = 100;
$lines = file_get_contents(basename($_FILES["fileToUpload"]["name"]), FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
$words = array_splice($words, 0, count($words));
$img = Database entry
foreach ($words as $x => $word) {
    print '<div class="result" style="position: relative; float: left; 
            width:' . $size . 'px; margin: 5px; height:' . $size . 'px;  
          background-image:url('. $img .'); background-size: 100% 100%;">
            <a id="word' . $x . '">' . $words[$x] . '</a></div>';
}   

正如您所看到的,我试图将数组的每个单词放入单独的<div>中,然后显示它。一切都很好,我只需要显示相应的img字作为背景的<div>

有人知道吗?任何和所有的建议感谢!

欢呼

不用数据库也可以。

  1. 将所有图片放到一个目录下(例如"Words")
  2. 将所有图像命名为其所代表的单词(例如 Volvo.png , BMW.png )
  3. 进入思想阵列并设置图像路径

代码示例

for($x=0;$x<Count($x);$x++)
{
    echo'<div class="result" style="background-image:url("https://website.com/Words/'.$words[$x].'.png");background-size: 100% 100%;"><a id="word'. $x .'">'. $words[$x] .'</a></div>';
}
指出

这是一个更好的解决方案,因为不需要连接到数据库,并且会更快地生成页面。

它的缺点是需要空间来存储所有的图像

不知道您正在使用的数据库类型,我假设mysql。这段代码应该足够了:

//                    IP            username       password    database
$mysqli = new mysqli('127.0.0.1', 'your_user', 'your_pass', 'sakila');
$sql = "select imUrl from  tableName where word = '".$cars[0]."'";
$result = $mysqli->query($sql));
$car_img = $result->fetch_assoc();
//access image using $car_img['imgUrl'];

希望有帮助。如果您有多个图像,您可以围绕这个循环并根据需要经常运行它,只要您将$car_img存储在某个地方,这样它就不会被覆盖。