Daniel Soublett
Daniel Soublett

Reputation: 888

Select multiple (PHP and MySQL)

I have a form with a select multiple like this:

<select name="states[]" size="5" multiple>
    <option value="2">state 1</option>
    <option value="3">state 2</option>
    <option value="4">state 3</option>
    <option value="5">state 4</option>
    <option value="6">state 5</option>
</select>

I want to have the possibility to choose more than one state, and then make the query to my database and show the description of each state chosen.

So this is what I have to make the query using PHP and MySQL:

$state = $_POST['states'];
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db); 

while($row = mysql_fetch_array($data)){
    $result=$row['description'];
}

echo $result;

I have that code and it doesn't show anything.

How can I fix this problem?

Upvotes: 1

Views: 26664

Answers (5)

NyC Solutions Group
NyC Solutions Group

Reputation: 1

Example (pages for edit):

//On select_multiple.php (Form):

<?php
//Conn
include('incl_config.php');

//Multiple data to bring
$sql = " select COD_DXS,VALOR_DXS from hc_dxsindromico where ESTADO_DXS='1' ";
$result=@mysql_query($sql);       
?>

//In the form select:
<select  multiple="multiple" size="7"  name="dxsindromico[]"> //look yes or yes brackets []
    <option value="" selected="selected">Choose one or more options</option>
        <?php
        while($row=mysql_fetch_array($result)){
    ?>
        <option value="<?php echo $row['COD_DXS']; ?>" style="color:#F00;"><?php echo $row['VALOR_DXS'];?></option> 
        <?php } ?>  
</select>

//////////// On grabar_mtr.php ///////////////

<?php
include('incl_config.php');
/*Multiple selection form in HTML5, PHP and Bootstraps
Created by: www.nycsoluciones.com
Version: 1.1*/

//we use a foreach to traverse the array (values of our select and save them in the table dxsindromico_data)

if(isset($_POST['dxsindromico'])){
    foreach( $_POST['dxsindromico'] as $insertar ) {
        //echo $insertar;
        $sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
        //echo $sqli;
        //exit;
        $resulti=mysql_query($sqli);
    } 
} else{
    foreach( $_POST['dxsindromico'] as $insertar ) {
        //echo $insertar;
        $sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
        $resulti=mysql_query($sqli);
    } 
}
?>

Upvotes: 0

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Try this

$state = $_POST['states']; // return Array
$count_states = count( $state );

if( $count_states > 0) {
    $states = implode( ',', $state);
    $data = mysql_query("SELECT * from states WHERE id_state IN ($states)",$db); 

    while($row = mysql_fetch_array($data)){
       echo $row['description'];
    }
}

Upvotes: 7

Kai Qing
Kai Qing

Reputation: 18833

You could build the string by iterating through the array:

$state = "";

foreach($_POST['states'] AS $s)
{
    // Sanitize $s here
    $state .= "`id_state` = " . $s . " OR";
}

if($state)
{
    $state = substr($state, 0, -3);

    $data = mysql_query("SELECT * from states WHERE $state",$db); 

    while($row = mysql_fetch_array($data)){
        echo $row['description'];
    }
}

Of course, you should use something like MySQLi or PDO to handle database interaction. They will have ways to sanitize input easily so you can avoid obvious SQL injection.

Tamil has a pretty good IN select method as well. This is just one option.

Upvotes: 0

stUrb
stUrb

Reputation: 6832

$_POST['states'] holds an Array with all the ID's of the selected states.

Off course you can query your database for every posted state_id, but way nicer (and faster) would it be to make a query which looks like this and uses only one query:

SELECT description FROM states WHERE id_state=1 OR id_state=2 etc etc

This also might be a good point to start using a database abstraction layer like PDO. As the number of posted states is variable, we need to make the statement also variable:

// The [connection setup][2] by PDO is done in $conn, with some proper exception handlers
// e.g. $conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

// Fill an array with count() number of elements with value 'id_state=?'
$place_holders = array_fill(0, count($_POST['state']), 'id_state= ?');

//implode the array 
$place_holders = implode(' OR ', $place_holders);

// prepare the query
$st = $conn->prepare("SELECT description FROM state WHERE $place_holders");

// execute to above prepared query with the $_POSTED states
$st->execute($_POST['state']);

// traverse the result
foreach($st->fetchAll() AS $r){
     // do some magic
}

Upvotes: 1

Curtis Crewe
Curtis Crewe

Reputation: 4336

This would require a simple foreach to go through the array and get results based on each value as such,

foreach($_POST['states'] as $state) {
    $data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
    $row = mysql_fetch_array($data);
    echo $row['description'];
}

Also since you're not protecting your query in some sort and are using mySQL which has been deprecated as of PHP 5.5.0, I suggest you looking into PDO or mySQLi Prepared statements

Upvotes: 1

Related Questions