简体   繁体   English

MYSQL 使用另一个表的外键将数据插入表中

[英]MYSQL Insert Data Into Table With Foreign Key From Another Table

I have two tables: book and borrowed_books .我有两张桌子: bookborrowed_books

Book Table has book_ID | Book Name Book Table 有book_ID | Book Name book_ID | Book Name

Borrowed_Books has student_ID | Book Name Borrowed_Booksstudent_ID | Book Name student_ID | Book Name

The Book names from both tables are Indexed.两个表中的书名都已编入索引。

I added the values of Book Table into an HTML Form select/option and it is being read but the problem is when I'm trying to insert the value, it's not reading the option name or value.我将 Book Table 的值添加到 HTML 表单选择/选项中,并且正在读取它,但问题是当我尝试插入值时,它没有读取选项名称或值。

HTML: HTML:

<select id="heard" class="form-control">
<option value="">Choose Book</option>
 <?php require_once '../mysql/bookssql.php';
  while($row = mysqli_fetch_array($data, MYSQLI_ASSOC)){ 
   echo '<option name="borrow_book" value="'.$row['Title'].'">' .$row['Title']. '</option>';
  }
 ?>
</select>

PHP Insert Code: PHP 插入代码:

<?php $borrow_book = $_POST['borrow_book'];
 $upload = "INSERT INTO `borrowed_books` (`student_ID`, `Book Name`) VALUES ('23, '$borrow_book');";
?>

The name should be in the <select> element, not the <option> s.名称应该在<select>元素中,而不是在<option>中。

<select id="heard" name="borrow_book" class="form-control">
<option value="">Choose Book</option>
 <?php require_once '../mysql/bookssql.php';
  while($row = mysqli_fetch_array($data, MYSQLI_ASSOC)){ 
   echo '<option value="'.$row['Title'].'">' .$row['Title']. '</option>';
  }
 ?>
</select>

You have a typo in $upload , there's an extra ' before 23 .您在$upload中有一个错字,在23之前有一个额外'

You should stop substituting variables directly into query strings, and use prepared statements with parameters.您应该停止将变量直接替换到查询字符串中,并使用带参数的准备好的语句。 See How can I prevent SQL injection in PHP?请参阅如何防止 PHP 中的 SQL 注入?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM