【问题标题】:Using if then with multiple conditions along with operators in PHP在 PHP 中使用 if then 和多个条件以及运算符
【发布时间】:2020-07-06 11:55:58
【问题描述】:

有一个下拉菜单,上面写着select playlist

每个播放列表中都有一定数量的歌曲。

例如:播放列表包括:POP(歌曲总数=3)、ROCK(歌曲=4)、Jaz(歌曲=5)、Classical(歌曲=6)

假设用户选择了一个播放列表-POP 并在文本框(歌曲编号框)中输入数字 3,然后当单击搜索按钮时,它将从音频文件夹(如果存在)打开 POP3.mp3 文件,否则它将显示数据库中没有歌曲

并且如果用户选择 POP 并在歌曲编号框中输入 4,它应该会显示 invalid songnumber

原来如此!!!但是这段代码不起作用我不知道错误在哪里。请指正!!

<?php
$valid = ['POP' => 3, 'ROCK' => 5, 'JAZZ' => 5];
// User selected genre and songnumber
$PlaylistName = 'ROCK'; // Note: I will get this value from dropdown in HTML
$songNumber = 5; // Note: I will get this value from textbox in HTML form
$song = $PlaylistName . $songNumber . '.mp3';
$file_pointer = './audio/' . $song;

foreach ($valid as $genre => $numberSongs) {
    if ($PlaylistName === $genre && $songNumber <= $numberSongs) {
        if (file_exists($file_pointer)) {
            header("Location: ./audio/" . $song);
            exit();
        } else {
            SongNotavailable();
        }
    } else {
        InvalidSongnumber();
    }
}

function InvalidSongnumber()
{
    echo "Invalid Song number!";
}

function SongNotavailable()
{
    echo '<span style="color: red;"/>Sorry! This song is not available on our database.</span>';
}
?>

// This gives result: Invalid Song number!Sorry! This song is not available on our database. Invalid Song number!

// But the valid answer is only Sorry! This song is not available on our database.

// So I need a correction in my code so that I can get only a valid result, not all results together

【问题讨论】:

  • 目前还不清楚是什么问题。你能把你的问题和问题浓缩一下吗?顺便说一句,在比较值时,您应该使用 == 而不是 =
  • 再次,问题不明确。 CODE IS NOT WORKING 并不能帮助我们了解问题所在。您期望发生什么以及实际发生了什么?请使用最新更改更新您的代码,以便我们都可以在同一页面上。另外,打开错误报告,以便查看任何警告/通知 - stackoverflow.com/a/21429652/296555
  • 也许您的and 需要是or,但不能确定,因为您还没有告诉我们真正的问题是什么。它会进入InvalidSongnumber 但它不应该吗?反之亦然?
  • 我已经修改了我的代码,请看看希望你现在理解它
  • 我试过你的代码,一切正常。唯一的可能是路径

标签: php post operators


【解决方案1】:

您的问题是您处于循环中,并且您正在为valid 中的每个条目进行迭代。您应该只验证一次传入的数据。

<?php

$valid = [
    'POP' => 3, 
    'ROCK' => 5, 
    'JAZZ' => 5
];

// Test data
$PlaylistName = 'ROCK'; 
$songNumber = 5;

// Check the playlist exists
if (!array_key_exists($PlaylistName, $valid)) {
    echo 'Invalid playlist provided.';
    exit;
}

// Check the song number is not greater than what is allowed
if ((int)$songNumber > $valid[$PlaylistName]) {
    echo  'Invalid song number provided.';
    exit;
}

$song = $PlaylistName . $songNumber . '.mp3';
$file_pointer = './audio/' . $song;

// Check the file exists on disk
if (!file_exists($file_pointer)) {
    echo '<span style="color: red;"/>Sorry! This song is not available on our database.</span>';
    exit;
}

// We now know the song is valid.
header("Location: ./audio/" . $song);
exit();

【讨论】:

  • 对于我提供的每个测试值,它总是显示提供的无效歌曲。先生,您能自己检查一下吗
猜你喜欢
  • 1970-01-01
  • 2012-11-25
  • 2020-03-18
  • 2019-07-04
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
相关资源
最近更新 更多