[英]How to display data from one table and then insert that data to another table in php?
我需要从mem_count等于2的表中获取数据,然后在最后一个unique_id之后将该数据插入另一个表。
这是我的代码:
$mem_count2=mysql_query("SELECT mem_count,mem_id FROM member_status WHERE mem_count = 2 order by mem_id ASC");
if(mysql_num_rows($mem_count2 )==0){
die(mysql_error());
}
else{
$start_value=00;
// $start_value dynamically comes from other table which i am not mentioning here
// $start_value can starts from any number For Eg. 2, 5.
while ($row=mysql_fetch_array($mem_count2)) {
$uniq_code="PHR-" . str_pad((int) $start_value, 2, "0", STR_PAD_LEFT);
//if mem_id already inserted then use IGNORE in INSERT i.e INSERT IGNORE
$cql = "INSERT IGNORE INTO member_code (mem_id, temp_code,unique_code) values ('".$row['mem_id']."','".$row['mem_count']."','".$uniq_code."')";
mysql_query($cql) or exit(mysql_error());
$start_value++;
}
}
它运行顺利,但有时我得到这个输出:
+------------+-------------+
| mem_id | unique_code |
+------------+-------------+
| 1 | PHR-01 |
+------------+-------------+
| 5 | PHR-02 |
+------------+-------------+
| 3 | PHR-04 |
+------------+-------------+
在INSERT IGNORE查询中肯定存在一些问题!我已将mem_id设为UNIQUE。 请纠正这一点,因为我完全陷入困境!
Member_code结构
+------------+-------------+-----+
| mem_id | unique_code | Id |
+------------+-------------+-----+
| 1 | PHR-01 | 1 |
+------------+-------------+-----+
| 5 | PHR-02 | 5 |
+------------+-------------+-----+
| 3 | PHR-04 | 3 |
+------------+-------------+-----+
这可能是因为你在这一行的某个时刻出现了错误
mysql_query($cql) or exit(mysql_error());
然后你的增量变量将递增以进行下一次插入。 您应该测试插入,如果没有出错,则执行增量。
当结果存储在$mem_count
时,您在代码中使用了一个名为$mem_count2
的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.