Php 无法使用循环在mysqli中插入多个数据
我想把一个人的facebook好友存储到一张表中。下面代码的结果显示只插入了一条记录。这不是我循环的问题,因为我呼应了这个名字,这一切都出现了Php 无法使用循环在mysqli中插入多个数据,php,mysql,mysqli,Php,Mysql,Mysqli,我想把一个人的facebook好友存储到一张表中。下面代码的结果显示只插入了一条记录。这不是我循环的问题,因为我呼应了这个名字,这一切都出现了 foreach($user_friends['data'] as $friend){ //echo $friend['name'] . "</br>"; $userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&am
foreach($user_friends['data'] as $friend){
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3 = $db->prepare("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)");
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid);
$stmt3->execute();
}
foreach($user\u friends['data']作为$friend){
//echo$friend['name']。“”;
$userImg=”https://graph.facebook.com/“$friend['id']”/picture?宽度=200,高度=200”;
$friendsName=$friend['name'];
$stmt3=$db->prepare(“插入到allfriend(`uId`、`name`、`img`、`friendOf`)值(?,,?,?)”;
$stmt3->bind_param('ssss',$user_fbid,$friendsName,$userImg,$user_fbid);
$stmt3->execute();
}
您稍微误用了prepare/bind功能。您只需要准备一次,但每次使用后确实需要重置语句
此外,你应该检查你的陈述是否失败。如果你这样做,你可能会发现为什么事情可能与你预期的不同
您的列friend.uID
是否可能实际上是主键?显示的代码尝试将相同的值插入多行。那可能是你的问题
试试这个:
$stmt3 = $db->prepare
("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)")
|| die "prepare failed: ". $db->error;
foreach($user_friends['data'] as $friend) {
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid)
|| die "bind_param failed " . $db->error;
$stmt3->execute()
|| die "execute failed " . $db->error;
$stmt3->reset()
|| die "reset failed " . $db->error;
}
$stmt3=$db->prepare
(“插入allfriend(`uId`、`name`、`img`、`friendOf`)值(?,,?,?))
||模具“准备失败:”$db->错误;
foreach($user_friends['data']作为$friends){
//echo$friend['name']。“”;
$userImg=”https://graph.facebook.com/“$friend['id']”/picture?宽度=200,高度=200”;
$friendsName=$friend['name'];
$stmt3->bind_param('ssss',$user_fbid,$friendsName,$userImg,$user_fbid)
||die“绑定参数失败”。$db->错误;
$stmt3->execute()
||死“执行失败”。$db->错误;
$stmt3->reset()
||模具“重置失败”。$db->错误;
}
您无需每次调用prepare
和bind_param
。在循环之前调用它们,然后在循环内部调用execute
,这将是一个问题。但目的是帮助我们互相学习。