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

报告相同问题?

悬赏问题

  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题