【问题标题】:How to add the id of the first table to the id_position field of the second table when I click submit?点击提交时如何将第一个表的id添加到第二个表的id_position字段中?
【发布时间】:2020-05-05 09:45:07
【问题描述】:

我有两张桌子。点击提交时如何将第一个表的id添加到第二个表的position_id字段中?我的请求是使用 ajax 发送的。第二个表的字段是动态的;您可以根据需要添加任意数量。例如,如果我有 5 条记录添加到数据库中,那么应该为所有记录添加 position_id,即第一个表的 id。 //我的代码

//data base
CREATE TABLE IF NOT EXISTS `article` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;

CREATE TABLE IF NOT EXISTS `data` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `position_id` int(10) NOT NULL,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
//index.php
<html>
<head>
<title>Dynamically add input field using jquery</title>
<style>
.container1 input[type=text] {
padding:5px 0px;
margin:5px 5px 5px 0px;
}


.add_form_field
{
    background-color: #1c97f3;
    border: none;
    color: white;
    padding: 8px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border:1px solid #186dad;

}

input{
    border: 1px solid #1c97f3;
    width: 260px;
    height: 40px;
    margin-bottom:14px;
}

.delete{
    background-color: #fd1200;
    border: none;
    color: white;
    padding: 5px 15px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    margin: 4px 2px;
    cursor: pointer;

}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".container1"); 
    var add_button      = $(".add_form_field"); 

    var x = 1; 
    $(add_button).click(function(e){ 
        e.preventDefault();
        if(x < max_fields){ 
            x++; 
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
        }
        else
        {
        alert('You Reached the limits')
        }
    });

    $(wrapper).on("click",".delete", function(e){ 
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
    $('#submit').click(function(){       
      $.ajax({  
                url:"name.php",  
                method:"POST",  
                data:$('#add_name').serialize(),  
                success:function(data)  
                {  
                     $('#mess').html(data);
                     $("#content").hide(); 
                }  
           }); 
    });
});
</script>
</head>
<body>
<span id="mess"></span>

<div id="content">
<form name="add_name" id="add_name"> 
    Title:<br>
    <input type="text" name="title">
<div class="container1">

    <button class="add_form_field">Add New Field &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span></button>

    <div><input type="text" name="mytext[]"></div>


</div>
Description:<br>
<textarea cols="50px" rows="15px" name="description"></textarea><br>
Text:<br>
<textarea cols="50px" rows="15px" name="text"></textarea><br>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
</div>
</body>
</html>
//name.php
<?php
$number = count($_POST["mytext"]);  

if($number > 0)  
 { 
   $title = $_POST["title"];
   $desc = $_POST["description"];
   $text = $_POST["text"];   

  $connect = new PDO('mysql:dbname=test_db;host=localhost','root','',
  array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));



   if(trim($title)!='' || trim($desc)!='' || trim($text)!='')
   {
        try{
          $query = "INSERT INTO article
              (title, description, text) 
              VALUES (:title, :description, :text)";
          $statement = $connect->prepare($query);
          $statement->execute(
           array(
            ':title'   => $title,
            ':description'  => $desc, 
            ':text' => $text
            )
          );
        }
        catch(PDOException $e){
          throw new Exception($e -> getMessage() . "  " . get_class($this).' -> '.__METHOD__);
          $file = "exceptionlog.txt";
          file_put_contents($file, $e -> getMessage(), FILE_APPEND);
        }
        echo "Added!";
   }                
  for($i=0; $i<$number; $i++)  
  {
    if(trim($_POST["mytext"][$i] != ''))  
    {
       try{
        $query = "INSERT INTO data
          (name) 
          VALUES (:name)";
          $data = array(':name'   => $_POST["mytext"][$i]);
          $statement = $connect->prepare($query);
          $statement->execute($data);
        }
        catch(PDOException $e){
          throw new Exception($e -> getMessage() . "  " . get_class($this).' -> '.__METHOD__);
          $file = "exceptionlog.txt";
          file_put_contents($file, $e -> getMessage(), FILE_APPEND);
        }  


    }
  }

 }
?>

【问题讨论】:

    标签: php html ajax pdo


    【解决方案1】:

    如果我正确理解了您的问题,LastInsertId() 就是您的工具。 https://www.w3schools.com/php/php_mysql_insert_lastid.asp

    //name.php
    <?php
    $number = count($_POST["mytext"]);  
    
    if($number > 0)  
     { 
       $title = $_POST["title"];
       $desc = $_POST["description"];
       $text = $_POST["text"];   
    
      $connect = new PDO('mysql:dbname=test_db;host=localhost','root','',
      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
    
    
    
       if(trim($title)!='' || trim($desc)!='' || trim($text)!='')
       {
            try{
              $query = "INSERT INTO article
                  (title, description, text) 
                  VALUES (:title, :description, :text)";
              $statement = $connect->prepare($query);
              $statement->execute(
               array(
                ':title'   => $title,
                ':description'  => $desc, 
                ':text' => $text
                )
              );
             $position_id = $statement->LastInsertId();
            }
            catch(PDOException $e){
              throw new Exception($e -> getMessage() . "  " . get_class($this).' -> '.__METHOD__);
              $file = "exceptionlog.txt";
              file_put_contents($file, $e -> getMessage(), FILE_APPEND);
            }
            echo "Added!";
       }                
      for($i=0; $i<$number; $i++)  
      {
        if(trim($_POST["mytext"][$i] != ''))  
        {
           try{
            $query = "INSERT INTO data
              (name, position_id) 
              VALUES (:name, '".$position_id."')";
              $data = array(':name'   => $_POST["mytext"][$i]);
              $statement = $connect->prepare($query);
              $statement->execute($data);
            }
            catch(PDOException $e){
              throw new Exception($e -> getMessage() . "  " . get_class($this).' -> '.__METHOD__);
              $file = "exceptionlog.txt";
              file_put_contents($file, $e -> getMessage(), FILE_APPEND);
            }  
    
    
        }
      }
    
     }
    
    

    【讨论】:

    • lastInsertId () 是 PDO 类方法,而不是 PDOStatement 类。 $position_id = $connect->LastInsertId();我认为这更正确。感谢您的链接,有用
    猜你喜欢
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多