2015-12-22 65 views
2

這是一個動態添加文本字段的代碼。當我們點擊一​​個鏈接時,它會自動添加文本字段,並將數據傳遞給數據庫。但是現在,我需要點擊鏈接後的兩個文本字段並將值傳遞給數據庫。我可以實現它嗎? 的代碼如下所示使用foreach循環傳遞兩個變量

的index.php

<?php 
    require("dbconn.php"); 
    ?> 

    <html> 
    <head> 
    <title></title> 
    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript"> 
    var counter = 0; 
    $(function(){ 
     $('p#add_field').click(function(){ 
      counter += 1; 
      $('#container').append(
        '<strong>Hobby No. ' + counter + '</strong><br />' 
        + '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />' 
        +'<input id="field_' + counter + '" name="name[]' + '" type="text" /><br />'); 

     }); 
    }); 
    </script> 

    <body> 

    <?php 
    if (isset($_POST['submit_val'])) { 
    if ($_POST['dynfields']) { 
    foreach ($_POST['dynfields'] as $key=>$value) { 
    $values = mysql_real_escape_string($value); 
    $query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection); 

    } 
    } 

     echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>"; 

     mysql_close(); 
    } 
    ?> 
    <?php if (!isset($_POST['submit_val'])) { ?> 
     <h1>Add your Hobbies</h1> 
     <form method="post" action=""> 


      <div id="container"> 
       <p id="add_field"><a href="#"><span>Click To Add Hobbies</span></a></p> 
      </div> 

      <input type="submit" name="submit_val" value="Submit" /> 
     </form> 
    <?php } ?> 

    </body> 
    </html> 

在這裏,在index.php頁面中點擊添加文本字段會給動態文本fields.I要添加兩個或更多的文本字段,並希望通過數據庫的值

+0

什麼是你面對你.............嘗試添加名稱字段也是問題,但你不使用它。 –

+0

但我怎麼能傳遞值使用foreach循環的數據庫 – Lekshmy

回答

0

可能是您的mysql連接字符串不正確(如果您將$values作爲空白測試替代方法,則刪除mysql_real_escape_stringecho "INSERT INTO my_hobbies (hobbies) VALUES ('$value')"並查看這是否爲所需的SQL字符串)。

注意:開始使用mysqli或pdo,因爲mysql已被棄用。

你可以嘗試這樣的:

<?php 

     if (isset($_POST['submit_val'])) { 
     $mysqli = new mysqli('localhost','root','root','hobby');//make sure your connection is made 
     if (mysqli_connect_errno()) { 
      echo "Problem in connection"; 
      exit(); 
     } 
     if ($_POST['dynfields']) { 
     foreach ($_POST['dynfields'] as $key=>$value) { 
     $values = $mysqli->real_escape_string($value); 
     // echo $values; 
     $sql= "INSERT INTO my_hobbies (hobbies) VALUES ('$values')"; 
     //echo $sql; 
     $mysqli->query($sql); 
     if($mysqli->errno > 0){ 
      echo "PROBLEM WHILE SAVING"; 
      exit; 
     } 
     } 
     } 

      echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>"; 

      mysql_close(); 
     } 
     ?>