1

I have a web page with many rows which has two input.Maybe 10 rows, maybe 100 rows, it depends on how many times button addP is clicked. These input values should be inserted into IDC table with idc_addDVC.php.

I want to use while loop for many input data.But unfortunately these data can't be inserted into IDC table with my idc_addDVC.php.

ClOUDT and IDC tables show nothing after submit.Here is my JS code:

<script>
var aDWI=1;
function addPf()
{
    newrow = '<tr><td style="width:25%" colspan="2"><input style="width:98%" name="enName'+aDWI+'"></td><td style="width:85%" colspan="2"><input style="width:98%" name="enID'+aDWI+'"></td></tr>'; 
    $(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
     aDWI = aDWI + 1;   
    $('#engID').attr("value",aDWI);
}
</script>

Here is my html code:

<div>
  <form action="idc_addDVC.php?act=add&table=IDC" method="POST">
    <table>
      <tr>
          <input type="button" id="addP" onclick="addPf()" value="AP">
      </tr>
      <tr>
         <input type="text"  name="enName">
         <input type="text"  name="enID">
      </tr>
      <tr>
          newrow is added here
      </tr>
      <tr>
         <td>
           <input type="submit" value="submitBtn">
           <input type="hidden"  id="engID" value="1" name="engRow">
         </td>
     </tr>
    </table>
 </form>
</div>

Here is fail idc_addDVC.php code:

<?php
 if($_GET["act"]=="add")
{
   $conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxx');

   $query="begin declare i int;
           set i=1;
           insert into ClOUDT (customer) values ('JOHN');
           while i < ".$_POST['engRow']."
           do
             insert into  IDC (name,id,cloudeid) values('".$_POST['enName'+i]."','".$_POST['enID'+i]."',LAST_INSERT_ID());
           set i=i+1;
           end while; 
           commit;";
   $stmt=$conn->query($query);
  echo "success";
  ......
 }
 else
 {
   echo "fail";
   ......
 }
}
?>

Here is successful idc_addDVC.php code:

 <?php
 if($_GET["act"]=="add")
{
   $conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx','root','xxx');

   $query="begin ;
           insert into ClOUDT (customer) values ('JOHN');
           insert into  IDC (name,id,cloudeid) values('".$_POST['enName']."','".$_POST['enID']."',LAST_INSERT_ID());
           commit;";
   $stmt=$conn->query($query);
  echo "success";
  ......
 }
 else
 {
   echo "fail";
   ......
 }
}
?>

I suppose 'enName'+i in $query of idc_addDVC.php is wrong. But i have no idea how to get the dynamic input values.It is complex , who can help me ?

stack
  • 821
  • 1
  • 15
  • 28
  • Questions which ask for debugging (so called "Help, my code doesn't work" questions) tend to be voted down and then closed. Can you debug and refine your issue to a specific problem, for which you can ask advice? What debugging have you tried? I'd also try to tidy your question formatting up too, use backticks to mark variable, file and table names as code in your paragraphs and inject some PSR-2 into your code formatting... – wally Aug 08 '17 at 08:20
  • Your form is using the "POST" method, while in your PHP you're referring to a "GET". Change the `if($_GET["act"])` to `if($_POST["act"])`. I would also remove the variables you've included in the form action, leaving the `idc_addDVC.php` and instead pass those parameters via hidden form inputs. – mickburkejnr Aug 08 '17 at 09:14
  • @wally,I have no idea about inerting many rows data into DB. So i need help.I have tried 'enName'+i, 'enName'$i, 'enName+$i','enName.$i.', but all of them are wrong.Maybe the while loop is wrong. So PHP expert's help is needed. – stack Aug 09 '17 at 03:15
  • @mickburkejnr,GET and POST method is not the key.Actually, i want to use loop to insert many row data in idc_addDVC.php. I had tried many style, just like 'enName+$i', 'enName.$i', 'enName'+i in POST para, but all of them are wrong – stack Aug 09 '17 at 03:18

2 Answers2

1

HTML

Remove onclick attribute and attach onclick event handler using jQuery.

<input type="button" id="addP" value="AP">

JavaScript

Use array notation [] when building input names. It makes it easier to loop through POSTed fields afterwards. And avoids you having to keep track of your last row with engRow.

$('#addP').click(function () {
    $('#staTable tr:last-child').before('
        <tr><td colspan="2" style="width:25%"><input name="enName[]" style="width:98%"></td></tr>
    ');
});

PHP

I would do the bulk insert within a transaction instead of a stored procedure.

<?php
// turn on error reporting in case
error_reporting(E_ALL);
ini_set('display_errors', 1);

// wrong: == (comparaison), not = (assignment)
if ($_GET['act'] == 'add') {
    try {
        $conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxx');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $conn->beginTransaction();

        // wrong: INSERT INTO, not INSET INTO
        $sth = $conn->prepare("INSERT INTO cloudt(customer) VALUES('JOHN')");             
        $sth->execute();
        $cloudeid = $conn->lastInsertId();

        // $_POST['enName'] should be an array

        foreach ($_POST['enName'] as $name) {
            $sth = $conn->prepare("INSERT INTO idc(name, cloudeid) VALUES(?, ?)");
            $sth->execute(array($name, $cloudeid));
        }
        $conn->commit();
        echo "success";
    } catch (PDOException $e) {
        echo $e->getMessage();
        $conn->rollBack();
        echo "fail";
    }
}
?>

Useful readings

Mikey
  • 6,728
  • 4
  • 22
  • 45
  • When $conn->beginTransaction() and $conn->commit() were added, it worked fail. My PDO connection is :$conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxxx'); – stack Aug 09 '17 at 06:54
  • i hava tested, $conn->beginTransaction() can pass,$conn->query($query); can pass.But $conn->commit() can not pass.There is no error information, just hold on at $conn->commit(); – stack Aug 09 '17 at 09:49
  • @Mikey.it shows "SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute." – stack Aug 09 '17 at 13:57
  • @Mikey.After change:$conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn->commit();can pass.But data can not be inserted into table. – stack Aug 09 '17 at 14:00
  • @stack That is not how you use [PDO::setAttribute](http://php.net/manual/en/pdo.setattribute.php): it only has two arguments. For `PDO::MYSQL_ATTR_USE_BUFFERED_QUER‌​Y`, the value should be a boolean. The only reason why it goes to the `$conn->commit()` is because you disabled the exception handling. Undo everything. I've never had this issue before but the cause may have been from what you initially did before. – Mikey Aug 09 '17 at 14:35
  • @stack Look at [similar questions on SO](https://stackoverflow.com/search?q=Cannot+execute+queries+while+other+unbuffered+queries+are+active) regarding your error -- as well as this [Sitepoint post](https://www.sitepoint.com/community/t/pdo-unbuffered-queries/214233/2). Some suggest to use `$sth->closeCursor()` or to `unset($sth)` after your executions. – Mikey Aug 09 '17 at 14:41
  • ,$sth->closeCursor() is OK.It works fine.My php version is php56-5.6.13, But i don't know why. Anyway thankyou very much – stack Aug 11 '17 at 01:19
0

After $sth->closeCursor() and array(PDO::ATTR_AUTOCOMMIT=>0) are added, it works fine.

if($_GET["act"]=="add")
{
  if($_POST['customerName']!= NULL)
  {
      try
      {
        $conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxx',array(PDO::ATTR_AUTOCOMMIT=>0));
      }
      catch(PDOException $e)
      {
        echo "connect failed!".$e->getMesage();
        exit;
      }  

      try
      {
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $conn->beginTransaction();
      $query="insert into cloudt (name) VALUES('JOHN');
              insert into  idc (name,id,phone,cloudtid) VALUES('".$_POST['engName3']."','".$_POST['engID3']."','".$_POST['engPhone3']."',LAST_INSERT_ID());               
              insert into  idc (name,id,phone,cloudtid) VALUES('".$_POST['engName4']."','".$_POST['engID4']."','".$_POST['engPhone4']."',LAST_INSERT_ID());";
      $stmt=$conn->query($query);
      $stmt->closeCursor();
      $conn->commit();
      echo "success";
     }
      catch (PDOException $e) {
              echo $e->getMessage();
              $conn->rollBack();
              echo "fail";
      }

   }
 }     
stack
  • 821
  • 1
  • 15
  • 28