-1

1How do I insert a query based on a dropdown list? My database consists of 4 tables, one parent table and 3 child tables. My dropdown list consists of Table1, Table2, and Table3. If Table3 is selected, data will be inserted into Table3.

It works fine when I try to insert a single input field but, when I try to insert more than one input, it will only store the last selected table.

Have a look at my form which I have stored here.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "2d_system";
    $conn = new mysqli($servername, $username, $password, $dbname);



  $sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())";
   mysqli_query($conn, $sql);

  foreach($_POST['gamecenter'] as $i => $gamecenter){
  $gamecenter = $_POST['gamecenter'][$i];
  $number = $_POST['number'][$i];
  $price = $_POST['price'][$i];

//checks type of gamecenter if true, insert
  if ($gamecenter == 'Damacai'){ 
try {
  //to insert into parent table
  //$sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())";
 // mysqli_query($conn, $sql);
  $queryDamacai = "INSERT INTO damacai_draw (LotteryId, Damacai_Number, Price) VALUES (last_insert_id(), '$number', '$price')"; 

  if(!mysqli_query($conn, $queryDamacai)){  
   throw new Exception("error: could not able to execute $queryDamacai. " . mysqli_error($conn));
 }

 echo "Records added successfully.";
  }
      catch(Exception $e)
   {
      echo $e->getMessage();
   }
  }

      //checks type of gamecenter if true, insert
       if ($gamecenter == 'Magnum'){ 
          try {
         //to insert into parent table
           //$sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES 
      (now())";
     //mysqli_query($conn, $sql);

$queryMagnum = "INSERT INTO magnum_draw (LotteryId, Magnum_Number, Price) VALUES (last_insert_id(), '$number', '$price')"; 

if(!mysqli_query($conn, $queryMagnum)){  
  throw new Exception("error: could not able to execute $queryMagnum. " . mysqli_error($conn));
}

     echo "Records added successfully.";
   }
   catch(Exception $e)
 {
   echo $e->getMessage();
 }
}

//checks type of gamecenter if true, insert
 if ($gamecenter == 'Toto'){ 
   try{

<?php
//index.php

$connect = new PDO("mysql:host=localhost;dbname=2d_system", "root", "");
function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
 }
 return $output;
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>2D</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <br />
   <h4 align="center">Enter Number Details</h4>
   <br />
   <form method="post" id="insert_form" action="insert.php">
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
      <tr>
       <th>2D Number</th>
       <th>Price (RM)</th>
       <th>Game Center</th>
       <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
      </tr>
     </table>
     <div align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Print" />
     </div>
    </div>
   </form>
   <form method="post" action="collect_vals.php">
   
   
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="number[]" class="form-control item_name" /></td>';
  html += '<td><input type="text" name="price[]" class="form-control item_quantity" /></td>';
  html += '<td><select name="gamecenter[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
  $('#item_table').append(html);
 });
 
 $(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
 });
 
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.number').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.price').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.gamecenter').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Select Unit at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Item Details Saved</div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
</script>

//to insert into parent table

$queryToto = "INSERT INTO toto_draw (LotteryId, Toto_Number, Price) VALUES (last_insert_id(), '$number', '$price')"; 

if(!mysqli_query($conn, $queryToto)){  
  throw new Exception("error: could not able to execute $queryToto. " . mysqli_error($conn));
}

    echo "Records added successfully.";
 }
 catch(Exception $e)
 {
     echo $e->getMessage();
  }
  }



   } 

    $conn->close();
     ?>
Dharma
  • 3
  • 3
  • Based on the post you've made, I would recommend spending some time reading documentation in the [Help Center](https://stackoverflow.com/help) so that you have the best chance at getting your question answered. – Brien Foss Feb 17 '18 at 03:18

2 Answers2

0

Jump to "EDIT" for actual answer

Your foreach loop only updates the query string... but never executes it, so you keep doing that until the last record, and then you run the query... so that's why it only stores the last input.

For my example, I'll only use the Damacai game center, but it applies to all. Try to run the code and throw an Exception when a query can't be executed. If all queries run correctly, a success message will show up:

<?php
if($gamecenter == 'Damacai'){
    try {
        $sql = "INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())";
        mysqli_query($conn, $sql);

        foreach($_POST['number'] as $i => $number){
            // Get values from post.
            $number = mysqli_real_escape_string($conn, $number);
            $price = mysqli_real_escape_string($conn, $_POST['price'][$i]);

            // Add to database
            $queryDamacai = "INSERT INTO damacai_draw (LotteryId, Damacai_Number, Price) VALUES (last_insert_id(), '$number', '$price')";
            //$queryDamacai = substr($queryDamacai, 0, -1); //remove last char
            //$result = mysqli_query($conn, $query);

            if(!mysqli_query($conn, $queryDamacai)){
                throw new Exception("error: could not able to execute $queryDamacai. " . mysqli_error($conn));
            }
        }
        echo "records added successfully.";
    } catch(Exception $e){
        echo $e->getMessage();
    }
}
?>

It is important to note that if you want to store data for several Game Centers at once, then you shouldn’t use if () {} else if () {}, but instead create separate if statements for each Game Center. Otherwise, only one Game Center will be modified. Also, take a second look at how you’re using $gamecenter because you’re making it sound like it might be an array.

EDIT

So the information was not being sent as I thought... I believe that I get the idea, despite the fact that I don't know why so much jQuery is used to create the form. Regardless of that, here's the entire (yes, for all game centers) code that I think should be working. You still have to make sure you actually need [$k] for $_POST['gamecenter'] because I believe, although not sure, that if foreach is set to give both the key and value, you don't need to use the key for the elements being looped. But I might be wrong for your specific case.

Without further due, the code:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "2d_system";
$conn = new mysqli($servername, $username, $password, $dbname);

try {
    if($conn->query("INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())")){ // consider adding a default value of CURRENT_TIMESTAMP for CreatedDateTime
        $lotteryTicketID = $conn->insert_id;
        foreach($_POST['gamecenter'] as $k => $v){ // all game centers will be looped here
            $gamecenter = $_POST['gamecenter'][$k]; // make sure you need this, if the values are incorrect, then consider using $gamecenter = $v;
            if($stmt = $conn->prepare("INSERT INTO ".strtolower($gamecenter)."_draw (LotteryId, ".$gamecenter."_Number, Price) VALUES (?, ?, ?)")){ // This part is done to avoid creating so many duplicated queries and and shorten the code.
                $number = $_POST['number'][$k];
                $price = $_POST['price'][$k];

                $stmt->bind_param('idd', $lotteryTicketID, $number, $price); // be careful with these values. If you change the name of your tables or columns, these might be affected.
                $stmt->execute();
            }
            if($conn->errno){
                throw new Exception("Error: could not execute query/queries: ".$conn->error);
            }
        }
    }
    if($conn->errno){
        throw new Exception("Error: could not execute query/queries: ".$conn->error);
    }
    echo "Records added successfully.";
} catch(Exception $e){
    echo $e->getMessage();
}
$conn->close();
?>
Zeke
  • 1,281
  • 1
  • 18
  • 26
  • I had to update my answer because I realized that it wouldn't work with the variables as they were. Had to mix up a few things and take away a concatenation, etcetera. Now it should work. I also commented out some things, didn't want to delete them to avoid confusions. – Zeke Jan 28 '18 at 16:05
  • Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Jan 28 '18 at 18:13
  • @RiggsFolly I know, I always use parameterized, but I thought it would be fine just to answer the question and talk about that as another topic. Plus, it’s not my code, I just edited the code in the question. What if he doesn’t know how to use those things and I simply wrote it the cool way? He’d be more confused. – Zeke Jan 28 '18 at 18:15
  • @RiggsFolly furthermore, I prefer object-oriented style. – Zeke Jan 28 '18 at 18:16
  • @Zeke Thanks for the reply, i have tried using your code. it still insert the last input filed into database. – Dharma Jan 29 '18 at 02:26
  • Did you make sure that `$_POST['number']` is an array with all the numbers you need? How are you sending that value to your server? – Zeke Jan 29 '18 at 02:35
  • Maybe your HTML or JavaScript isn't sending the data correctly, so that contributes to the existing PHP issue. I suggest you do `print_r($_POST['number'])` somewhere at the top of your PHP part and send multiple inputs, this way you'll be able to see if everything is sent. If not, please post that part of the code and I'll take a look at it. – Zeke Jan 29 '18 at 02:52
  • @Zeke Yes, it stored all the numbers but I think the problem lies on the gamecenter because all numbers keyed in are stored but only inside the last selected table. For example, field 1 -> 22 -> 22 -> Damacai , field 2-> 33 -> 33 -> Magnum. When i clicked the submit button all numbers are stored inside Magnum table. It supposed to insert 22 into Damacai and 33 into Magnum. Let me know if u need more explanation and thank you for the reply again – Dharma Jan 29 '18 at 04:00
  • I’ll repeat, please update your question adding the form you’re using to send the information. The problem might be there, could be the Game Center or the number or whatever, but it might be there. – Zeke Jan 29 '18 at 05:36
  • Wait, if you want to do that, then don’t use `else if`... simply create an `if` for each Game Center. – Zeke Jan 29 '18 at 05:42
  • I’ll get back at you as soon as I can, but I’m leaving now and I might take over 10 hours. – Zeke Jan 29 '18 at 05:48
  • @Zeke Thanks, i will try use the method. i understand you might be busy, thanks for the answer. i will be waiting for your advice. – Dharma Jan 29 '18 at 05:56
  • I already said I need you to update your question adding the form and all blocks of code related to sending the information. I believe it also has to do with the way you’re sending the information. So please, add those things to your question. – Zeke Jan 29 '18 at 12:51
  • @Zeke Hey please have look at my updated code, It works fine when i enter 1 data into 3 tables. Example: Number 11,12,13, will insert into table1(11),table2(12),table3(13). Works Fine. But if i insert 2 data into the same table it showing up a error. This is the error that i get; Cannot add or update a child row: a foreign key constraint fails – Dharma Jan 29 '18 at 15:42
  • Let me take a look, I don't think you're doing the same thing I was expecting, but I'll have to read it all. Again. – Zeke Jan 29 '18 at 16:09
  • I updated my answer. Now I posted the entire code, all that I wrote under **edit** was prepared to receive as many game centers as you want, following your naming scheme. If you change your naming scheme (the names of your tables and/or columns), then this code might stop working. Be careful and read every single line. If there is something you do not understand, then ask before using it or changing it. – Zeke Jan 29 '18 at 18:45
  • Hey @Zeke when i use your code, showing me this "error in line 12 syntax error, unexpected 'foreach' (T_FOREACH)" – Dharma Jan 30 '18 at 04:40
  • That’s a very normal syntax issue, did you correct it? (I’m pretty sure you know what that error means, and if you don’t... well, you better start learning). I don’t see it so far in the code, but I’ll keep searching. If you can copy the _entire error line_ it would be great. Because That gives more info. – Zeke Jan 30 '18 at 09:27
  • Are you sure you didn’t edit something when you copied the code? If you erased the comments (which I don’t see why) if you may have deleted a `{`, especially on line 11. And that could be one reason. There is no syntax error in my code that I can see. – Zeke Jan 30 '18 at 09:31
  • @Zeke My bad i copied wrongly, however then this error comes out ,incorrect syntax use near '?(LotteryId, ?, Price) VALUES (last_insert_id(), ?, ?)' at line 1. I checked everything and I didnt find any syntax error. Help! – Dharma Jan 31 '18 at 05:15
  • I forgot you can’t bind a table name... that’s why, the `?` for the table name is causing the issue... it would actually be great if you didn’t do that, but that’s nothing you can’t fix by concatenating the name of the Game Center. Do you understand? I’ll update my answer when I can, but if you understand this bit I just explained, try to do it on your own. Use an if-else statement to check the name and prepare the SQL inside the foreach loop (both things). That way you can concatenate the name of the table, since this is sent before binding. If you can’t do it, wait for my update. – Zeke Jan 31 '18 at 06:48
  • @Zeke hey sorry i don't understand, what u mean – Dharma Jan 31 '18 at 09:54
  • Then you’ll have to wait until I can use a computer to update my answer. I can’t really on my phone. – Zeke Jan 31 '18 at 10:24
  • I just updated the code, please try again and report back. – Zeke Jan 31 '18 at 19:47
  • @Zeke I have tried your code it works but whenever I tried to insert two of the same table it will show "Cannot add or update a child row: a foreign key constraint fails". Ive tried to make some changes and I think its because of the last_insert_id(). It cant be use with multiple query. Any advice? – Dharma Feb 01 '18 at 15:28
  • I don’t think it’s because of that, but I know what you mean about the last insert id. I’ll update my answer in a few minutes. Hang on, I won’t take too long. – Zeke Feb 01 '18 at 15:40
  • I'm glad to hear that, I'm sorry it took way too long to fix your issue, sometimes it's hard to solve when one doesn't have access to the database structure and relations, let alone when the coding habits are different. In any case, I'm glad we could find a solution. There is still a lot I would change about your databases, though, so consider reading good practices. – Zeke Feb 01 '18 at 16:05
  • It's okay I appreciate your help. I realize that I still have lots to learn Btw I followed your twitter if you don't mind. @Zeke – Dharma Feb 01 '18 at 16:10
  • @Zeke hey bro, can you have a look at my updated code, i have tried to use your code, it entering into database 3 times as a different "ID". You can have a look on the image i have provided. I'm trying to check the input from the database before inserting. So means it checking the availability of the number before inserting into database – Dharma Feb 10 '18 at 15:45
  • @DHARMA If you had problems after the question was resolved, then you should have created a new one. You're going to confuse people who are looking for answers by doing this. I'd suggest you undo your changes and create a new question or ask me personally. And do **NOT** call me _bro_. – Zeke Feb 10 '18 at 15:48
  • @Zeke okay i will create a new question – Dharma Feb 10 '18 at 15:55
  • And honestly, what you're asking me now is rather simple and I'm shocked you can't see it. **Don't forget to undo the changes you made to your question**. – Zeke Feb 10 '18 at 15:55
  • You know... there **is** a reason why the `foreach` was placed after the lottery ticket creation. You didn't respect that and now you broke it all. – Zeke Feb 10 '18 at 15:58
  • https://stackoverflow.com/questions/48722759/insert-into-table-using-array-method-with-parent-id @Zeke i have created my question and undo the older question – Dharma Feb 10 '18 at 16:08
  • You haven’t undone the changes, I can still see them here. I’m being dead serious about getting this question back to how it was before. People will get confused. I’m not gonna see your new question until this one is back to normal. – Zeke Feb 10 '18 at 16:11
  • Alright, now it’s back. I’ll check your other question soon. But I believe someone will find the issue blazing fast before I even get there. Since I actually already know what’s wrong and it’s pretty obvious. – Zeke Feb 10 '18 at 16:17
0

First check how you taking post value of your gamecenter field.You use it here as a multiple dynamic field so you need to name your field in dynamic way like gamecenter[] not a static name .if you make it static then the value of it will be static and overwritten.You need to rename this field so that it can represent a dynamic name. You can take the value by accessing the index by row number. so you need to make a foreach to catch the right $_POST['gamecenter'][i] then apply your condition.I think it will work fine then.

thank you. please let me know if any problem happend next.