PHP/FORM 问题

发布于 2024-11-14 12:20:54 字数 9721 浏览 1 评论 0原文

我是编程新手,所以请耐心等待...我正在使用 MySQL/PHP 创建一个应用程序,其中部分内容允许用户从两个下拉菜单中选择位置和房间。一共有三个表,room、location 和 room_location。我创建了允许用户将房间添加到房间表的表单和允许他们将位置添加到位置表的表单 - 这些都工作正常,因为输入只是一个文本字段,用户可以提交他们喜欢的任何文本。我的问题是第三个表单/表(dropdown_form.php) - 该表有三个字段,id |房间名称 |位置_名称。

我试图通过 room_location 表实现的目标是: 用户将获得一个网页,其中有一个用于选择 location_name(从位置表派生)的下拉菜单和另一个用于选择 room_name(从房间表派生)的下拉菜单。从两个下拉列表中进行选择后,用户将提交房间和位置的组合,并且新条目将添加到数据库中的 room_location 表中。

room_location 表 ID 示例

|地点名称 |房间名称
1 |医院1 |房间

1 2 |医院1 |房间

2 3 |医院1 |房间

3 4 |医院2 |房间

1 5 |医院2 |房间2 到目前为止,

我已经获得了显示两个下拉菜单的表单,但是当我选择并提交时,我收到一条错误消息“错误:键‘PRIMARY’的重复条目’”我包含了一些用于测试目的的回显语句看看发生了什么,我现在得到:

输入的位置和房间名称是

数组([select_location] => [select_room] =>)

错误:键“PRIMARY”的重复条目“” (重复条目似乎为 NULL?所以不要认为任何内容实际上被传递到 process.php)

看起来应该将数据传递到 process.php 的选择有问题(我认为)正在处理 $_POST 语句。我已经包含了我的代码的副本,对此的任何帮助将不胜感激。

dropdown_form.php

    <html>
    <head>
    <title>Testing Dropdown form</title>
    </head>
    <body>

<?php
        //make connection to the database
        mysql_connect ("localhost", "root", "password") or die ('Database connection ERROR: ' . mysql_error());
        mysql_select_db ("my_database");
?>

<fieldset style="width:30%" align="center"><legend><b>Add New Location/Room Combination</b></legend>
<table align="center" cellspacing="0" cellpadding="10" border="0">
<tr>
    <td align="center" valign="middle"> 
        <b> Location Name: </b> 
    </td>
    <td align="center" valign="middle"> 
        <b> Room Name: </b> 
    </td>
</tr>
<tr>
    <td align="center" valign="middle">
        <!-- create form to submit data process.php -->
        <form name="room_location_form" action="process.php" method="post">
        <select name="select_location">         

        <?php
        //create and run a query that selects all the locations to create an options list
        $loc_query = "SELECT location_name FROM location ORDER BY location_name";
        $loc_result = mysql_query($loc_query);

        while ($row = mysql_fetch_array($loc_result, MYSQL_ASSOC)) 
        {
        echo "<option value=$row[id]>$row[location_name]</option>";
        }
        ?>
        </select>
    </td>

    <td>        
        <?php
        //create and run a query that selects all the rooms to create an options list
        $room_query = "SELECT room_name FROM room_name ORDER BY room_name";
        $room_result = mysql_query($room_query);
        ?>

        <select name="select_room">

        <?php
            while ($row = mysql_fetch_array($room_result, MYSQL_ASSOC)) 
            {
            echo "<option value=$row[id]>$row[room_name]</option>";
            }
        ?>  
        </select>

    </td>

    <!--Add a submit button -->
    <td align="center" valign="middle">
        <input type="submit" value="Add Location/Room">
    </td>

</tr>

</form>
</table>
</fieldset>

<br>
<br>
<hr width=50%>
<br>
 <table border=1 align=center cellspacing=1>
    <tr>
        <th>Location Name</th>
        <th>Room Name</th>
    </tr>

<?php

//build query to display a list of all current locations and rooms
 $query = mysql_query("select * from room_location ORDER BY location_name, room_name"); 

  //return the array and loop through each row
  while ($row = mysql_fetch_array($query)) {
  $location_name = $row['location_name'];
  $room_name = $row['room_name'];

 ?>

    <tr>
        <th><?php echo $location_name;?></th>
        <th><?php echo $room_name;?></th>
    </tr>

<?php }  //this ends the loop   
?>

process.php

<?php
//make connection
$conn = mysql_connect ("localhost", "root", "password"); 
if (!$conn) 
    {
    die ('Database connection ERROR: ' . mysql_error());
    }
$db = mysql_select_db ("my_database");

//Add new Location and Room Name combination - sent from form
$sql="INSERT INTO room_location (location_name, room_name) VALUES (('$_POST[select_location]'), ('$_POST[select_room]'))"; 
    echo "Location and Room name entered was ", $_POST['select_location'], " & ", $_POST['select_room']; 
?>
<br> <!-- Line break just to see what is being output when testing -->
<?php
print_r($_POST);  //added for testing purposes to see what is being POSTed
?>
<br> <!-- Line break just to see what is being output when testing -->
<?php
if (!mysql_query($sql,$conn))
    {
    die ('Error: ' . mysql_error());
    }
    echo "Location and Room name entered was ", $_POST['select_location'], " & ", $_POST['select_room']; 

mysql_close($conn)
 ?>

***按建议进行更新** 到目前为止,感谢大家的建议,我已经取得了一些进展,谢谢大家。使用下面的代码,我现在得到 select_location 输出为 location_id 和 select_room 输出为 room_name_id 而不是 location_name 和 room_name - 大家知道我做错了什么吗?

dropdown_form.php

    <?php
    //make connection to the database
            mysql_connect ("localhost", "root", "password") or die ('Database connection ERROR: ' . mysql_error());
            mysql_select_db ("my_database");
    ?>

    <fieldset style="width:30%" align="center"><legend><b>Add New Location/Room Combination</b></legend>
    <table align="center" cellspacing="0" cellpadding="10" border="0">
    <tr>
        <td align="center" valign="middle"> 
            <b> Location Name: </b> 
        </td>
        <td align="center" valign="middle"> 
            <b> Room Name: </b> 
        </td>
    </tr>
    <tr>
        <td align="center" valign="middle">
            <!-- create form to submit data process.php -->
            <form name="room_location_form" action="process.php" method="post">
            <select name="select_location">         

            <?php
            //create and run a query that selects all the locations to create an options list
            $loc_query = "SELECT location_id,location_name FROM location ORDER BY location_name";
            $loc_result = mysql_query($loc_query);

            while ($row = mysql_fetch_array($loc_result, MYSQL_ASSOC)) 
            {
            echo "<option value=\"".$row['location_id']."\">".$row['location_name']."</option>\n";
            }
            ?>
            </select>
        </td>

        <td>        
            <?php
            //create and run a query that selects all the rooms to create an options list
            $room_query = "SELECT room_name_id,room_name FROM room_name ORDER BY room_name";
            $room_result = mysql_query($room_query);
            ?>

            <select name="select_room">

            <?php
                while ($row = mysql_fetch_array($room_result, MYSQL_ASSOC)) 
                {
                echo "<option value=\"".$row['room_name_id']."\">".$row['room_name']."</option>\n";
                        }
            ?>  
            </select>

        </td> 

        <!--Add a submit button -->
        <td align="center" valign="middle">
            <input type="submit" value="Add Location/Room">
        </td>

    </tr>

    </form>
    </table>
    </fieldset>

    <br>
    <br>
    <hr width=50%>
    <br>
     <table border=1 align=center cellspacing=1>
        <tr>
            <th>Location Name</th>
            <th>Room Name</th>
        </tr>

    <?php

    //build query to display a list of all current locations and rooms
     $query = mysql_query("select * from room_location ORDER BY location_name, room_name"); 

      //return the array and loop through each row
      while ($row = mysql_fetch_array($query)) {
      $location_name = $row['location_name'];
      $room_name = $row['room_name'];

     ?>

        <tr>
            <th><?php echo $location_name;?></th>
            <th><?php echo $room_name;?></th>
        </tr>

    <?php }  //this ends the loop   
    ?>

process.php

    <?php
    //make connection
    $conn = mysql_connect ("localhost", "root", "password"); 
    if (!$conn) 
        {
        die ('Database connection ERROR: ' . mysql_error());
        }
    $db = mysql_select_db ("my_database");

        //Add new Location and Room Name combination - sent from form
        $sql="INSERT INTO room_location (location_name, room_name) VALUES (('".$_POST['select_location']."'), ('".$_POST['select_room']."'))"; 

    ?>
    <br> <!-- Line break just to see what is being output when testing -->
    <?php
    print_r($_POST);  //added for testing purposes to see what is being POSTed
    ?>
    <br> <!-- Line break just to see what is being output when testing -->
    <?php
    if (!mysql_query($sql,$conn))
        {
        die ('Error: ' . mysql_error());
        }
    echo "Location and Room name entered was ", [$_POST['select_location']], " & ", $_POST['select_room']; 

    mysql_close($conn)
     ?>

I'm new to programming so please bear with me...I'm using MySQL/PHP to create an application where part of it allows users to select a location and room from two drop down menus. There are three tables, room, location and room_location. I have created forms that allow user to add a room to room table and a form to allow them to add a location to location table - these both work fine as the input is just a text field and the user can submit any text they like. My problem is with the third form/table (dropdown_form.php)- this table has three fields, id | room_name | location_name.

What I am trying to achieve with the room_location table is this:
The user will get a webpage that has a dropdown menu for selecting a location_name (which is derived from the location table) and another dropdown menu for selecting the room_name (which is derived from the room table). After selecting from both dropdowns the user will submit this combination of room and location and a new entry will be added to the room_location table in the database.

example of room_location table

ID | location_name | room_name
1 | Hospital1 | room1

2 | Hospital1 | room2

3 | Hospital1 | room3

4 | Hospital2 | room1

5 | Hospital2 | room2
etc

So far I've got the form for this to display both of the dropdown menus but when I select and submit I get an error saying "Error: Duplicate entry '' for key 'PRIMARY' " I included some echo statements for testing purposes to see what is happening, I'm now getting:

Location and Room name entered was

Array ( [select_location] => [select_room] => )

Error: Duplicate entry '' for key 'PRIMARY'
(duplicate entry appears to be NULL? so don't think anything is actually being passed to process.php)

It appears that there is something wrong (I think) with the selects that are supposed to be passing the data to process.php which is handling the $_POST statements. I've included a copy of my code, any help at all with this would be greatly appreciated.

dropdown_form.php

    <html>
    <head>
    <title>Testing Dropdown form</title>
    </head>
    <body>

<?php
        //make connection to the database
        mysql_connect ("localhost", "root", "password") or die ('Database connection ERROR: ' . mysql_error());
        mysql_select_db ("my_database");
?>

<fieldset style="width:30%" align="center"><legend><b>Add New Location/Room Combination</b></legend>
<table align="center" cellspacing="0" cellpadding="10" border="0">
<tr>
    <td align="center" valign="middle"> 
        <b> Location Name: </b> 
    </td>
    <td align="center" valign="middle"> 
        <b> Room Name: </b> 
    </td>
</tr>
<tr>
    <td align="center" valign="middle">
        <!-- create form to submit data process.php -->
        <form name="room_location_form" action="process.php" method="post">
        <select name="select_location">         

        <?php
        //create and run a query that selects all the locations to create an options list
        $loc_query = "SELECT location_name FROM location ORDER BY location_name";
        $loc_result = mysql_query($loc_query);

        while ($row = mysql_fetch_array($loc_result, MYSQL_ASSOC)) 
        {
        echo "<option value=$row[id]>$row[location_name]</option>";
        }
        ?>
        </select>
    </td>

    <td>        
        <?php
        //create and run a query that selects all the rooms to create an options list
        $room_query = "SELECT room_name FROM room_name ORDER BY room_name";
        $room_result = mysql_query($room_query);
        ?>

        <select name="select_room">

        <?php
            while ($row = mysql_fetch_array($room_result, MYSQL_ASSOC)) 
            {
            echo "<option value=$row[id]>$row[room_name]</option>";
            }
        ?>  
        </select>

    </td>

    <!--Add a submit button -->
    <td align="center" valign="middle">
        <input type="submit" value="Add Location/Room">
    </td>

</tr>

</form>
</table>
</fieldset>

<br>
<br>
<hr width=50%>
<br>
 <table border=1 align=center cellspacing=1>
    <tr>
        <th>Location Name</th>
        <th>Room Name</th>
    </tr>

<?php

//build query to display a list of all current locations and rooms
 $query = mysql_query("select * from room_location ORDER BY location_name, room_name"); 

  //return the array and loop through each row
  while ($row = mysql_fetch_array($query)) {
  $location_name = $row['location_name'];
  $room_name = $row['room_name'];

 ?>

    <tr>
        <th><?php echo $location_name;?></th>
        <th><?php echo $room_name;?></th>
    </tr>

<?php }  //this ends the loop   
?>

process.php

<?php
//make connection
$conn = mysql_connect ("localhost", "root", "password"); 
if (!$conn) 
    {
    die ('Database connection ERROR: ' . mysql_error());
    }
$db = mysql_select_db ("my_database");

//Add new Location and Room Name combination - sent from form
$sql="INSERT INTO room_location (location_name, room_name) VALUES (('$_POST[select_location]'), ('$_POST[select_room]'))"; 
    echo "Location and Room name entered was ", $_POST['select_location'], " & ", $_POST['select_room']; 
?>
<br> <!-- Line break just to see what is being output when testing -->
<?php
print_r($_POST);  //added for testing purposes to see what is being POSTed
?>
<br> <!-- Line break just to see what is being output when testing -->
<?php
if (!mysql_query($sql,$conn))
    {
    die ('Error: ' . mysql_error());
    }
    echo "Location and Room name entered was ", $_POST['select_location'], " & ", $_POST['select_room']; 

mysql_close($conn)
 ?>

***UPDATES MADE AS SUGGESTED**
Thanks for the suggestions so far, I;ve made some progess thanks to you all. Using code below I now get select_location outputting as location_id and select_room outputting as room_name_id instead of the location_name and room_name - any ideas what I'm doing wrong guys?

dropdown_form.php

    <?php
    //make connection to the database
            mysql_connect ("localhost", "root", "password") or die ('Database connection ERROR: ' . mysql_error());
            mysql_select_db ("my_database");
    ?>

    <fieldset style="width:30%" align="center"><legend><b>Add New Location/Room Combination</b></legend>
    <table align="center" cellspacing="0" cellpadding="10" border="0">
    <tr>
        <td align="center" valign="middle"> 
            <b> Location Name: </b> 
        </td>
        <td align="center" valign="middle"> 
            <b> Room Name: </b> 
        </td>
    </tr>
    <tr>
        <td align="center" valign="middle">
            <!-- create form to submit data process.php -->
            <form name="room_location_form" action="process.php" method="post">
            <select name="select_location">         

            <?php
            //create and run a query that selects all the locations to create an options list
            $loc_query = "SELECT location_id,location_name FROM location ORDER BY location_name";
            $loc_result = mysql_query($loc_query);

            while ($row = mysql_fetch_array($loc_result, MYSQL_ASSOC)) 
            {
            echo "<option value=\"".$row['location_id']."\">".$row['location_name']."</option>\n";
            }
            ?>
            </select>
        </td>

        <td>        
            <?php
            //create and run a query that selects all the rooms to create an options list
            $room_query = "SELECT room_name_id,room_name FROM room_name ORDER BY room_name";
            $room_result = mysql_query($room_query);
            ?>

            <select name="select_room">

            <?php
                while ($row = mysql_fetch_array($room_result, MYSQL_ASSOC)) 
                {
                echo "<option value=\"".$row['room_name_id']."\">".$row['room_name']."</option>\n";
                        }
            ?>  
            </select>

        </td> 

        <!--Add a submit button -->
        <td align="center" valign="middle">
            <input type="submit" value="Add Location/Room">
        </td>

    </tr>

    </form>
    </table>
    </fieldset>

    <br>
    <br>
    <hr width=50%>
    <br>
     <table border=1 align=center cellspacing=1>
        <tr>
            <th>Location Name</th>
            <th>Room Name</th>
        </tr>

    <?php

    //build query to display a list of all current locations and rooms
     $query = mysql_query("select * from room_location ORDER BY location_name, room_name"); 

      //return the array and loop through each row
      while ($row = mysql_fetch_array($query)) {
      $location_name = $row['location_name'];
      $room_name = $row['room_name'];

     ?>

        <tr>
            <th><?php echo $location_name;?></th>
            <th><?php echo $room_name;?></th>
        </tr>

    <?php }  //this ends the loop   
    ?>

process.php

    <?php
    //make connection
    $conn = mysql_connect ("localhost", "root", "password"); 
    if (!$conn) 
        {
        die ('Database connection ERROR: ' . mysql_error());
        }
    $db = mysql_select_db ("my_database");

        //Add new Location and Room Name combination - sent from form
        $sql="INSERT INTO room_location (location_name, room_name) VALUES (('".$_POST['select_location']."'), ('".$_POST['select_room']."'))"; 

    ?>
    <br> <!-- Line break just to see what is being output when testing -->
    <?php
    print_r($_POST);  //added for testing purposes to see what is being POSTed
    ?>
    <br> <!-- Line break just to see what is being output when testing -->
    <?php
    if (!mysql_query($sql,$conn))
        {
        die ('Error: ' . mysql_error());
        }
    echo "Location and Room name entered was ", [$_POST['select_location']], " & ", $_POST['select_room']; 

    mysql_close($conn)
     ?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

玉环 2024-11-21 12:20:54

除了其他人所说的之外,

在您的 SELECTS 上的 dropdown_form.php 中,要获取下拉列表,您不会检索表单中 id 值的 id。

SELECT location_name FROM location ORDER BY location
make it 
SELECT id,location_name FROM location ORDER BY location desc

然后你可以像这样访问它:

echo "<option value=\"".$row['id']."\">".$row['location_name']."</option>\n";

注意我也正确地格式化了它

对第二个选择执行相同的操作..

将新行插入数据库时​​,请确保 id 为主键并且自动递增。
查询:

$sql='INSERT INTO room_location (`id`,`location_name`, `room_name`) VALUES ("","'.mysql_real_escape_string($_POST['select_location']).'", "'.mysql_real_escape_string($_POST['select_room']).'")';

besides what others have said,

in dropdown_form.php on your SELECTS, to get the dropdowns your not retrieving an id for the id value in the form.

SELECT location_name FROM location ORDER BY location
make it 
SELECT id,location_name FROM location ORDER BY location desc

then you can access it like:

echo "<option value=\"".$row['id']."\">".$row['location_name']."</option>\n";

notice i also formatted it correctly

do the same with the second select...

On inserting the new row into the database make sure that the id is the primary key and auto increments.
the query:

$sql='INSERT INTO room_location (`id`,`location_name`, `room_name`) VALUES ("","'.mysql_real_escape_string($_POST['select_location']).'", "'.mysql_real_escape_string($_POST['select_room']).'")';
生寂 2024-11-21 12:20:54

只是记下,因为我假设您在这篇文章中为了快速目的而删除了清理,但请确保您正在清理您的 $_POST 变量以防止 SQL 注入。

话虽如此,请尝试用以下内容替换您的查询:

$sql="INSERT INTO room_location (location_name, room_name) VALUES (('".$_POST['select_location']."'), ('".$_POST['select_room']."'))";

编辑:

似乎我对此有点晚了,因为 Blender 已经注意到了。

Just making note because I'm assuming you removed the sanitizing for quick purposes on this post, but make sure you are sanitizing your $_POST variables against SQL Injection.

With that said, try replacing your query with this:

$sql="INSERT INTO room_location (location_name, room_name) VALUES (('".$_POST['select_location']."'), ('".$_POST['select_room']."'))";

EDIT:

Seems I am a bit late on this, as Blender has already noted it.

剑心龙吟 2024-11-21 12:20:54

终于我自己破解了这个...不是最优雅的解决方案,但它有效:D 感谢您的指点。

*更新到 process.php ***

<?php
    //This section retrieves the room name selected on dropdown_form.php page
    $room_id = $_POST['select_room']; //temp variable to hold room_name_id
    $query = mysql_query("SELECT room_name FROM room_name WHERE room_name_id = $room_id");
      while ($row = mysql_fetch_array($query)) 
      {
       $room_name = $row['room_name'];
      }

    //This section retrieves the location name selected on add_room_location_form.php page
    $location_id = $_POST['select_location']; //temp variable to hold location_name_id
    $query = mysql_query("SELECT location_name FROM location WHERE location_id = $location_id");
      while ($row = mysql_fetch_array($query)) 
      {
      $location_name = $row['location_name'];
          }

    //Insert room & location data held in $location_name & $room_name into room_location table
    $sql="INSERT INTO room_location (location_name, room_name) VALUES (('$location_name'), ('$room_name'))"; 
    echo "Location and Room name entered was ", $location_name, " & ", $room_name;  

    //I tried using this INSERT below but it inserts the array indexes instead of elements to location_name, room_name.
    //$sql="INSERT INTO room_location (location_name, room_name) VALUES (('".$_POST['select_location']."'), ('".$_POST['select_room']."'))";    
?>

Finally cracked this myself...not the most elegant solution but it works :D Thanks for the pointers.

*UPDATE to process.php ***

<?php
    //This section retrieves the room name selected on dropdown_form.php page
    $room_id = $_POST['select_room']; //temp variable to hold room_name_id
    $query = mysql_query("SELECT room_name FROM room_name WHERE room_name_id = $room_id");
      while ($row = mysql_fetch_array($query)) 
      {
       $room_name = $row['room_name'];
      }

    //This section retrieves the location name selected on add_room_location_form.php page
    $location_id = $_POST['select_location']; //temp variable to hold location_name_id
    $query = mysql_query("SELECT location_name FROM location WHERE location_id = $location_id");
      while ($row = mysql_fetch_array($query)) 
      {
      $location_name = $row['location_name'];
          }

    //Insert room & location data held in $location_name & $room_name into room_location table
    $sql="INSERT INTO room_location (location_name, room_name) VALUES (('$location_name'), ('$room_name'))"; 
    echo "Location and Room name entered was ", $location_name, " & ", $room_name;  

    //I tried using this INSERT below but it inserts the array indexes instead of elements to location_name, room_name.
    //$sql="INSERT INTO room_location (location_name, room_name) VALUES (('".$_POST['select_location']."'), ('".$_POST['select_room']."'))";    
?>
心的憧憬 2024-11-21 12:20:54

尝试将自动增量设置为数据库中的 id 字段

Try setting auto increment to your id field in database

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文