douwei1904 2015-11-12 15:52
浏览 596
已采纳

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

I have an input form which includes a list box where multiple items can be selected:

<select name="MultiRoomSelect[]" id="MultiRoomSelect" multiple="multiple">

I am trying to read the content of $_POST['MultiRoomSelect'] and use the result to look up records in a table.

For testing the result of MultiRoomSelect[] is "2,3,4" which are the correct ID's for the record(s) lookup I want to execute.

The lookup query I have is

SELECT RecordID, RoomID FROM Jafa WHERE RoomID = 

It's the = part I am very unsure about, how can I use the result of the MultiRoomSelect[] to populate a variable I can use in the query like:

SELECT RecordID, RoomID FROM Jafa WHERE RoomID = $value //MultiRoomSelect[]

and keep looping until the array has read all three array values.

I hope I have written this clearly. Many thanks in advance.

  • 写回答

2条回答 默认 最新

  • dousi2553 2015-11-12 16:04
    关注

    This is what I meant:

    $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*/
    }
    

    Which would yield the final sql as:

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

    Using the following form to test

        <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>
    

    And randomly selecting a large range of non-contiguous numbers generated the following 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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?