插入命令失败

时间:2017-05-06 20:41:57

标签: php mysql join

所以,我在将数据输入此表时遇到问题。我有一个类似的会员表设置。如果我将插入更改为查询到成员资格从加入一切正常,但一旦我更改表加入它就停止工作。该表似乎已正确设置,因为它与我的成员资格表基本相同,但由于某种原因,数据不会插入。我想不出可能导致我的问题的原因,所以我来找专家。

请注意,此代码在进入不同的表时都能正常运行。提前谢谢。

if ( isset($_POST['btn-join']) ) {

    // clean user inputs to prevent sql injections
    $groupID = trim($_POST['groupID']);
    $groupID = strip_tags($groupID);
    $groupID = htmlspecialchars($groupID);      

    $teamname = trim($_POST['teamname']);
    $teamname = strip_tags($teamname);
    $teamname = htmlspecialchars($teamname);

    // Query groups to set group name
    $query2 = "SELECT groupName FROM groups WHERE groupID='$groupID'";
    $result2 = mysqli_query($con,$query2);
    $groupquery = mysqli_fetch_array($result2,MYSQLI_ASSOC);
    $groupname = $groupquery['groupName'];

    // groupID validation
    if (empty($groupID)) {
        $error = true;
        $groupIDError = "Please enter valid Group ID.";
    } else {
        // check email exist or not
        $query3 = "SELECT groupID FROM groups WHERE groupID='$groupID'";
        $result3 = mysqli_query($con,$query3);
        $count = mysqli_num_rows($result3);
        if($count!=1){
            $error = true;
            $groupIDError = "Provided Group does not exist.";
        }
    }

    // basic teamname validation
    if (empty($teamname)) {
        $error = true;
        $nameError = "Please enter your Team Name.";
    } else if (strlen($teamname) < 3) {
        $error = true;
        $nameError = "Team Name must have at least 3 characters.";
    }

    // if there's no error, continue to signup
    if( !$error ) {

        $query = "INSERT INTO join(groupID,userID,groupName,teamName) VALUES('$groupID','$userID','$groupname','$teamname')";
        $membership = mysqli_query($con,$query);

        if ($membership) {
            $errTyp = "success";
            $errMSG = "Account successfully updated";
            header("Location: dashboard.php");

        } else {
            $errTyp = "danger";
            $errMSG = "Something went wrong, try again later...";   
        }   
    }
}

SQL:

CREATE TABLE IF NOT EXISTS `join` (
  `jID` int(11) NOT NULL AUTO_INCREMENT,
  `groupID` varchar(32) NOT NULL,
  `userID` varchar(32) NOT NULL,
  `groupName` varchar(35) NOT NULL,
  `teamName` varchar(32) NOT NULL,
  `joinDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`jID`),
  UNIQUE KEY `groupID` (`groupID`,`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

1 个答案:

答案 0 :(得分:4)

join是SQL中的保留字。要避免这些问题,请在表名和列名周围使用反引号:

$query = "INSERT INTO `join`(`groupID`,`userID`,`groupName`,`teamName`) VALUES('$groupID','$userID','$groupname','$teamname')";
$membership = mysqli_query($con,$query);

作为旁注,您应该真正重写此查询以使用预准备语句,然后将变量绑定到它。这是一个等待发生的SQL注入。