简体   繁体   中英

Loop through an array and use the result of each loop as a variable for inserting to 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.

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

I see you've already imploded the result and have everything required inside $MultiRoomIDResult .

You can use a simple IN clause like @RamRaider mentioned.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM