PHP - 为什么这段代码在表中插入两行

时间:2014-07-19 22:09:40

标签: php mysql sql insert rows

我有一些PHP / SQL来创建一个组:

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的初学者。

提前谢谢。

0 个答案:

没有答案