首页 > 解决方案 > 从表中选择数据,其中列像数组

问题描述

试图从数据库中获取一个数组并使用这个数组来执行一个查询,比如:“select from table where column like that array”。

在搜索了许多旧问题后,无法找到解决方案。

<?php
$mysqli = new mysqli("localhost", "hhtt", "htt", "htt");

/* Vérification de la connexion */
if ($mysqli->connect_errno) {
    printf("Echec de la connexion : %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT site FROM user_info";
$result = $mysqli->query($query);

/* Tableau numérique */
while($row = $result->fetch_array())
{
$rows[] = $row;
}

$string = implode(' OR arrondissement LIKE ', $rows);


$query2 = "SELECT path FROM photos WHERE arrondissement LIKE {$string}";

$myArray = array();

$result2 = $mysqli->query($query2);

while($row2 = $result2->fetch_array(MYSQLI_ASSOC)) {
    $myArray[] = $row2;
}
echo json_encode($myArray);

/*Fermeture de la connexion */
$mysqli->close();


?>

使用 mysql 查询中的数组从表中获取 json 数据。

标签: phpmysqlarraysmysqli

解决方案


Looking to your code You could use a single query avoiding implode and the related select based on array

    select  path FROM photos p
    INNER JOIN  user_info u ON  u.site = p.arrondissement

or if you really need like

    select  path FROM photos p
    INNER JOIN  user_info u ON  p.arrondissement like concat('%', u.site, '%')

an dif you need others where condition yu jst add the where clause after the join

    select  path FROM photos p
    INNER JOIN  user_info u ON  p.arrondissement like concat('%', u.site, '%')
    where p.is_clean = 0 

or extend the JOIN clause

    select  path FROM photos p
    INNER JOIN  user_info u ON  p.arrondissement like concat('%', u.site, '%')
       AND  p.is_clean = 0 

推荐阅读