PHP按钮进行查询和刷新页面


PHP Button to carry out query and refresh page

我的页面上有两个按钮(是和否)。我在另一个页面"选择.php"上有一个功能,可以根据此决定更新数据库。此函数将"是"或"否"作为输入。因此,我希望每个按钮运行选择.php页面,根据按下的按钮使用"是"或"否",然后刷新当前页面。目前我已经尝试过(对于"是"):

echo "<form></br>";
echo "<input type='button' value = 'yes' Method ='POST' ACTION = 'choice.php'>";
echo "</form>";

但我不确定从这里走向何方。选择.php页面有:

function choice('yes'/'no');

参数应该以逗号分隔,但是从超全局数组中获取参数时,您实际上并不需要参数。但是,只有在以下情况下'yes'才需要调用该函数:

<form action="choice.php" method="post">
<input type="submit" name="choice" value="yes" />
<input type="submit" name="choice" value="no" /> <!-- You'd better use radio buttons -->
</form>
<?php    
function choice() {
    if ($db->query("UPDATE ..... ;")) {
        return true;
    }
    return false;
}
if (isset($_POST['choice']) && $_POST['choice'] == 'yes') {
    choice();
}
else {
    echo 'no';
}
?>

当然,你可以有多个if,但我认为这对你的帮助不够:

if (isset($_POST['choice']) && $_POST['choice'] == 'yes') {
     //something;
}
elseif (isset($_POST['choice']) && $_POST['choice'] == 'no') {
     //something else;
}
elseif (isset($_POST['choice']) && $_POST['choice'] == 'maybe') {
     //something else;
}

如果您希望函数使用来自用户的值更新 db,您可以使用如下所示的内容:

function choice() {
    $choices = array('yes', 'no', 'maybe', 'dunno'); //predefined choices
    if (in_array($_POST['choice'], $choices)) { //checks if the user input is one of the predefined choices (yes, no, maybe or dunno)
        if($db->query("UPDATE table1 SET userchoice = '{$_POST['choice']}' WHERE user_id = '{$_SESSION['id']}';")) {
            return true;
        }
    }
    return false;
}

if (isset($_POST['choice'])) choice(); //so here you don't need (not necessary, but you can) to check if the value is the one you want. If it's set, you call choice(), then the function checks if it's in the array of predefined choices, so if it is - it will update, if it's not it will return false

一种方法是在数据库操作完成后在choice.php上使用header
header('Location: *where your form page is*');

另一种方法是使用 javascript 做一个 ajax 帖子

假设你有这样的东西:

<form method='POST' action='choice.php'>
<tr>
 <td><input type="submit" name="answerswer" value="yes"></td>
 <td><input type="submit" name="answerswer" value="no"></td>
</tr>
</form>

PHP文件中,您可以使用POST方法检查答案,无论是yes还是no

if($_POST['answer'] == 'yes') {
 //do something
}
if($_POST['answer'] == 'no') {
 //do something else
}