问题描述
我的查询不是类似于/search.php?cat=2,而是/search.php?cat=SomeName.
Instead of my queries being something like /search.php?cat=2, I'd like it instead to be /search.php?cat=SomeName.
我刚开始学习 PHP 和 MYSQL,当然觉得有很多我不知道的标准实践.我只是掌握了窍门(您可能不同意;)并组合了一个函数,该函数可以将名称替换为 ID,该函数正在运行.
I just started learning PHP and MYSQL and of course feel like there's lots of standard practices I'm unaware of. I'm just getting the hang of things (you may disagree ;) and put together a function that swaps name's for ID's, which is working.
有没有更标准的方法来做到这一点?
Is there a more standard way of doing this?
工作代码:
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;
}
推荐答案
据我所知,一般情况下,您只需像您一样执行第二个查询,尽管它们通常合并为一个查询,如下所示:
Generally as far as I know you just do a second query like you do, although they are usually combined into one query, like this:
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;
}
这篇关于是否有标准方法可以将查询从 ID 交换到不同的列(如“名称")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!