简体   繁体   English

如何从表A获取INT类型的ID并将其插入到另一个表中? 在PHP中

[英]How to get INT-type id from Table A and insert it into another table? In PHP

I am not doing insert query, so the mysqli_insert_id doesnt' work. 我没有在执行插入查询,因此mysqli_insert_id无法正常工作。

I need to select an id(Primary, INT) from Table A which will be inserted into Table B. 我需要从表A中选择一个id(Primary,INT),它将插入表B中。

My Tables Structure: 我的表格结构:

Table book:
-id (Primary, Auto Increment, INT)
-title
-publisher_id (Foreign key to Table publisher.pub_id, INT)

Table publisher:
-pub_id (Primary, Auto Increment, INT)
-publisher

I tried like this: 我这样尝试过:

$query ="SELECT pub_id FROM book WHERE publisher = '$publisher' ";
$result=$mysqli->query($query);
$pub_id=$result->fetch_assoc();

$query ="INSERT INTO book (title,publisher_id)
              VALUES ('$title', '$pub_id['pub_id']')";
$mysqli->query($query);

Then I got error message like: 然后我得到了如下错误消息:

syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) 

Is there something wrong with the data type or something else? 数据类型是否有问题或其他原因?

How to get INT-type id from Table book and insert it into another table? 如何从Table Book获取INT类型的ID并将其插入到另一个表中?

It doesn't work because you are doing this: 它不起作用,因为您正在执行以下操作:

$query ="INSERT INTO book (title,publisher_id)
              VALUES ('$title', '$pub_id['pub_id']')";

Try this instead: 尝试以下方法:

$query ="INSERT INTO book (title,publisher_id)
              VALUES ('$title', '".$pub_id['pub_id']."')";

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

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