Raheem Harris Raheem Harris - 22 days ago 4
HTML Question

How do i clear this array by user input in php/html?

I am working on a program that has the user type in their course, first name, last name, and description of a program. The code is mostly done except for getting the clear the array button to work. When I use the unset array to clear the array on its own, it works but then the user cant enter in more data. I want to have the user be able to clear the data. Here is my code:

<?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>


Can someone please help?

Answer
<?php

// there is nothing wrong with this function.

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

?>

Okay, this function is fine, there is nothing wrong with it. But, you can't use this function like:

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

You see that onclick="Clear()", and that php function clear()? Yeah, you can't execute php functions with a html onclick="". You can only do that with javascript functions.

But you can do something like this:

<?php

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

?>