我在我的项目中嵌套了 if 条件,但我遇到了问题;
if(isset($_GET['q']) && isset($_GET['t'])) {
$query = $_GET['q'];
$type = $_GET['t'];
$none_key = FALSE;
if($type = 'singer') {
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%'");
$control = $singers->rowCount();
if($control > 0) {
$on_page = 24;
$number_singers = $singers->rowCount();
$number_page = ceil($number_singers/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%' ORDER BY singer_name ASC LIMIT ".$limit.",".$on_page);
$singer_key = TRUE;
} else {
$none_key = TRUE;
}
}
if($type = 'song') {
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%'");
$control = $songs->rowCount();
if($control > 0) {
$on_page = 24;
$number_songs = $songs->rowCount();
$number_page = ceil($number_songs/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%' ORDER BY song_name ASC LIMIT ".$limit.",".$on_page);
$song_key = TRUE;
} else {
$none_key = TRUE;
}
}
} else {
$key = TRUE;
}
当我运行代码时,我期望如果“control”变量之一大于 0,则“none_key”变量必须等于 0。当“type”变量为“song”时,没有问题但是如果'type'变量是'singer'然后'none_key'变量打印1,我认为它正在运行第二个if block 并变为'none_key'1因为第二个'control'变量不大于零。
最佳答案
这是一个赋值,它将$type
设置为值singer
:
if ($type = 'singer') {
你想要一个比较,它会检查 $type
是否等于 singer
的值:
if ($type == 'singer') {
[编辑] 有些人喜欢用最后一个变量来编写这种语句。这通常称为“尤达条件”:
if ('singer' == $type) {
这样一来,如果你搞砸了并且只使用了一个 =
,你会得到一个错误。
关于php - 如果条件不起作用则嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51661786/