0

我的查询不是 /search.php?cat=2,而是 /search.php?cat=SomeName。

我刚开始学习 PHP 和 MYSQL,当然觉得有很多我不知道的标准做法。我只是掌握了一些事情的窍门(您可能不同意;)并组合了一个将名称交换为 ID 的函数,该函数正在运行。

有没有更标准的方法来做到这一点?

工作代码:

function swap_name_for_id($name, $search) {
        global $connection;
        if ($search == 'category') {
            $query = "SELECT categories.id, categories.name
                FROM categories 
                WHERE categories.name = '{$name}'";
        }
        $swap_set = mysqli_query($connection, $query);
        confirm_query($swap_set);
        while ($swap = mysqli_fetch_array($swap_set)) {
            $search_id = $swap["id"];
        }
        return $search_id;
    }
function get_parts_for_category($category_name) {
        $category_id = swap_name_for_id($category_name,     'category');
        global $connection;
        $query = "SELECT parts.id, parts.name, parts.    part_category
                FROM parts 
                WHERE part_category = {$category_id}
                ORDER BY name ASC";
        $part_set = mysqli_query($connection, $query);
        confirm_query($part_set);
        return $part_set;
    }
4

1 回答 1

1

一般来说,据我所知,您只需像您一样执行第二个查询,尽管它们通常组合成一个查询,如下所示:

function get_parts_for_category($category_name) {
    global $connection;
    $query = "SELECT parts.id, parts.name, parts.part_category
            FROM parts 
            WHERE part_category = (SELECT categories.id FROM categories WHERE categories.name = '{$category_name}')
            ORDER BY name ASC";
    $part_set = mysqli_query($connection, $query);
    confirm_query($part_set);
    return $part_set;
}
于 2013-07-12T03:05:33.467 回答