Lynob
Lynob

Reputation: 5337

selectbox inserting values multiple times

<?php
require '../common/connect-db.php';
require_once 'admin-template.php';
?>
<form id="form1" name="form1" method="post" action="test.php">
<?php
 // add button
if(isset($_POST['add_dayoff'])) {
$AddQuery = "INSERT INTO dayoff (fname,lname,datef)
VALUES ('$_POST[select1]')";
mysqli_query($db,$AddQuery);
};
?>
<?php
$query="SELECT DISTINCT fname, lname FROM employees";
$result = $db->query($query);
?>
<table><caption>Dayoff Table</caption>
     <tr>
     <th>First Name</th>
     <th>Employee Dayoff</th>
     </tr>
     <tr>
<td><select name="select1" id="select1" >
<?php
echo '<option value="">Please select...</option>';
while ($row = mysqli_fetch_array($result)) {
    echo "<option value='" . $row['fname'] . $row['lname'] . "'>" . $row['fname'] ." ". $row['lname'] . "</option>";
}
?>

<td><input type="date"  name="date" required /></td>
</select></td>
<td><input type="submit"  name="add_dayoff" /></td>

</tr>
</table>

the primary key is email in employees table, i know it's not a secure way to do it, and i should use prepare statements, but it's just a small project. 'dayoff' has an auto incremented int 'id' as primary key.

So what happens is that all records are inserted more than once. And some records fname and lname are concatenated and stored in fname in dayoff table

Upvotes: 0

Views: 25

Answers (1)

Vigneswaran S
Vigneswaran S

Reputation: 2094

You have syntax error

INSERT INTO dayoff (fname,lname,datef) VALUES ($_POST[select1]).$_POST[select1] will contains fnamelname.

Moreover you didn't get date value ie:$_post['date']. Try this and let me know the result

  <?php
    require_once 'admin-template.php';
    ?>
    <form id="form1" name="form1" method="post" action="test.php">
    <?php
    // add button
    if(isset($_POST['add_dayoff'])) {
    $fname=$_POST['select1'];// get the value which stores firstname-lastname
    $n=explode('-',$fname);//explode the value with -
    $datef=$_POST['date'];
    $AddQuery = "INSERT INTO dayoff (fname,lname,datef) VALUES ('$n[0]','$n[1]',$datef)";// query should be like this 
    mysqli_query($db,$AddQuery);
    };
    ?>
    <?php
    $query="SELECT DISTINCT fname, lname FROM employees";
    $result = $db->query($query);
    ?>
    <table><caption>Dayoff Table</caption>
    <tr>
    <th>First Name</th>
    <th>Employee Dayoff</th>
    </tr>
    <tr>
    <td><select name="select1" id="select1" >
    <?php
    echo '<option value="">Please select...</option>';
    while ($row = mysqli_fetch_array($result)) {
    echo "<option value='". $row['fname']."-".$row['lname'] . "'>" . $row['fname'] ." ". $row['lname'] . "</option>";
    }
    ?>
    <td><input type="date"  name="date" required /></td>
    </select></td>
   <td><input type="submit"  name="add_dayoff" /></td>
   </tr>
    </table>

Upvotes: 2

Related Questions