Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

php - Why does my if else stament work but when I replace it with a function it doesn't?

I am creating dynamically some accordions (the number depends on the database output) which contain input forms and want to keep them open if an error is reported after input validation. When I use an if else statement within my echo that creates the forms it works as expected. But if I replace the if else with a function the page doesn't even load correctly.

The following code (striped down to a minimal example) adds "w3-show" or nothing to the div class and works fine. The $player_edit_err[$id] will contain the error message as its value or will be an empty array if no error is reported. I am initializing this array after $_POST has been submitted like this: $player_edit_err = array(); and after validation like this: if (empty($new_player_name)) {$player_edit_err[$id] = "Please enter a Name.";} the array will be empty or contain the error as a string. At the end I am showing the complete $_POST code.

foreach ($players_in_tourn as $id => $name) {
  echo "<div class='w3-hide";

  if (!empty($player_edit_err[$id])) {
    echo " w3-show";
  } else {
    echo "";
  }

  echo "'><form action='" . htmlspecialchars($_SERVER['PHP_SELF']) . "' method='post'>
            <input type='text' name='new_player_name' value='$name'>
            <input type='hidden' name='player_id' value='$id'>
            <span>" . $player_edit_err[$id] . "</span>
          </form>
        </div>";
}

But if I want to place the if else statement inside a function in order to tide-up the code like this:

function accordionShow($error) {
  if (!empty($error)) {
    return " w3-show";
} else {
    return "";}
}

and try to call the function by replacing the if else statement like this: echo accordionShow($player_edit_err[$id]); or accordionShow($player_edit_err[$id]); it does not work. Please note that I have tested this with using either echo or return in the function. In fact, when I try to call the function the list of accordions is not created completely. It stops after the first one with the rest of the page also not loading. I don't know if this is relevant, but I am also getting an Uninitialized string offset: error message in the php log file. The php error is referring to the $player_edit_err[$id] string when the code runs fine (i.e. when not using the function).

Any help to understand this problem greatly appreciated. Thanks!

EDIT: Here is the complete $_POST code

// Processing form data when form is submitted
foreach ($players_in_tourn as $id => $name) {
    if (($_SERVER["REQUEST_METHOD"] == "POST") && isset($_POST["edit_player$id"])) {
        $message = "POST for edit_player";

        //Define variables
        $player_id = $_POST["player_id"];
        $player_name = $_POST["player_name"];
        $new_player_name = $_POST["new_player_name"];
        $player_edit_err = array();

        // Make the function for form data input validation available 
        require('functions/functions.php');

        // Validate tourn_name
        if (empty($new_player_name)) {
            $player_edit_err[$id] = "Please enter a Name.";
        } else {
            $new_player_name = test_input($new_player_name);
        }

        // // Validate player ... check if it exists already in the tournament
        $new_array = $_SESSION['playersInTourn'];
        unset($new_array[$player_id]);

        if (in_array($new_player_name, $new_array)) {
            $player_edit_err[$id] = "Player $new_player_name already exists.";
        }

        $_SESSION['errors'] = $player_edit_err;

        // Then insert the tournament player
        if ($player_edit_err[$id] == "") {
            // If no errors insert the tournament player
            $stmt = $db->prepare("UPDATE Players SET name =? WHERE idPlayers=?");
            $stmt->execute([$new_player_name, $player_id]);

            // Redirect to Tournament page
            header("location: add_players.php");
            exit();
        }
    }
}
question from:https://stackoverflow.com/questions/65877703/why-does-my-if-else-stament-work-but-when-i-replace-it-with-a-function-it-doesn

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When if (empty($new_player_name)) { and if (in_array($new_player_name, $new_array)) { are not satisfied/true, then if ($player_edit_err[$id] == "") { will generate an error because the $id key of the $player_edit_err array does not exist.

If I am an honest, I would rewrite this whole flow (in fact, I'd redesign your form that points to this script so that array type fields are named edit_player[$id] instead of edit_player$id).

However, to quickly patch your script, just use an empty() check.

if (empty($player_edit_err[$id])) {

I will make one important note: prepared statements are designed to be declared once (before entering a loop) then executed as many times as needed inside the loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...