Louie Louie - 5 months ago 11
MySQL Question

how to auto increment an input name in html and save in database?

I have a table named positions. This table has the list of the different positions that the admin has added in the listOfPositions.php like President, Vice-President, etc. After adding different positions, he can now add the different people under that position. And that's where my problem is. How will I have an auto increment input name for the names of the people depending on how many positions it has in the table positions ?

I tried using javascript, but it increments only in the html and not reflecting to the php when I try to save. My current code where the adding of the names of different persons depending on the position is the ff:

<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<form action="post_officers.php" method="post"><br>
<center><select name="year">

<?php

for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. "-" . $i .'" '.$selected.'> '.$year2.'-'.$i.'</option>'."\n");
}
?>
</select></center>


<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name" /></td>
</tr>

</table>
<?php
}
?>

<input type="submit" name="submit" value="SAVE"/>
</form>
<script>
$("input[name='file']").each(function(ind) {
$(this).attr(ind + 1);
});

$("input[name='position']").each(function(ind) {
$(this).attr(ind + 1);
});

$("input[name='name']").each(function(ind) {
$(this).attr(ind + 1);
});


</script>


And this is my php code:

<?php
include ('dbcontroller.php');
date_default_timezone_set('Asia/Manila');
$year = mysqli_real_escape_string($conn,$_POST['year']);

if(isset($_POST['submit'])) {
$result = mysqli_query($conn,"SELECT * FROM officers WHERE year = '$year'");
$num_rows = mysqli_num_rows($result);

if($num_rows>0){
echo "<script type='text/javascript'>alert('Year already exists.'); window.location.href='create_alumni_officers.php';</script>";
}
else {
for ($i = 1; $i <= 8; $i++) {
$name = mysqli_real_escape_string($conn,$_POST['name'.$i]);
$position = mysqli_real_escape_string($conn,$_POST['position'.$i]);

$file=(rand(1000,100000)."-".$_FILES['file'.$i]['name']);
$type=($_FILES['file'.$i]['type']);
$size=$_FILES['file'.$i]['size'];
$loc=($_FILES['file'.$i]['tmp_name']);

$new_size=$size/1024; // file size in KB

// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case

$final_file=str_replace(' ','-',$new_file_name);

if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}

}
}


?>


And this doesn't work at all. Any help? I hope you guys understood what I'm trying to ask.

Answer

This is the best way to do it:

<?php 
    include_once('dbcontroller.php');   
    $sql = "SELECT * FROM positions ORDER BY pos_id ASC";
    $result = mysqli_query($conn, $sql);
    /* assign an onchange event handler */
    while ($row = mysqli_fetch_array($result)) {
    $position = $row['position'];
    ?>
<table id="options-table">                  
            <tr>
                <td><input type="file" name="file[<?php echo $position; ?>]" /></td>    
                <td><input type="hidden" name="position[<?php echo $position; ?>]" value="<?php echo $position; ?>" /><?php echo $position; ?></td>
                 <td><input type="text" name="name[<?php echo $position; ?>]" /></td>
            </tr>                  

        </table>
 <?php 
    }
    ?>

You don't need the javascript to change input attributes. Remove it.

In php use foreach loop like:

If you are still getting errors I will need to see the output of print_r($_POST);

<?php 
$files = $_FILES['file'];
$positions = $_POST['position']; //use this for the foreach loop because it will always have a value
$names = $_POST['name'];

foreach($positions as $key=>$position){
  $file = @$files[$key];
  $name= @$names[$key];
  //Do your magic  for each user here
    $name = mysqli_real_escape_string($conn,$name);
    $position = mysqli_real_escape_string($conn,$position);

    $filename = rand(1000,100000)."-".$file['name'];
    $type = $file['type'];
    $size = $file['size'];
    $loc = $file['tmp_name'];

    $new_size=$size/1024; // file size in KB

    // make file name in lower case
     $new_file_name = strtolower($filename);
     // make file name in lower case

     $final_file = str_replace(' ','-',$new_file_name);

    if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
                          echo "Page is loading, please wait...";
      $result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
      or die(mysqli_error($conn));
      echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
    }

}

?>
Comments