循环遍历数组并使用每个循环的结果作为插入MySQL的变量

时间:2015-11-12 15:52:50

标签: php mysql

我有一个输入表单,其中包含一个列表框,可以选择多个项目:

<html>
  <body>


    <script>
      function openPopup(mydiv) {
        popup = document.getElementById("myPopup");
        popup.style.display = "block";
        myPopupContent = document.getElementById("myPopupContent");
        myPopupContent.textContent = document.getElementById(mydiv).textContent;
      }

      function closePopup() {
        popup = document.getElementById("myPopup");
        popup.style.display = "none";
      }      
    </script>

    <style>
      #myPopup {
        display: none;
        position: absolute;
        top:50px;
        right:50%;
        background-color: blue;
        height:100px;
        width:100px;
      }

      #myExit {
        position: absolute;
        right:0px;
        text-align: right;
        color:white;
        background-color: red;
      }
    </style>

    <div id="myPopup">
      <a href="#" id="myExit" onclick="closePopup();return false">x</a>
      <div id="myPopupContent"></div>
    </div>


    <a href="#" id="chan001" onclick="openPopup('chan001'); return false;">Foo</a>
    <a href="#" id="chan002" onclick="openPopup('chan002'); return false;">Fii</a>
    <a href="#" id="chan003" onclick="openPopup('chan003'); return false;">Faa</a>



  </body>
</html>

我正在尝试阅读<select name="MultiRoomSelect[]" id="MultiRoomSelect" multiple="multiple"> 的内容,并使用结果在表格中查找记录。

为了测试$_POST['MultiRoomSelect']的结果是MultiRoomSelect[],它是我想要执行的记录查找的正确ID。

我的查询查询是

"2,3,4"

这是我非常不确定的部分,我如何使用SELECT RecordID, RoomID FROM Jafa WHERE RoomID = 的结果来填充我可以在查询中使用的变量,如:

MultiRoomSelect[]

并保持循环,直到数组读取了所有三个数组值。

我希望我已经写清楚了。非常感谢提前。

2 个答案:

答案 0 :(得分:1)

这就是我的意思:

$ids=$_POST['MultiRoomSelect'];

$sql="select `RecordID`, `RoomID` from `Jafa` where `RoomID` in ( ".implode( ',', $ids )." );";



/* Query the db once: pseudo code */
$results = $db->query( $sql );

/* Process recordset */
while( $rs = $result->fetch() ){
    /* show records etc*/
}

哪会产生最终的sql为:

select `RecordID`, `RoomID` from `Jafa` where `RoomID` in ( 1,2,3 ); 

使用以下表格进行测试

    <form method='post'  action='/test/target.php'>
        <h1>Multi-Select SQL</h1>
        <select name="MultiRoomSelect[]" id="MultiRoomSelect" multiple="multiple">
        <?php
            for( $i=1; $i < 100; $i++ ) echo '<option value='.$i.'>'.$i;
        ?>
        </select>
        <input type='hidden' name='section' value='multiselectsql' />
        <input type='submit' id='sub' value='Submit'>
    </form>

随机选择大量不连续的数字生成以下sql:

select `RecordID`, `RoomID` from `Jafa` where `RoomID` in ( 46,47,48,49,50,56,57,58,64,65,66,67,68,69,70,71,72,74,76,78,80,82,84,86,88,90,92,93,96 ); 

答案 1 :(得分:0)

我看到你已经imploded结果,并且$MultiRoomIDResult内有所需的一切。

您可以使用像@RamRaider一样的简单IN子句。

SELECT * FROM jafa where roomid IN ($MultiRoomIDResult);