如何通过php / html中的用户输入清除此数组?

时间:2016-11-18 00:28:21

标签: php html

我正在开发一个程序,其程序中包含用户类型,名字,姓氏和程序说明。除了清除数组按钮之外,代码主要完成。当我使用unset数组自己清除数组时,它可以工作,但用户无法输入更多数据。我想让用户能够清除数据。这是我的代码:

<?php
session_start();
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>

<script>
function showHint(str) {
if (str.length == 0) {
    document.getElementById("txtHint").innerHTML = "";
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
        }
    }
    xmlhttp.open("GET", "gethint.php?q="+str, true);
    xmlhttp.send();
}
}
</script>
<?php
function clear(){   //this is the problem
    unset($_SESSION['courses']);
    return true;
}
?>

 </head>
<body>
<form method="POST">
  Course: <input type="text" name="courses" />
   <br /><br />
   First Name: <input type="text" name="firstname" />
   <br /><br />
    Last Name: <input type="text" name="lastname" />
    <br /><br />
    Description: <input type="text" name="description" />
    <br /><br />
    <input type="submit" name="submit" value="Submit">
</form>

<?php 
// First we check if the form has been sent and we have a value
if (!empty($_POST['courses'])) {
 if (!isset($_SESSION['courses']))
    $_SESSION['courses'] = array(); // Initialize the array if it doesn't exist

// Add the value to our array
$_SESSION['courses'][] = array("course" => $_POST['courses'],
                                "firstname" => $_POST['firstname'],
                                 "lastname" => $_POST['lastname'],
                                "description" => $_POST['description']); 
}

// If there are values to show, print them!
if (!empty($_SESSION['courses'])) {
foreach ($_SESSION['courses'] as $course) {
    echo $course['course']."    ".
          $course['firstname']."    ".
          $course['lastname']."    ".
         $course['description']."    ".
        "<br />";
}
}


?>
 <input type="submit" name="Clear" value="Clear"  onclick="clear()"> //this is the problem
<?php

?>

</body>
</html>

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

<input type="submit" name="Clear" value="Clear"  onclick="clear()">

clear()将调用javascript函数。你已经正确编写了一个php函数。

检查提交按钮“Clear”的值是否为“clear”,如果为true则运行PHP函数clear()。

if ($_POST['Clear'] === 'clear') {
    clear();
}

答案 1 :(得分:1)

<?php

// there is nothing wrong with this function.

function clear() {
    unset($_SESSION['courses']);
    return true;
}

?>

好的,这个功能很好,没有任何问题。但是,你不能像以下那样使用这个功能:

<input type="submit" name="Clear" onclick="Clear()" /> <!-- this is the problem -->

你看到onclick="Clear()"和那个php函数clear()?是的,你不能用html onclick=""执行php函数。您只能使用 javascript 功能执行此操作。

但你可以这样做:

<?php

if(isset($_POST['Clear']))
{
  // if the user submits the form, then the following code will be executed.
  clear();
}

?>