php - PDO 将 3 个表单值插入到 4 个表中

标签 php mysql forms pdo

我刚刚切换到 PDO,但 PHP 表单仍然存在问题。 该表格是为国家/地区用户的团队注册而制作的,每个国家/地区最多可以输入 2 名球员,最多 3 名球员。我创建了一个默认情况下适用于 3 名玩家的表单,第三种表单是可选的,以防他们需要添加一名玩家。

但是,我是 PDO 新手,我将向您展示整个脚本,以便您可以帮助我排除脚本故障。

脚本和表单位于同一个文件中,我运行测试,页面变成白色,没有错误。

现在我想做的是将至少 2 个/最多 3 个球队球员数据插入 MySQL。

这是我的 PHP 代码:

<?php 
try 
{
require_once 'connection_pdo.php';

    $championships = 'SELECT * FROM champs 
                      WHERE champ_status = 1 
                      ORDER BY champ_name ASC';
    $championships_results = $db->query($championships);

    $users = 'SELECT userid, username FROM users';
    $users_results = $db->query($users);

    $colname_numRows = "-1";
    if (isset($_SESSION['MM_UserGroup'])) {
      $colname_numRows = $_SESSION['MM_UserGroup']; 
    }

    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {

    $stmt = $db->prepare("INSERT INTO players (playerid, FirstName, LastName, Dob, NationalRanking, PhoneNumber, EmailAddress, CountryID)
    VALUES (:playerid, :FirstName, :LastName, :Dob, :NationalRanking, :PhoneNumber, :EmailAddress, :CountryID)");
    //player 1
    $stmt->bindParam(':FirstName', $_POST["playerFirstName1"]);
    $stmt->bindParam(':LastName', $_POST["playerLastName1"]);
    $stmt->bindParam(':Dob', $_POST['year1']."-".$_POST['month1']."-".$_POST['day1']);
    $stmt->bindParam(':Ranking', $_POST["playerNationalRanking1"]);
    $stmt->bindParam(':playerPhoneNumber', $_POST["playerPhoneNumber1"]);
    $stmt->bindParam(':playerEmailAddress', $_POST["playerEmailAddress1"]);
    $stmt->bindParam(':playerCountryID', $_POST["playerCountryID1"]);
    $stmt->execute();
    $last_ID_of_P1 = $db->lastInsertId();
    //player 2
    $stmt->bindParam(':FirstName', $_POST["playerFirstName2"]);
    $stmt->bindParam(':LastName', $_POST["playerLastName2"]);
    $stmt->bindParam(':Dob', $_POST['year2']."-".$_POST['month2']."-".$_POST['day2']);
    $stmt->bindParam(':Ranking', $_POST["playerNationalRanking2"]);
    $stmt->bindParam(':playerPhoneNumber', $_POST["playerPhoneNumber2"]);
    $stmt->bindParam(':playerEmailAddress', $_POST["playerEmailAddress2"]);
    $stmt->bindParam(':playerCountryID', $_POST["playerCountryID2"]);
    $stmt->execute();
    $last_ID_of_P2 = $db->lastInsertId();
    //player 3
    $stmt->bindParam(':FirstName', $_POST["playerFirstName3"]);
    $stmt->bindParam(':LastName', $_POST["playerLastName3"]);
    $stmt->bindParam(':Dob', $_POST['year3']."-".$_POST['month3']."-".$_POST['day3']);
    $stmt->bindParam(':Ranking', $_POST["playerNationalRanking3"]);
    $stmt->bindParam(':playerPhoneNumber', $_POST["playerPhoneNumber3"]);
    $stmt->bindParam(':playerEmailAddress', $_POST["playerEmailAddress3"]);
    $stmt->bindParam(':playerCountryID', $_POST["playerCountryID3"]);
    $stmt->execute();
    $last_ID_of_P3 = $db->lastInsertId();

    $stmt2 = $db->prepare("INSERT INTO participants (playerID, idparticipants, idChampionships, idUsers, created_at, status, booking_status) VALUES($last_ID_of_P1, :idparticipants, :idChampionships, :idUsers, :created_at, 1, 0)");

    //participant player 1
    $stmt2->bindParam(':idparticipants', $_POST["idparticipants1"]);
    $stmt2->bindParam(':idChampionships', $_POST["idChampionships1"]);
    $stmt2->bindParam(':idUsers', $_POST['idUsers1']);
    $stmt2->bindParam(':created_at', $_POST["created_at1"]);
    $stmt2->execute();
    $last_ID_of_participant_1 = $db->lastInsertId();

    //participant player 2
    $stmt2->bindParam(':idparticipants', $_POST["idparticipants2"]);
    $stmt2->bindParam(':idChampionships', $_POST["idChampionships2"]);
    $stmt2->bindParam(':idUsers', $_POST['idUsers2']);
    $stmt2->bindParam(':created_at', $_POST["created_at2"]);
    $stmt2->execute();
    $last_ID_of_participant_2 = $db->lastInsertId();

    //participant player 3
    $stmt2->bindParam(':idparticipants', $_POST["idparticipants3"]);
    $stmt2->bindParam(':idChampionships', $_POST["idChampionships3"]);
    $stmt2->bindParam(':idUsers', $_POST['idUsers3']);
    $stmt2->bindParam(':created_at', $_POST["created_at3"]);
    $stmt2->execute();
    $last_ID_of_participant_3 = $db->lastInsertId();

    $stmtTeam = $db->prepare("INSERT INTO teamPlayers (TeamID, idparticipant, idUsers, Idplayer1, Idplayer2, Idplayer3) VALUES(TeamID, 111021, $last_ID_of_P1, $last_ID_of_P2, $last_ID_of_P3)");
    $stmtTeam->execute();

    //upload script 1
    if(!is_dir("upload/".$_SESSION['MM_Username'])) {
    //do we need to make the uploads directory for the files?
    mkdir("upload/".$_SESSION['MM_Username']);
    //make the rest of the script safe, though this will only be done once
    if(is_uploaded_file($_FILES['uploadedfile']['tmp_name'])){ 
    $folder = "upload/".$_SESSION['MM_Username']; 
    $file = "/" .sha1(rand())."-" .basename($_FILES['uploadedfile']['name']);
    //basename( $_FILES['uploadedfile']['name']); 
    $full_path = $folder.$file; 

        $idPlayer       =   $last_ID_of_P1;
        $IP             =   $_SERVER['REMOTE_ADDR'];
        $FileLocation   =   $full_path;
        $idUsers        =   $_SESSION['MM_UserGroup'];

        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $full_path)){

            $sql_image ="INSERT INTO files(Time, FileLocation, IP, idUsers, idparticipant)values(NOW(),:FileLocation,:IP,:idUsers,:idparticipant)";
            $qry=$db->prepare($sql_image);
            $success = $qry->execute(array(':FileLocation'=>$full_path,':IP'=>$IP,':idUsers'=>$idUsers,':idparticipant'=>$idPlayer));
        }else{
            $sql_image ="UPDATE files SET Time=?, FileLocation=?, IP=?, idUsers=?, idparticipant=? where idUsers=?";
            $qry=$db->prepare($sql_image);
            $success = $qry->execute(array(NOW(), $full_path, $IP, $idUsers, $idPlayer));   
        }

        if($success){
            echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>";
            echo "<script language='javascript' type='text/javascript'>window.open('listfiles.php','_self')</script>";
        }else{
            echo 'db transaction failed';
        }
    } else { 
       echo "upload received! but process failed";
            } 
    }
    else{ 
    echo "upload failure ! Nothing was uploaded";
        } 
    }
}//upload script2 

catch (PDOException $e) 
{
    //$error = $e->getMessage();    
    echo "Error: " . $e->getMessage();
}
?>

正如您所见,我重复 3 次插入,以获取每个表上最后插入的 id,以便在其他表中引用。

HTML 表单位于我之前关于相同问题的问题中,但具有 mysql_* 函数。

提前致谢。

PHP MySQL inserting 3 different form values to 4 different tables

最佳答案

您必须阅读 PDO 示例:

Complete guide and error debugging

检查您的 Debug模式是否已开启

error_reporting(E_ALL);

$stmt = $db->prepare("INSERT INTO table(field1,field2,field3,field4,field5) VALUES(:field1,:field2,:field3,:field4,:field5)");
$stmt->execute(array(':field1' => $field1, ':field2' => $field2, ':field3' => $field3, ':field4' => $field4, ':field5' => $field5));
$affected_rows = $stmt->rowCount();

一次只能为一个准备语句执行一个执行语句

关于php - PDO 将 3 个表单值插入到 4 个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29982712/

相关文章:

php - MySQL 更改表在已存在的字段之前或之后添加字段

mysql - SQL Group By 对其他表中的字段进行分组

php - 当选中复选框时,mysql 将数据库中的枚举从 no 更新为复选框值

forms - 输入类型=重置和 knockout

php - WP 菜单 - 在下拉列表中的 li 旁边插入图像

php - mysql 使用 IF NOT IN 关键字或替代方法选择所有其他数据

php - 在 PHPExcel 中获取不需要的字符,如 "_x000D_"或 "x000D"

php - 拉拉维尔 5.3 : Cannot add Additional user info for User registration

javascript - 未捕获的类型错误 : Cannot read property 'fname' of undefined at FillInfo()

php - 将jQuery文件上传与表单结合到mysql