PHP SQL + HTML checkboxes

Associate
Joined
1 Mar 2006
Posts
425
Hi


im just looking for a bit of help on the best way to do this..

so i have a sample SQL Database
2rhy9ok.jpg


now from that DB i want my HTML page to show checkboxes ticked if there is a "1" in the corresponding checkbox field


20u4cq8.jpg


can anyone advise on the best way to do this?

thanks ;)
 
hi

thanks for the response

im guessing i will have make the query a variable first?

eg:
Code:
$var = mysql_query("SELECT * FROM chkbx1")
 
how about

Code:
<?php
include_once 'includes/db.php';

$sql = "SELECT somecolumm FROM sometable";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$checked = $result['somecolumm'];

?>

<input type="checkbox" name="somecolumm" value="1" <?php if ($checked == 1) echo 'checked'; ?> />
 
I've expanded on denby's example as his is spot on, the only difference is that instead of "include_once" I would always use "require_once" whenever the database connection file is concerned, I'd rather have the script stop immediately if there's an error. ;)

Code:
<?php
	require_once "db.php";
	$sql 		= "SELECT * FROM database_name";
	$result 	= mysql_query($sql);
	$row 		= mysql_fetch_array($result);
	$chkbox1 	= $result['chkbx1'];
	$chkbox2 	= $result['chkbx2'];
?>
<table>
	<tr>
		<td>1</td>
		<td><input type="checkbox"
			<?php
				if ($chkbox1 == 1)
					echo " checked "
			?>	
		/></td>
	</tr>
	<tr>
		<td>2</td>
		<td><input type="checkbox"
			<?php
				if ($chkbox2 == 1)
					echo " checked "
			?>	
		/></td>
	</tr>
</table>


Nice one , one thing though it doesn't say which table in the DB to pull data from

Should it be select * from database where. Colummname = chkbox1;

?
 
Hi

thanks for all your replies so far , it is greatly appreciated

now they are both constantly checked,even though one of the columns has a "0" in it


e9vfus.jpg






Code:
<?php

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'XXXXXXXXXX');
define('DB_PASSWORD', 'XXX');
define('DB_DATABASE', 'sbsuppli_game');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());

$sql = "SELECT * FROM game";
	$result 	= mysql_query($sql);
	$row 		= mysql_fetch_array($result);
	$chkbox1 	= $result['chkbx1'];
	$chkbox2 	= $result['chkbx2'];
	
?>
<table>
	<tr>
		<td>1</td>
		<td><input type="checkbox"
			<?php
				if ($chkbox1 == 1)
					echo " checked "
			?>	
		</td>
	</tr>
	<tr>
		<td>2</td>
		<td><input type="checkbox"
			<?php
				if ($chkbox2 == 1)
					echo " checked "
			?>	
		</td>
	</tr>
</table>
?>
 
Last edited:
Back
Top Bottom