...

View Full Version : Update checkbox value in MySql Database



monkey64
03-04-2007, 08:30 PM
Hi there

I'm quite a newbie to PHP and MySql, but I've got a sample database working.
What I'm tring to do is, I am quite sure, really simple...

I have a form and want to store checkbox values back to the database. I first created a TINYINT field in the database and gave a default value of '0'. So far, I'm able to read the values from the database in my form by using this code:



if ($row['allow'] == 1)
{
echo "<td width=20><input type='checkbox' checked>";
}
else
{
echo "<td width=20><input name type='checkbox' unchecked>";
}

But I now want to be able to record any new values from the form back to the database. I think it might have something to do with the form action event.

Can anyone enlighten me? Here's my (rough) code so far:




<?php

// Make a MySQL Connection
$host="localhost";
$user="user";
$password="password";

mysql_connect($host,$user,$password);
mysql_select_db("realbab_clickdata") or die(mysql_error());

// Get all the data from the table
$result = mysql_query("SELECT * FROM msg ORDER BY id DESC")
or die(mysql_error());

// Add a table header

echo "<table width='100%' cellspacing='1' cellpadding='1' border='0' bgcolor='#FFCC99' style='margin-bottom:6px; border:#000000 solid 2px'>
<tr style='font-size:11px; font-family:Arial, Helvetica, sans-serif; font-weight:bold;'>";


//This is the main table

echo "<table width='1200' cellspacing='1' cellpadding='1' border='1' bgcolor='#FFCC99'>";

// keeps getting the next row until there are no more to get

while($row = mysql_fetch_array( $result ))
{

// Print out the contents of each row into a table
echo "<tr style='font-size:12px; font-family:Arial, Helvetica, sans-serif'>";

echo "<td width=30>" . $row['id'] . "</td>";
echo "<td width=270>" . $row['msg'] . "</td>";
echo "<td width=50>" . $row['name'] . "</td>";
echo "<td width=20>" . $row['page'] . "</td>";

if ($row['allow'] == 1)
{
echo "<td width=20><input type='checkbox' checked>";
}
else
{
echo "<td width=20><input name type='checkbox' unchecked>";
}

}

echo "</table><p></p>";

?>




Thanks in advance

Inigoesdr
03-04-2007, 09:30 PM
After you select the database you would do something like this:


<?php
if(!empty($_POST))
{
$test = !empty($_POST['test']) ? 1 : 0; // where $_POST['test'] is the name of your checkbox
// here you would update the database
}
?>

You need to name your checkbox inputs though. Oh, you need all of your inputs inside of a form too:

<form action="<?=$_SERVER['SCRIPT_NAME'];?>" method="post">
<input type="checkbox" name="test" value="1" checked />
<input type="submit" value="Update" />
</form>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum