简体   繁体   English

当我获取数据并将其插入表中时查询不起作用

[英]Query does not work when i fetch data and insert it into a table

I am trying to insert to another table the results of a select statement from another table. 我试图将另一个表中的select语句的结果插入到另一个表中。 The select statement works but the insert statement does not work. select语句有效,但是insert语句无效。 Please help me. 请帮我。

$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)) {
  $csubject=$row['sub_name'];
  $cday=$row['sub_day'];
  $ctime=$row['sub_time'];

  echo "<strong>". $csubject . "</strong>";
}

$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");

header("Location:homeclient.php");
?> 

You asked for how to do these two as one query. 您询问如何将这两个查询合并为一个查询。

This is how: 这是这样的:

$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");

// I would also add error checking
if ( mysql_errno() )
    echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)) {
  $csubject=$row['sub_name'];
  $cday=$row['sub_day'];
  $ctime=$row['sub_time'];

  echo "<strong>". $csubject . "</strong>";
  $query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}   
header("Location:homeclient.php");
?> 

Try changing to this. 尝试更改为此。 Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results. 当前,您的查询不在您的时间范围内,它只会运行一次,并且$ csubject等的值始终将是获取的结果的最后一个值。

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

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