修复查询以将与查询匹配的所有行提取到关联数组中,而不只是一个

时间:2018-08-22 21:36:40

标签: php pdo count

在数据库中,有6行,其中city_name等于“圣安东尼奥”(拼写,大小写和空格均相同)。对于选择位置ID,我有以下代码。

function search_locations(string $term): array
{

    global $db;

    $sql = 'SELECT location_id FROM cities
            WHERE
            city_name LIKE :term';
    $stmt = $db->prepare($sql);
    $stmt->bindparam(':term', $term);
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

当我在函数中运行该命令,然后使用来检查数组

<?php $id_array = search_locations($search_term); ?>
<pre>
<?php print_r( $id_array); ?>
</pre>

我得到以下内容

Array (
[0] => Array
    (
        [location_id] => 38
    )

)

这仅显示找到一个位置。但是如果在我的返回语句之前将以下内容添加到我的查询中

$cSql = 'SELECT COUNT(*) FROM cities WHERE city_name LIKE :term';
$cStmt = $db->prepare($cSql);
$cStmt->bindParam(':term', $term);
$cStmt->execute();

// To just see the result without violating return rules
exit($cStmt->fetchColumn()); 

我得到6个结果。请记住,我也将第一个查询更改为

    $sql = 'SELECT * FROM cities
            WHERE
            city_name LIKE :term';

并且在主数组中仍然只有一个元素,并且只有该表中出现的第一行的所有字段值都具有该city_name等于“ San Antonio”的

编辑

将简洁的代码放入文件中后,我注意到如果仅按上面的代码调用,则不会发生此结果。但是还有更多我认为与之无关的代码。现在在下面添加。

<?php
require_once '../../private/initialize.php';
if (is_post_request() && $_POST['search_term'] !== "") {
    $search_term = $_POST['search_term'];
    $id_array = search_locations($search_term);
    // Its Fine here
    echo '<pre>';
    print_r( $id_array);
    echo '</pre>';

    $location = [];
    $cities = [];
    $zips = [];
    $phones = [];
    $urls = [];
    foreach ($id_array as $item) {
        array_push($location, find_location_by_id($item['location_id']));
        array_push($cities, find_cities_by_location_id($item['location_id']));
        array_push($zips, find_zips_by_location_id($item['location_id']));
        array_push($phones, find_phones_by_location_id($item['location_id']));
        array_push($urls, find_urls_by_location_id($item['location_id']));
    }
} else {
    redirect_to(url_for('lookup/test_search.php'));
}

$page_title = 'Results for "' . $search_term . '"';
include_once SHARED_PATH . '/search_header.php';

if (!empty($id_array)) { ?>
    <?php
    if (sizeof($id_array) === 1) {
        // Its bad here
        echo '<pre>';
        print_r( $id_array);
        echo '</pre>';
} ?>

0 个答案:

没有答案