我有两个关系
的表+----------------------+ +-----------------+
| Shape | | Point_Values |
+----------------------+ +-----------------+
| shape_id (KEY) | | id (KEY) |
| shape_name (VARCHAR) | | point_x (INT) |
+----------------------+ | point_y (INT) |
| shape_id (INT) |
+-----------------+
如何在同一个请求中获得形状和点的同时构建插入一般或CodeIgniter,这意味着当一个形状完成时,有一个点数组和形状名称/ id 。我必须在表格中插入,但两者都匹配shape_id。
按要求
Array ( [name] => "circle" [points] => Array ( [x] => Array ( [0] => 182 [1] => 190 [2] => 215 [3] => 240 [4] => 291 [5] => 328 [6] => 364 [7] => 391 [8] => 425 [9] => 459 [10] => 487 [11] => 512 [12] => 529 [13] => 540 [14] => 551 [15] => 560 [16] => 570 [17] => 581 [18] => 592 [19] => 604 [20] => 617 [21] => 628 [22] => 635 [23] => 639 [24] => 642 [25] => 642 [26] => 640 [27] => 630 [28] => 619 [29] => 606 [30] => 591 ) [y] => Array ( [0] => 165 [1] => 159 [2] => 150 [3] => 147 [4] => 144 [5] => 144 [6] => 147 [7] => 152 [8] => 162 [9] => 172 [10] => 184 [11] => 199 [12] => 211 [13] => 219 [14] => 225 [15] => 228 [16] => 231 [17] => 232 [18] => 233 [19] => 233 [20] => 231 [21] => 222 [22] => 204 [23] => 189 [24] => 156 [25] => 133 [26] => 120 [27] => 100 [28] => 85 [29] => 69 [30] => 54 ) ) )
答案 0 :(得分:1)
考虑到这个数组,这段代码应该很好用。它执行一个初始插入以从表格形状中获取id,并且所有点都是批量插入的。
function insertShape($s){
mysql_query('INSERT INTO shape (name) VALUES ("'.$s['name'].'");');
$id=mysql_insert_id();
$i=0;
for(;;){
if(!isset($s['points']['x'][$i], $s['points']['y'][$i]))break;
$inserts[]='('.$id.','.$s['points']['x'][$i].','.$s['points']['y'][$i].')';
$i++;
}
mysql_query('INSERT INTO point_values (shape_id,x,y) VALUES '.implode(',',$inserts));
}
如果你的情况不需要对钥匙进行严格的测试,我可能会把它变成一个foreach。
答案 1 :(得分:0)
我建议你使用基本算法,首先你在shape_id(point_value)
和shape_id(shape)
之间建立外键约束
首先插入形状表
mysql_query("INSERT INTO shape SET shape_name='".$array['name']."'");
然后获取 last_insert_id
$shape_id=mysql_insert_id();
然后转到point_value表
foreach( $array['points] as $k)
{
$qry= "INSERT INTO point_value SET
point_x=(int)$array['points']['x'][$i],
point_y=(int)$array['points']['y'][$i],
shape_id=(int)$shape_id ";
mysql_query($qry);
}
我希望这会帮助你......寻求帮助 感谢