PHP / MySQL:从外键表中插入表1中的值

时间:2018-04-26 01:42:24

标签: php html mysql

我正在为一个类的桌面RPG怪物数据库工作,我需要使用以下参数将值插入我的怪物表:Monster Table

CREATE TABLE Monsters (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100) NOT NULL,
HP int unsigned NOT NULL,
MP int unsigned NOT NULL,
AC int unsigned NOT NULL,
MonsterType_ID int NOT NULL,
PRIMARY KEY(ID),
FOREIGN KEY(MonsterType_ID) REFERENCES MonsterType(ID) ON DELETE CASCADE
) ENGINE=InnoDB;

我还有MonsterType Table

CREATE TABLE MonsterType (  
ID int NOT NULL AUTO_INCREMENT,  
Name varchar(100) NOT NULL,  
PRIMARY KEY (ID)  
) ENGINE=InnoDB;

我已设置PHP代码:PHP Monster Query

if (isset($_POST["submit"])) {
    if( (isset($_POST["Name"]) && $_POST["Name"] !== "") && 
    (isset($_POST["HP"]) && $_POST["HP"] !== "") &&
    (isset($_POST["MP"]) && $_POST["MP"] !== "") &&
    (isset($_POST["AC"]) && $_POST["AC"] !== "") &&
    (isset($_POST["MonsterType_ID"]) && $_POST["MonsterType_ID"] !== "") ) {



            $query = "INSERT INTO Monsters ";
            $query .= "(Name, HP, MP, AC, MonsterType_ID) ";
            $query .= "VALUES (";
            $query .= "'".$_POST["Name"]."',";
            $query .= "'".$_POST["HP"]."',";
            $query .= "'".$_POST["MP"]."',";
            $query .= "'".$_POST["AC"]."',";
            $query .= "'".$_POST["MonsterType_ID"]."');";

            $result = $mysqli->query($query);

当我转到Add Monsters时,Monster Type字段只接受与MonsterType.ID索引对应的整数值。相反,我希望能够在文本字段中输入MonsterType Names

INSERT INTO MonsterType (Name)
VALUES
    ('Abberation'),
    ('Beast'),
    ('Celestial'),
    ('Construct'),
    ('Dragon'),
    ('Elemental'),
    ('Fey'),
    ('Fiend'),
    ('Giant'),
    ('Humanoid'),
    ('Monstrosity'),
    ('Ooze'),
    ('Plant'),
    ('Undead');

并将相应的Type Name的ID插入数据库。

我已经可以使用此查询display与Monster关联的MonsterType:Monster Display

$query = "SELECT Monsters.ID AS `mID`, 
          Monsters.Name AS `MName`, Monsters.MonsterType_ID, 
          MonsterType.Name FROM Monsters ";
$query .= "inner join MonsterType ON Monsters.MonsterType_ID = MonsterType.ID 
          ORDER BY MonsterType.Name ASC";
$result = $mysqli->query($query);

if ($result && $result->num_rows > 0) {
    echo "<div class='row'>";
    echo "<center>";
    echo "<h2>The Monster Database</h2>";
    echo "<table>";
    echo "<tr><th>Name</th><th>Type</th>
    <th></th><th></th></tr>";
    while ($row = $result->fetch_assoc())  {
        echo "<tr>";    
        //Output FirstName and LastName
        echo "<td>" .$row["MName"]."</td>";
        echo "<td>" .$row["Name"]."</td>";

我只是不确定如何更改我的插入查询,以便它接受文本字段中的MonsterType.Name并使用与我的插入怪物表查询中的MonsterType.Name关联的MonsterType.ID。

当然,理想情况下,我只想让我的Monster Type字段成为所有MonsterType.Names的下拉列表,但我在使用HTML code embedded in a PHP block进行下拉字段时遇到问题。

 echo '
    <div class="row">
    <label for="left-label" class="left inline">

    <h2>Add a monster</h2>
    <form method="POST" action="addMonsters.php">

    <p> Monster Name: <input type="text" name="Name">
    <p> Hit Points: <input type="text" name="HP">
    <p> Mana Points: <input type="text" name="MP">
    <p> Armor Class: <input type="text" name="AC">
    <p> Monster Type: <input type="text" name="MonsterType_ID">
    /////// This didn't work
    <p>Monster Type: <select name="Name">
    <option></option>
    <?php
         $query = "SELECT DISTINCT Name FROM MonsterType";
         $result = $mysqli->query($query);
         if($result && $result->num_rows>=1){
            while($row = $result->fetch_assoc()){
               echo "<option value = '".$row['Name']."'>".$row['Name']."/option>";
        }
    }
         else {echo "<h2>No query results</h2>";}
     ?>
     </select>
      ///////////   
    <input type="submit" name="submit" class="button tiny round" value="Add monster" />
    </form>
    ';

如果有人能解决这个问题,那就更好了。

任何指导将不胜感激!谢谢!

编辑:

我已经使用这段代码成功填充了我的下拉列表:

echo '<p>Monster Type: <select name="MonsterType_ID">';
        echo '<option></option>';

                $query = "SELECT DISTINCT ID, Name FROM MonsterType";
                $result = $mysqli ->query($query);
                if($result && $result->num_rows>=1){
                    while($row2 = $result->fetch_assoc()){
                        if($row2['mID'] == $MonsterID){
                            echo "<option selected value = '".$row2['ID']."'>".$row2['Name']."</option>";
                        }
                        else{
                            echo "<option value = '".$row2['ID']."'>".$row2['Name']."</option>";
                        }
                    }
                }

                else {
                    echo "<h2>No query results</h2>";
                }
        echo '</select></p>';

但是,这不能正确地POST到原始查询,并且我收到错误消息,我没有填写所有信息。 (我错过了一个引号(select name =“MonsterType_ID”))但是,我仍然得到“错误!无法添加”。$ _ POST [“Name”]。“!”;所以这意味着Query的结果是错误的。不确定会发生什么,除了MonsterType.ID没有与Monsters.MonsterType_ID匹配。

if (isset($_POST["submit"])) {
    if( (isset($_POST["Name"]) && $_POST["Name"] !== "") && 
    (isset($_POST["HP"]) && $_POST["HP"] !== "") &&
    (isset($_POST["MP"]) && $_POST["MP"] !== "") &&
    (isset($_POST["AC"]) && $_POST["AC"] !== "") &&
    (isset($_POST["MonsterType_ID"]) && $_POST["MonsterType_ID"] !== "")     ) {



            //STEP 2.
                //Create query to insert information that has been posted
            $query = "INSERT INTO Monsters ";
            $query .= "(Name, HP, MP, AC, MonsterType_ID) ";
            $query .= "VALUES (";
            $query .= "'".$_POST["Name"]."',";
            $query .= "'".$_POST["HP"]."',";
            $query .= "'".$_POST["MP"]."',";
            $query .= "'".$_POST["AC"]."',";
            $query .= "'".$_POST["MonsterType_ID"]."'));";
            //$query .= "(SELECT ID FROM MonsterType WHERE Name='".$_POST["MonsterType_ID"]."'));";


            $result = $mysqli->query($query);

            // Execute query




        if($result) {

        $_SESSION["message"] = $_POST["Name"]." has been added!";
            header("Location: readMonsters.php");
            exit;

        }
        else {

        $_SESSION["message"] = "Error! Could not add ".$_POST["Name"]."!";
            header("Location: addMonsters.php");
            exit;
        }
    }
    else {
        $_SESSION["message"] = "Unable to add monster. Fill in all information!";
        header("Location: addMonsters.php");
        exit;
    }

编辑2:一切正常!下拉列表是正确的,我只需要更改查询以接受正确的参数。

$query = "INSERT INTO Monsters ";
            $query .= "(Name, HP, MP, AC, MonsterType_ID) ";
            $query .= "VALUES (";
            $query .= "'".$_POST["Name"]."',";
            $query .= "'".$_POST["HP"]."',";
            $query .= "'".$_POST["MP"]."',";
            $query .= "'".$_POST["AC"]."',";
            //$query .= "'".$_POST["MonsterType_ID"]."'));";
            $query .= "(SELECT ID FROM MonsterType WHERE ID='".$_POST["MonsterType_ID"]."'));";


            $result = $mysqli->query($query);

即,我将(SELECT ID FROM MonsterType WHERE Name = ...)更改为(SELECT ID FROM MonsterType WHERE ID = ...)。我的下拉列表现在成功运行。谢谢尼克的帮助!

3 个答案:

答案 0 :(得分:1)

简短回答,根据您当前的代码结构,更改此行:

$query .= "'".$_POST["MonsterType_ID"]."');";

$query .= "(SELECT ID FROM MonsterType WHERE Name='".$_POST["MonsterType_ID"]."'));";

这将执行子查询选择以从MonsterType获取所提交名称的相应ID。

长答案

此方法的问题在于,如果用户在MonsterType_ID文本框中输入的内容不是有效的MonsterType,例如他们输错了#34; Aberration&#34; for&#34; Abberation&#34;此查询将失败。您尝试生成下拉列表是正确的方法。你会想要这样的东西:

<p>Monster Type: <select name="MonsterType_ID">
<?php
     $query = "SELECT ID, Name FROM MonsterType";
     $result = $mysqli->query($query);
     if ($result) { 
        while ($row = $result->fetch_assoc()) {
           echo "<option value = \"" . $row['ID'] . "\">" . $row['Name'] . "</option>";
        }
     }
 ?>
 </select>

这将为您提供一个选项,其中选项值(在$_POST中传递给PHP的内容)是您需要插入Monsters数据库的ID。这样您就不需要进行简短回答中所述的任何预处理(基本上您的现有代码将按原样运行)。

答案 1 :(得分:0)

执行插入时可以使用select。

INSERT INTO monsters (your, variable, fields, here, monsterTypeID) 
Select 'varname', 'varname', 'varname', 'varname', monsterTypeID FROM
MonsterTypeNames WHERE name='namevar';

答案 2 :(得分:0)

您需要查询monstertype表以根据monstertype名称获取id,并使用检索到的monstertype id构成insert查询的一部分。

因此,解决方案是将其拆分为两个查询或使用insert select(insert with subquery)。如果将其拆分为两个查询,则必须选择,然后插入。如果要在一个查询中执行此操作,可以使用insert select