Как добавить идентификатор первой таблицы в поле id_position второй таблицы, когда я нажимаю кнопку отправить? - PullRequest
1 голос
/ 19 января 2020

У меня есть две таблицы. Как добавить идентификатор первой таблицы в поле position_id второй таблицы, когда я нажимаю кнопку отправить? Мой запрос отправлен с помощью ajax. Поля для второй таблицы являются динамическими; Вы можете добавить их столько, сколько захотите. Например, если у меня было 5 записей, которые были добавлены в базу данных, то position_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);
        }  


    }
  }

 }
?>

1 Ответ

0 голосов
/ 19 января 2020

Если я правильно понял ваш вопрос, 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);
        }  


    }
  }

 }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...