根据用户选择插入多个表? PHP

时间:2016-01-17 20:13:11

标签: php html mysql sql

我正在做一个项目,在AddJob页面中,我需要根据用户选择rocord保存位置的含义在myslq中的表中添加记录。

这是我的代码,直到现在,它只将记录保存到Food Table中。我可以将其设为可选项。

<?php
session_start();
if( isset($_SESSION['username']) ){

     if(isset($_POST['add'])){

        if(isset($_POST['add'])) 
        {
          $errorMessage = "";

           if(($_POST['lists'])== 0)  // trying to get error if user don't choose.
              {
                $errorMessage .= "<li>You Forgot to Choose !</li>";

              }

              if(empty($_POST['JobName'])) 
              {
                $errorMessage .= "<li>You Forgot To Enter A Job Name !</li>";

              }
              if(empty($_POST['Description'])) 
              {
                $errorMessage .= "<li>You Forgot To Enter A Description !</li>";
              }

            if(empty($_POST['NoStudent'])) 
              {
                $errorMessage .= "<li>You Forgot To Enter A Student Number !</li>";
              }

            if(empty($_POST['dueDate'])) 
              {
                $errorMessage .= "<li>You Forgot To Enter A Due Date !</li>";
              }

              $lists = $_POST['lists'];
              $JN = $_POST['JobName'];
              $DES = $_POST['Description'];
              $NoS = $_POST['NoStudent'];
              $DuDate = $_POST['dueDate'];
              if(!empty($errorMessage)) 
              {
                echo("<p>There was an error with your form:</p>\n");
                echo("<ul>" . $errorMessage . "</ul>\n");
                die();
              } 


            }

            //////// IF all test passed.. then connect to db
             $con = mysqli_connect("localhost","root" ,"" ,"CIE") or die ("cannot connect : ".mysqli_error());

          $sql = "INSERT INTO Food (JobName,Description,NoStudent,DueDate) 
          VALUES 
          ('$JN','$DES','$NoS','$DuDate')";


           mysqli_query($con, $sql) or die(mysqli_error($con));

          echo "You Successfuly Added a new Reocord ...";
          mysqli_close($con);

     }

     else {  echo '
    <form action= "AddJob.php"  method = "post">
    <table width ="100%" cellpadding ="4" border="1" >

    <tr>
    <th>Select a Catagory</th>
    <th>Jobs Name</th>
    <th>Description</th>
    <th> No Students needed</th>
    <th>Due Date</th>
    </tr>';
        echo "<tr>
     <td>". 

    "<select name = lists >
      <option name= nothing value= 0 selected >Choose a Catagory</option>
      <option name= nothing value= 1>    Advertising     </option>
      <option name= nothing value= 2>    Fiscal          </option>
      <option name= nothing value= 3>    Food            </option>
      <option name= nothing value= 4>    Shopping        </option>
      <option name= nothing value= 5>    Rentals         </option>
      <option name= nothing value= 6>   Setting up       </option>
      <option name= nothing value= 7>    Performances    </option>
      <option name= nothing value= 8>  Registration/Ushering  </option>
      <option name= nothing value= 9>   Master of Ceremonies  </option>
      <option name= nothing value= 10>    Cleaning up   </option>
      <option name= nothing value= 11>    Others        </option>

     </select>"
      ." </td>
     <td> "."<input type=text name=JobName maxlength=50  placeholder='Enter Job Name '>" ." </td>
     <td> "."<input type=text name=Description maxlength=50 placeholder='Enter Description '>" ." </td>
     <td> ". "<input type=text name=NoStudent maxlength=50   onkeypress=return isNumber(event) placeholder='ONLY NUMBERS'/>" . "</td>
     <td>". "<input type=text name=dueDate maxlength=50 placeholder='YYYY-MM-DD'>" ." </td>
     </tr>";
     echo '
     </table>
     <br/>
     <div align="center">
     <input type="submit" name="add" value="Add" />
     <input type="reset" value="Clear" />
     </div>
     </form>
     ';
    }
}else{echo "must logout to see this page..!!";}
?>
<html>
<head><title> Add.. </title></head>
<br>
<body>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

如果您的11个表具有相同的结构(字段名称),您只需替换&#34; food&#34;表名由变量表示,由&#34;开关&#34;初始化。 on&#34; $ lists&#34;可变内容。 一个简单的版本可能是这样的:

$table="";       
switch($lists)
{
    case 1:
        $table ="Advertising";
    break;
    case 2:
        $table ="fiscal";
    break;
.........other cases..........
    case 0;
    default;
        echo 'Unsupported category';
    break;
}
if ($table != ""){
    $sql = "INSERT INTO ". $table . "(JobName,Description,NoStudent,DueDate) 
                          VALUES 
                          ('$JN','$DES','$NoS','$DuDate')";
}

答案 1 :(得分:0)

这将变得罗嗦,但我保证最后会有代码。

假设您实际上有11个表,@ dev35000在构建SQL查询时使用PHP变量的解决方案适合您。

但是,由于所有表似乎都包含相同类型的数据,因此您可以通过创建具有CategoryId的表来使自己更轻松。你可以把那个表称为Jobs(或者对你有意义的任何东西。我说就是你正在存储的那些工作)然后你会创建一个表来存储所有不同的类别。

您最终得到的表格是:

`Jobs` Table
-----------------------
JobId       | JobName       | Description | NoStudent   | DueDate     | CategoryId
INT, PK, AI | VARCHAR(50)   | VARCHAR(50) | VARCHAR(50) | VARCHAR(50) | INT
-----------------------
Filled with data inserted through the form

`Category` Table
-----------------------
CategoryId  | Category
INT, PK, AI | VARCHAR(50)
-----------------------
1           | Advertising
2           | Fiscal
3           | Food
4           | Shopping
5           | Rentals
6           | Setting up
7           | Performances
8           | Registration/Ushering
9           | Master of Ceremonies
10          | Cleaning up
11          | Others

JobId和CategoryId将为auto_incrmenting columns 您已经发送了CategoryId,因此您的代码实际上不会在那里发生变化。要显示Category表中Job表记录所属的类别,可以使用SQL中的JOIN来显示作业所属的类别,并使用以下查询:

SELECT j.JobName, j.Description, j.NoStudent, j.DueDate, c.Category
FROM Jobs j
JOIN Category c ON j.CategoryId = c.CategoryId

在我们开始使用代码之前:

  1. 您对isset($_POST['add'])进行了2次检查。删除内部的 因为它是多余的
  2. 我使用完整的变量名而不是缩写。我认为这将使您的代码更容易阅读(为您自己和 其他)将其改回缩写不会破坏任何东西。
  3. 我切换了你的代码,以利用预防语句来防止SQL注入
  4. 给某种缩进方案一个更改(我意识到从你的IDE到StackOverflow的代码会弄乱格式化。如果这就是这里发生的事情,请道歉)
  5. 我将您的表单切换为始终使用单引号
  6. <html>
        <head><title> Add.. </title></head>
    <body>
    <?php
    session_start();
    if(isset($_SESSION['username'])) {
    
        if(isset($_POST['add'])) {
    
            $errorMessage = "";
    
            if(($_POST['lists'])== 0) { // trying to get error if user don't choose.
                $errorMessage .= "<li>You Forgot to Choose !</li>";
            }
            if(empty($_POST['JobName'])) {
                $errorMessage .= "<li>You Forgot To Enter A Job Name !</li>";
            }
            if(empty($_POST['Description'])) {
                $errorMessage .= "<li>You Forgot To Enter A Description !</li>";
            }
            if(empty($_POST['NoStudent'])) {
                $errorMessage .= "<li>You Forgot To Enter A Student Number !</li>";
            }
            if(empty($_POST['dueDate'])) {
                $errorMessage .= "<li>You Forgot To Enter A Due Date !</li>";
            }
            if(!empty($errorMessage)) {
                echo("<p>There was an error with your form:</p>\n");
                echo("<ul>" . $errorMessage . "</ul>\n");
                die();
            }
    
            $JobName = $_POST['JobName'];
            $Description = $_POST['Description'];
            $NoStudent = $_POST['NoStudent'];
            $DueDate = $_POST['dueDate'];
            $lists = $_POST['lists'];
    
            //////// IF all test passed.. then connect to db
            $con = mysqli_connect("localhost","root" ,"" ,"CIE") or die ("cannot connect : ".mysqli_error());
    
            $sql = "INSERT INTO Jobs (JobName,Description,NoStudent,DueDate,Category) 
            VALUES 
            (?, ?, ?, ?, ?, ?)";
            // reference: http://php.net/manual/en/mysqli.prepare.php
            if ($stmt = mysqli_prepare($con, $sql)) {
                // reference: http://php.net/manual/en/mysqli-stmt.bind-param.php
                mysqli_stmt_bind_param($stmt, 'ssisi', $JobName, $Description, $NoStudent, $DueDate, $lists);
    
    
                mysqli_execute($con, $sql) or die(mysqli_error($con));
    
                echo "You Successfuly Added a new Reocord ...";
            }
    
            mysqli_close($con);
        }
        else {
            echo "
    <form action= 'AddJob.php'  method = 'post'>
        <table width ='100'% cellpadding ='4' border='1' >
            <tr>
                <th>Select a Category</th>
                <th>Jobs Name</th>
                <th>Description</th>
                <th>No Students needed</th>
                <th>Due Date</th>
            </tr>
            <tr>
                <td>
                    <select name = lists >
                        <option name= nothing value= 0 selected >Choose a Category</option>
                        <option name= nothing value= 1>    Advertising     </option>
                        <option name= nothing value= 2>    Fiscal          </option>
                        <option name= nothing value= 3>    Food            </option>
                        <option name= nothing value= 4>    Shopping        </option>
                        <option name= nothing value= 5>    Rentals         </option>
                        <option name= nothing value= 6>   Setting up       </option>
                        <option name= nothing value= 7>    Performances    </option>
                        <option name= nothing value= 8>  Registration/Ushering  </option>
                        <option name= nothing value= 9>   Master of Ceremonies  </option>
                        <option name= nothing value= 10>    Cleaning up   </option>
                        <option name= nothing value= 11>    Others        </option>
                    </select>
                </td>
                <td> <input type=text name=JobName maxlength=50  placeholder='Enter Job Name '></td>
                <td> <input type=text name=Description maxlength=50 placeholder='Enter Description '></td>
                <td> <input type=text name=NoStudent maxlength=50   onkeypress=return isNumber(event) placeholder='ONLY NUMBERS'/></td>
                <td> <input type=text name=dueDate maxlength=50 placeholder='YYYY-MM-DD'></td>
            </tr>
        </table>
        <br/>
        <div align='center'>
            <input type='submit' name='add' value='Add' />
            <input type='reset' value='Clear' />
        </div>
    </form>";
        }
    }
    else
    {
        echo "must login to see this page..!!";
    }
    ?>
    </body>
    </html>
    

    如果我能搞清楚的话,请告诉我。