PHP和MySQL:插入选择错误的$行

时间:2014-01-16 21:23:40

标签: php mysql

我的小脚本需要帮助。 您看,当我按$_POST['accept_req']时,它不会选择我想要的$req_user$row['username'])。它选择上面的行或它下面的行,我不知道该怎么做。

$requests = mysql_query("SELECT * FROM `party_requests` WHERE party_id = '$get_party_id'");

while ($row = mysql_fetch_array($requests, MYSQL_ASSOC)){   

    $req_user = mysql_real_escape_string($row['username']);

    if(isset($_POST['accept_req'])){
        $query = mysql_query("INSERT INTO party_members (`party_id`, `username`) VALUES ('".$get_party_id."', '".$req_user."')") or die("Could not be completed.");
        $result = mysql_query($query);
        mysql_query("DELETE FROM party_requests WHERE party_id = '$get_party_id' AND username = '$req_user' ");
        header("Location: ". $_SERVER['REQUEST_URI']);
        exit;
    }

    echo "<p>", $req_user, "<form action='' method='post'>", "<input type='submit' name='accept_req' value='Accept'/>", "</form>" ,"</p>";

}

我知道mysql_*已被弃用,请忽略它。

2 个答案:

答案 0 :(得分:0)

select语句在

之外
if(isset($_POST['accept_req'])){...}

所以代码检索错误的id。如果我理解你想要做什么,你需要把它放在if语句中

答案 1 :(得分:0)

你可以这样做。

$requests = mysql_query("SELECT * FROM `party_requests` WHERE party_id = '$get_party_id'");

while ($row = mysql_fetch_array($requests, MYSQL_ASSOC))
{   
    $req_user =$row['username'];
}

if(isset($_POST['accept_req']) and isset($req_user))
 {
    $query = mysql_query("INSERT INTO party_members (`party_id`, `username`) VALUES ('".$get_party_id."', '".$req_user."')") or die("Could not be completed.");
    $result = mysql_query($query);
    mysql_query("DELETE FROM party_requests WHERE party_id = '$get_party_id' AND username = '$req_user' ");
    header("Location: ". $_SERVER['REQUEST_URI']);
    exit;
   }

echo "<p>", $req_user, "<form action='' method='post'>", "<input type='submit' name='accept_req' value='Accept'/>", "</form>" ,"</p>";

或者这样:

 if(isset($_POST['accept_req']))
 {
   $requests = mysql_query("SELECT * FROM `party_requests` WHERE party_id = '$get_party_id'");
   while ($row = mysql_fetch_array($requests, MYSQL_ASSOC))
   {   
       $req_user =$row['username'];
   }

    $query = mysql_query("INSERT INTO party_members (`party_id`, `username`) VALUES ('".$get_party_id."', '".$req_user."')") or die("Could not be completed.");
    $result = mysql_query($query);
    mysql_query("DELETE FROM party_requests WHERE party_id = '$get_party_id' AND username = '$req_user' ");
    header("Location: ". $_SERVER['REQUEST_URI']);
    exit;
 }

   if(mysql_num_rows($requests)){  //If there isn't any results it outputs "No requests"
echo "<p>", $req_user, "<form action='' method='post'>", "<input type='submit' name='accept_req' value='Accept'/>", "</form>" ,"</p>";
}else{
    echo "No requests";
}