Adrian Suteu Adrian Suteu - 2 months ago 6
MySQL Question

PHP: Keep submited data in form even if there are multiple checkboxes with the same NAME

I have the following situation:

I have made a form for a SEARCH BOX for a mysqli connection. It allows the user to choose which fields to search by (name, email, telephone...). The code works but I would like to do a little more.


  1. Keep the submitted data inside the fields after clicking on submit button (I mention that the target for the form is the same page). I don't know how to do this as the name of most of the fields is the same - 'keyword[]'.

  2. Automatically check telephone2 when the user checks telephone1 checkbox.

    <form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="get">

    <input type="checkbox" name="keyword[]" value="last name" checked> Last Name
    <input type="checkbox" name="keyword[]" value="first name" checked> First Name
    <input type="checkbox" name="keyword[]" value="email" checked> Email
    <input type="checkbox" name="keyword[]" value="telephone1"> Tel1
    <input type="checkbox" name="keyword[]" hidden value="telephone2"> Tel2
    <input type="text" name="searched_text">
    <input type="submit" name="submit" value="SEARCH">
    </form>



Can you please help me?

Thank you in advance!

Answer

Replace your code with this and then test.

<form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="get">

<input type="checkbox" name="keyword[]" value="last name" <?php if(isset($_GET['keyword']) && in_array("last name", $_GET['keyword'])) echo "checked"; ?>> Last Name
<input type="checkbox" name="keyword[]" value="first name" <?php if(isset($_GET['keyword']) && in_array("first name", $_GET['keyword'])) echo "checked"; ?> > First Name
<input type="checkbox" name="keyword[]" value="email" <?php if(isset($_GET['keyword']) && in_array("email", $_GET['keyword'])) echo "checked"; ?>> Email
<input type="checkbox" name="keyword[]" value="telephone1" onclick="document.getElementById('telephone2').checked = true" <?php if(isset($_GET['keyword']) && in_array("telephone1", $_GET['keyword'])) echo "checked"; ?>> Tel1
<input type="checkbox" name="keyword[]" id="telephone2"  value="telephone2" <?php if(isset($_GET['keyword']) && in_array("telephone2", $_GET['keyword'])) echo "checked"; ?>> Tel2
<input type="text" name="searched_text">
<input type="submit" name="submit" value="SEARCH">

Comments