-3
我有一些PHP/SQL創建組:PHP - 爲什麼這個代碼中插入兩個行並表
if(isset($_POST['group_name'], $_POST['description'], $_POST['invites'])){
$invites = explode(',', $_POST['invites']);
$user_id = $_SESSION['user_id'];
foreach(secure_mysqli("SELECT `username` FROM `users` WHERE `user_id` = ?", array($user_id), "i") as $result){
$logged_in_username = $result;
}
if(in_array($logged_in_username, $invites)){
}else{
$invites[] = $logged_in_username;
}
foreach($invites as &$invite) {
if(empty(secure_mysqli("SELECT `user_id` FROM `users` WHERE `username` = ?", array($invite), "s"))) {
exit("1 or more of the users that you entered do(es) not exist!");
}
}
create_group($_POST['group_name'], $_POST['description'], $invites);
}
function create_group($name, $description, $invites){
$names = secure_mysqli("SELECT `group_name` FROM `groups` WHERE `group_name` = ?", array($name), "s");
$descriptions = secure_mysqli("SELECT `group_description` FROM `groups` WHERE `group_description` = ?", array($description), "s");
if(empty($names) && empty($descriptions)) {
secure_mysqli("INSERT INTO `groups` (`group_name`, `group_description`) VALUES (?, ?)", array($name, $description), "ss");
} else {
echo 'Group with that name/description already exists.';
}
foreach(secure_mysqli("SELECT `group_id` FROM `groups` WHERE `group_name` = ?", array($name), "s") as $result) {
$group_id = $result;
}
foreach($invites as &$invite) {
foreach(secure_mysqli("SELECT `user_id` FROM `users` WHERE `username` = ?", array($invite), "s") as $id) {
secure_mysqli("INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES (?, ?, ?)", array($group_id, $id, 0), "iii");
}
}
}
function secure_mysqli($query, $values, $datatypes) {
global $link;
$stmt = mysqli_prepare($link, $query);
if($stmt !== false){
if(is_array($values)){ foreach ($values as &$value) $ref_values[] = &$value;
call_user_func_array("mysqli_stmt_bind_param", array_merge(array($stmt, $datatypes), $ref_values));
mysqli_stmt_execute($stmt);
return @mysqli_fetch_array(mysqli_stmt_get_result($stmt));
}}}
對不起,你淹沒在代碼中。出於某種原因,這條線:
secure_mysqli("INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES (?, ?, ?)", array($group_id, $id, 0), "iii");
似乎插入兩行到表中的每個用戶,而不是1。我不知道爲什麼會這樣。請幫忙!
順便說一句,我一直在努力工作,但我仍然是PHP的初學者。
預先感謝您。
1.沒有人喜歡嘗試破譯一段代碼。儘量減少你的問題到一個合理的測試用例。 2.將輸入值提供給腳本;在這種情況下$ _POST變量。 – timclutton
@timclutton好吧,我會盡力做到這一點。 $ _POST變量可能等於'group1','第一組',數組('User1,User2') – Petrus