Page 1 of 1

List box + MySQL ?

Posted: Tue Mar 03, 2009 1:34 pm
by mhw
Hello again everyone.

I'm doing some basic php and MySQL and once more need a small hand. I've never tried list boxes with MySQL so this is something completely new to me.

Anyway, I have created a table with the following fields:

Service 1
Service 2
Service 3

Currently there is no value for any of the tables, as I want this to be controlled by a HTML list box. The options of the list box would be "Online" and "Offline". I have a PHP page created and linked up with the database, I just need help with the code so that once the list box is changed and the user clicks the "ok" button, the value for say Service 1 changes?

Any pointers? Thanks guys. :)

Re: List box + MySQL ?

Posted: Tue Mar 03, 2009 2:44 pm
by ben.artiss
From what you said it sounds like you should post the form with the lists to the PHP file and insert into or update the database:

HTML file

Code: Select all

<form method="post" action="script.php">
<select name="service1">
    <option value="offline">Offline</option>
    <option value="online">Online</option>
</select>
<input type="submit" value="Go" />
</form>
script.php

Code: Select all

<?php
if (isset($_POST['service1'])) {
    include('path/to/database.php'); // connect to the db
    $service = $_POST['service1']; // get posted value
    $insertSQL = mysql_query("INSERT INTO `table` (`column`) VALUES ('$service')", $conn) or die(mysql_error()); // insert into database
    header("Location: path/to/success.php"); exit; // leave script
} else {
    header("Location: path/to/naughty.php) exit; // just in case
}
?>
But if you want to change an existing value you should take a look at mysql's update. Also, you'd need a query before the form if you wanted to select either offline or online in the list dynamically. Sorry I can't be more specific! :)

Re: List box + MySQL ?

Posted: Tue Mar 03, 2009 3:45 pm
by user333
Correct solution, but a little security will not harm:

Code: Select all

 
$service = preg_replace("/[^a-z]*/", "", $_POST['service1']); // get posted value
 
There are many other ways to clear the input like PDO(If it is used)/mysql_real_escape_string() and others but this is one of the simplest ones.

Re: List box + MySQL ?

Posted: Tue Mar 03, 2009 4:34 pm
by ben.artiss
Nice to know other people spot it too! :) Keep up the keen eye user333.