Yilmaz Paçariz
Yilmaz Paçariz

Reputation: 186

select box value fetching in php

<select name="column" id="column">
<?php for($i=1; $i<=$sow[0]; $i++){ ?>
<option value="<?php echo $i ?>"><?php echo $i ?>.column</option>
<?php  }?> 
</select>

how can i fetch the value from select box, which one i choosed? I will save it in database

Upvotes: 1

Views: 737

Answers (4)

Brad Christie
Brad Christie

Reputation: 101614

Create a PHP page that can accept (and process) the incoming value:

/MyHandler.php

<?php

  $column = $_GET['column'];
  $json = isset($_GET['json']);

  $db = new PDO(...);

  $q = $db->prepare('INSERT INTO mytable (column) VALUES (?)');
  if ($q->execute(array($_GET['column'])) !== false){
    return $json ? json_encode(array('success'=>true)) : "Success";
  }else{
    return $json ? json_encode(array('success'=>false)) : "Fail";
  }

Then either wrap your select in a <form> and submit it to a php page or use AJAX and submit it to the same page (which would not involve a page refresh).

Form Method:

<form action="/MyHandler.php" method="GET">
  <select name="column" id="column">....</select>
  <input type="submit" value="Save Column">
</form>

Or, the jQuery/AJAX equivalent:

$('#column').change(function(){
  var val = $(this).val();
  $.getJSON('/MyHandler.php',{column:val,json:true},function(d){
    alert(d.success ? 'Value saved' : 'Value could not be saved');
  });
});

Upvotes: 1

Kisaro
Kisaro

Reputation: 281

You will either need to use AJAX to dynamically use PHP to insert into your database, or you need to use a form which involves pressing a submit button and reloading the page each time you insert. Using the latter, you can easily get the value by reading the value inside of $_POST['column'].

Upvotes: 0

Ofir Baruch
Ofir Baruch

Reputation: 10346

Wrap your select in <form method='post' action='...'> and in the "action" file use this code:

<?php

    //Db connection here...
    if(array_key_exists('column' , $_POST))
    {   
    $selected_option = mysql_real_escape_string($_POST['column']);

    mysql_query("INSERT INTO tblName(`fldName`) VALUES('$selected_option')");
    }

?>

Upvotes: 0

j08691
j08691

Reputation: 208012

$_REQUEST['column']; will give you the selected option's value.

Upvotes: 2

Related Questions