Gorg Gorg - 3 months ago 7
PHP Question

How can I make these PHP if statements more succinct?

I have multiple if statements which almost do the same thing. Only the number will change. I have shown only two ifs below. There will always be at least one button but there could be up to twenty, so I would like to know how I can make this more succinct.

if (isset($_POST['button1']) && ($_POST['button1']) == $button1 ){
$stmt = $db->prepare('UPDATE members SET page = :page WHERE memberid = :memberid');
$stmt->execute(array(':memberid' => $_SESSION['memberID'], ':page' => $_POST['button1']));
$array = $stmt -> fetchAll(PDO::FETCH_ASSOC);
$_SESSION["page"] = $_POST['button1'];
header ('Location: memberpage.php?page=' . $_SESSION["page"]);
}
elseif (isset($_POST['button2']) && ($_POST['button2']) == $button2 ){
$stmt = $db->prepare('UPDATE members SET page = :page WHERE memberid = :memberid');
$stmt->execute(array(':memberid' => $_SESSION['memberID'], ':page' => $_POST['button2']));
$array = $stmt -> fetchAll(PDO::FETCH_ASSOC);
$_SESSION["page"] = $_POST['button2'];
header ('Location: memberpage.php?page=' . $_SESSION["page"]);
}

Answer

I don't know where the variables $button1, $button2, etc are defined, but it seems to me like you could name the input on the HTML side just "button" and get away with doing a single if check...

$page_array = array(
    'page_one',
    'page_two'
)


if(isset($_POST['button']) && in_array($_POST['button'], $page_array)){
     $stmt = $db->prepare('UPDATE members SET page = :page WHERE memberid = :memberid');
     $stmt->execute(array(':memberid' => $_SESSION['memberID'], ':page' => $_POST['button']));
     $array = $stmt -> fetchAll(PDO::FETCH_ASSOC);
     $_SESSION["page"] = $_POST['button'];
     header ('Location: memberpage.php?page=' . $_POST['button']);
} else {
   // error checking
}

Again, I'm sort of guessing as to what your code is actually doing, but it seems like you're defining each button and setting a page to it.. ? On your html side you can just do like..

<form action="path/to/your_script" method="post">
    <input name="button" value="page_one" type="submit">
    <input name="button" value="page_two" type="submit">
</form>

the $page_array will define a list of accepted pages (if that's what you're looking for..) and in_array just checks to make sure the value passed from post exists in the list of accepted pages.