Simple PHP Shopping Cart Quantity - php

I am a rookie in PHP and I'm trying to make a shopping website for a college module.
Here is my products page that lists all of the products:
//Get the category from the URL
$category = $_GET['category'];
echo("<h1>Products: $category</h1>");
echo("<FORM METHOD='LINK' ACTION='products.php'>");
echo("<INPUT TYPE='submit' VALUE='Back'>");
echo("</FORM>");
echo("<hr>");
//Include database file with settings im
require "db.inc";
//Store the connection in a variable for later use
$connection = mysql_connect($hostname, $username, $password);
//Check for connection
if(! $connection )
{
die('Could not connect: ' . mysql_error());
}
//If the category is all then
if($category == "All")
{
$query = "SELECT * FROM products";//Select everything
}
//If it's not then..
else
{
$query = "SELECT * FROM products WHERE category = '$category'";
}
//Open the Database
mysql_select_db($dbname);
//Start the query
$result = mysql_query($query, $connection);
if(!$result )
{
die('Could not retrieve data: ' . mysql_error());
}
//Loop through the rows and display each object
while($row = mysql_fetch_array($result))
{
//Define all variables we will use
$productid = $row['id'];
$productname = $row['name'];
$productdescription = $row['description'];
$productimage = $row['image'];
$productprice = $row['price'];
$productstock = $row['stock'];
//Display each product and it's info
echo("<h3>$productname</h3>");
echo("<a href=$productimage><img border='0' alt=$productname src=$productimage width='100' height='100'></a><br>");
echo("$productdescription<br>");
echo("<b>Price:</b> £$productprice (ex VAT)<br>");
echo("<b>Stock:</b> $productstock<br>");
//Create a link for each product, that goes to the add to cart script with the product id in the URL
//Only if youre logged in can you see this button
if( isset($_SESSION['login']))
{
echo("<FORM METHOD='POST' ACTION='process_addtocart.php?id=$productid&quantity=1'>");
echo("<INPUT TYPE='submit' VALUE='Add to Cart'>");
echo("</FORM>");
}
echo("<hr>");
}
As you can see it gets all the products from the db and adds a button that links to the addcart php file with the id and quantity to add.
Here is my add to cart function:
<?php
//Make sure user is logged in first
if( isset($_SESSION['login']))
{
//Setup our shopping cart if it isnt already setup into an array table to hold item info
if( empty($_SESSION['shoppingcart']))
{
$_SESSION['shoppingcart'] = array();
}
$id = $_GET['id'];
$quantitytoadd = $_GET['quantity'];
if( isset( $_SESSION['shoppingcart'][$id]))
{
//CODE TO ADD TO QUANTITY????
}
array_push($_SESSION['shoppingcart'], $id);
echo("Item has been added to your cart!");
}
else
{
echo("<p>Please login to add items to your shopping cart!</P>");
}
?>
How would I make it increment a quantity value for THAT specific ID in the array table each time?
Would it be something like:
array_push($_SESSION['shoppingcart'], $id, $quantitytoadd++);

Or you could just increment the product by one with what you have already and make the product ids the key. Keep your inputs clean also.
<?php
//Make sure user is logged in first
if( isset($_SESSION['login']))
{
//Setup our shopping cart if it isnt already setup into an array table to hold item info
if( empty($_SESSION['shoppingcart']))
{
$_SESSION['shoppingcart'] = array();
}
$id = $_GET['id'];
$quantitytoadd = $_GET['quantity'];
if( isset( $_SESSION['shoppingcart'][$id]))
{
//CODE TO ADD TO QUANTITY????
$_SESSION['shoppingcart'][$id]++;
}
else
{
$_SESSION['shoppingcart'][$id] = 1;
}
echo("Item has been added to your cart!");
}
else
{
echo("<p>Please login to add items to your shopping cart!</P>");
}
?>

Related

Is it possible to connect a button from another table to another table to get the data?

I have two tables in one database. The first one is the g1 where the buttons' data is located. The second is the gradeone, where the enrollees' data is located. I want to display the data from the table "gradeone" by clicking the
specific buttons.
Assuming that I added 2 sections. Section 1 and section 2. I click the button section1. By clicking it, I want to display the data of the enrollee from table "gradeone" where the section is 1.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$sectionnumber ="";
$datasuccess ="";
$error ="";
function getPosts(){
$posts = array();
$posts[1] = $_POST['sectionnumber'];
return $posts;
}
if(isset($_POST['add'])){
$data = getPosts();
if(empty($data[1])){
$error = 'Enter The User Data To Insert';
}else {
$insertStmt = $con->prepare('INSERT INTO g1(sectionnumber) VALUES(:sectionnumber)');
$insertStmt->execute(array(
':sectionnumber'=> $data[1]
));
if($insertStmt){
$datasuccess = "<font color='#f8234a'>New added</font>";
}
}
}
?> //Code for adding a button
<?php
require 'connection.php';
$sql = "SELECT sectionnumber FROM g1";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<button type='button' class='btn'>Section " . $row["sectionnumber"] . "</button></a><hr>";
}
} else { echo "<B>No Sections</B>"; }
$con->close();
?> //Code for displaying the button
<html>
<body>
<form action=">
<input type="number" name="sectionnumber">
<input type="submit" name="add">
</form>
</body>
</html>

process transaction function paypal

I am building an e-commerce application through video tuition.
I have a process_transaction function that parses PayPal tx params from the URL upon a successful purchase and populates an 'orders' table in phpMyAdmin 4.8.0.
Previously, if your refreshed my thank_you.php page the orders continue to populate my 'orders' table (as there was previously no session destroy built into the aforementioned function).
The problem is, the code suggested to prevent such by our tutor for this function does not work. When run, the 'orders' table is no longer populating from the transactions nor is session_destroy operational.
I was wondering what is wrong with the function.
thank_you.php
<?php require_once("../resources/config.php"); ?>
<?php require_once("../resources/cart.php"); ?>
<?php include('../resources/templates/front/header.php') ?>
<?php process_transaction(); ?>
<!-- Page Content -->
<div class="container">
<h1 class="text-center">THANK YOU</h1>
<h3>Nippon will get your products shipped today</h3>
</div>
<!-- /.container -->
<?php include('../resources/templates/front/footer.php') ?>
cart.php (not working properly - does not persist orders in db, or session destroy)
<?php
function process_transaction() {
if(isset($_GET['tx'])) {
$amount = $_GET['amt']; // get amount
$currency = $_GET['cc'];
$transaction = $_GET['tx']; //
$status = $_GET['st']; // get status ie completed
$total = 0;
$item_quantity = 0;
foreach ($_SESSION as $name => $value) {
if($value > 0 ) {
if (substr($name, 0, 8) == "product_") {
$length = strlen($name);
$id = substr($name, 8, $length);
$send_order = query("INSERT INTO orders (order_amount,order_transaction,order_status,order_currency) VALUES('{$amount}','{$transaction}','{$status}','{$currency}')");
$last_id = last_id();
confirm($send_order);
$query = query("SELECT * FROM products WHERE product_id = " . escape_string($id) . " ");
confirm($query);
while($row = fetch_array($query)) {
$product_price = $row['product_price'];
$product_title = $row['product_title'];
$sub = $row['product_price'] * $value;
$item_quantity += $value;
$insert_report = query("INSERT INTO reports (product_id, order_id, product_title, product_price,product_quantity) VALUES ('{$id}','{$last_id}','{$product_title}','{$product_price}','{$value}')");
confirm($insert_report);
}
$total += $sub;
echo $item_quantity;
}
}
}
session_destroy();
} else {
redirect("index.php");
}
}
functions.php
function query($sql) {
global $connection;
return mysqli_query($connection, $sql);
}
function fetch_array($result) {
return mysqli_fetch_array($result);
}
function escape_string($string) {
global $connection;
return mysqli_real_escape_string($connection,$string);
}

Code required to automatically update database - fix needed

I could really do with some help. I've successfully managed to display how many items I have in stock on my product page using PHP code with help from other members which I am most grateful for.
I'm very new to PHP and have been trying to figure this out for days.
I have a database set up with a table called 'items' which I would like to update automatically if possible. I know I can do this manually but I want to prevent over selling stock I have not got.
For instance, when a customer has placed an order I would like for this to happen:
1) Get the quantity of items in stock under 'inventory' and reduce the number by 1.
2) Have the new quantity in stock replace the old quantity displayed on my product page.
Now, I use Mals-e for my shopping cart and have all orders sent to the database with a remote call. This is working fine so no problems with info going to the database.
This is the code I use to display the quantity:
<?php
include("config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
// Get a specific result from the "items" table
$result = mysql_query("SELECT * FROM items
WHERE Product='Baby Girls Sock Cupcake'");
while($row = mysql_fetch_array($result))
{
echo "Available Stock: ";
echo $row['inventory'] . " " . $row['Inventory'];
}
mysql_close();
?>
This is my form code:
<?php
echo "<form action=\"http://ww6.aitsafe.com/cf/add.cfm\" method=\"post\">\n";
echo "<input type=\"hidden\" name=\"userid\" value=\"12345678\">\n";
echo "<input type=\"hidden\" name=\"id\" value=\"6\">\n";
echo "<input type=\"hidden\" name=\"scode\" value=\"ABCD123\">\n";
echo "<input type=\"hidden\" name=\"nocart\">\n";
echo "<input type=\"hidden\" name=\"return\" value=\"http://www.mysite.co.uk\">\n";
echo "<b>Qty:</b> <input type=\"text\" name=\"qty\" size=\"1\">\n";
echo "<input type=\"hidden\" name=\"product\" value=\"Socks\">\n";
echo "<input type=\"hidden\" name=\"price\" value=\"1.85\">\n";
echo "<input name=\"submit\" value=\"Add to Cart\" type=\"submit\">\n";
echo "</form>";
?>
These are other bits of code I think I may need but I don't know what to do with them or if they are really what I need:
<?php
$ud_id = $_POST['ud_id'];
$ud_scode = $_POST['ud_scode'];
$ud_product = $_POST['ud_product'];
$ud_price = $_POST['ud_price'];
$ud_inventory = $_POST['ud_inventory'];
// query update
$sql = "UPDATE items SET `items` (`ID`, `$ud_Scode`, `$ud_Product`, `$ud_Price`, `$ud_Inventory` WHERE inventory=`$ud_Inventory`)
VALUES (\'6\', \'ABC123\', \'Socks\', \'1.85\', \'2\');";
?>
I notice in this line of code:
echo "<form action=\"http://ww6.aitsafe.com/cf/add.cfm\" method=\"post\">\n";
Other people have a link to a php page:
echo "<form action=\"update.php\" method=\"post\">\n";
Does the link have to be to a php page?
I also have this:
<?php
include("config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
// Get a specific result from the "items" table
$result = mysql_query("SELECT * FROM items
WHERE inventory='$inventory'") or die(mysql_error());
while($row = mysql_fetch_array($result))
// check stock
if ($row !== false)
{
echo 'out of stock';
}
else if ($row['count'] == 0)
{
echo 'out of stock.';
}
// if there is stock decrease quantity
$sql = "UPDATE items SET inventory = (inventory -1) WHERE id = '6'";
$result = mysql_query;
}
mysql_close();
?>
I know it's not right and I've got it completely wrong. Could someone please point me in the right direction with an example of code that I need, as I think I need more than this to get it to work.
My htm code and php code are on separate pages, I echo the available quantity in the htm page.
Many Thanks.
This is the code that is used to update the database when an order is placed with remote call fro mals-e:
<?PHP
include("sbconf/config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
$order_date=time("m j y h:i");
// create varibles
$id = $_POST['id'];
$username = $_POST['username'];
$ip = $_POST['ip'];
$method = $_POST['method'];
$cart = $_POST['cart'];
$discount = $_POST['discount'];
$subtotal = $_POST['subtotal'];
$shipping = $_POST['shipping'];
$tax = $_POST['tax'];
$total = $_POST['total'];
$shipping_zone = $_POST['shipping_zone'];
$inv_name = $_POST['inv_name'];
$inv_company = $_POST['inv_company'];
$inv_addr1 = $_POST['inv_addr1'];
$inv_addr2 = $_POST['inv_addr2'];
$inv_state = $_POST['inv_state'];
$inv_zip = $_POST['inv_zip'];
$inv_country = $_POST['inv_country'];
$del_name = $_POST['del_name'];
$del_addr1 = $_POST['del_addr1'];
$del_addr2 = $_POST['del_addr2'];
$del_state = $_POST['del_state'];
$del_zip = $_POST['del_zip'];
$del_country = $_POST['del_country'];
$tel = $_POST['tel'];
$fax = $_POST['fax'];
$email = $_POST['email'];
$message = $_POST['message'];
$sd = $_POST['sd'];
// query insert
mysql_query("INSERT INTO orders (id,username,ip,date,method,cart,discount,subtotal,shipping,tax,total,shipping_zone,inv_name,inv_company,inv_addr1,inv_addr2,inv_state,inv_zip,inv_country,del_name,del_addr1,del_addr2,del_state,del_zip,del_country,tel,fax,email,message,sd)
VALUES
('$id','$username','$ip','$order_date','$method','$cart','$discount','$subtotal','$shipping','$tax','$total','$shipping_zone','$inv_name','$inv_company','$inv_addr1','$inv_addr2','$inv_state','$inv_zip','$inv_country','$del_name','$del_addr1','$del_addr2','$del_state','$del_zip','$del_country','$tel','$fax','$email','$message','$sd')");
?>
Link to mals-e I used the php_mals.zip file:
https://www.mals-e.com/tpv.php?tp=26
I don't understand what you really want. here is a corrected version of the last piece of code you gave us (i removed your comments and put mines) :
<?php
include("config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
$result = mysql_query("SELECT * FROM items
WHERE inventory='$inventory'") or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row !== false)
{
echo 'out of stock';
}
else if ($row['count'] == 0)
{
echo 'out of stock.';
}
// only execute this request if there is stock
else
{
$sql = "UPDATE items SET inventory = (inventory -1) WHERE id = '6'";
}
//what is this ?
//$result = mysql_query;
}
BTW? do not use mysql_ functions, they are now deprecated. have a look at mysqli (http://fr.php.net/mysqli) or pdo (http://php.net/manual/fr/ref.pdo-mysql.php).
And to answer your question
I notice in this line of code:
echo "<form action=\"http://ww6.aitsafe.com/cf/add.cfm\" method=\"post\">\n";
Other people have a link to a php page:
echo "<form action=\"update.php\" method=\"post\">\n";
Does the link have to be to a php page?
Not really, this page can be anything. The thing is that if you want to process the form inputs with php, u'll have to call a page interpreted by php. By default apache recognizes php files those which have php extensions (*.php, *.php5 ...) but you can configure it to be able to handle all extensions you want (have a look at https://stackoverflow.com/a/12021997/2806497)

Taking user input from a <select> into a variable

Im currently working on a small university project. To develop a basic e-commerce php site. We have been given code or provided code within seminars which we are then to customise/develop further to our needs.
I am trying to adapt the following code to add an additional piece of information. The cart.php code builds a shopping cart functionality, which displays the product name, quantity and then allows the user to increase/decrease the quantity.
I am attempting to add the users (selected) product size to the shopping cart. Which they can select on product.php. I have already created the database support for this within product.php I just need the users selected option to then appear over in the cart.php.
Im not entirely sure how to do this correctly. My first problem is how do I record the users selection within product.php into a variable which can be transferred over to cart.php.
The second problem is then how to modify the cart.php to do this also, you shall see in cart.php I have attempted to add the product size to the table.
I really would appreciate some guidance with this.
Product.php
<div align="center"><?php
session_start();
//Connect to Session
include "conn.php";
//Retrieve Header
include "header.php";
//Query
//Get Product ID
if (isset($_GET['id'])){
$product_id = $_GET['id'];
//Select Product Attributes Query where Product ID is the selected product ID
$q="SELECT ProductName,img,ProductID,Description,p_spec1,p_spec2,p_spec3,p_spec4,p_spec5,Price,size_1,size_2,size_3,size_4,size_5 FROM Products
WHERE ProductID=$product_id";
//Retrieve and excute query from database and save results into a variable
$result = mysqli_query($_SESSION['conn'],$q);
//Display Product
if ($row = mysqli_fetch_array($result)){ //Create Product Attribute Array
echo "<div>
<p><b>Name:</b>" .$row[0]."</p>
<p><img src=".$row[1]."></p>
<p><b>Product Code:</b>" .$row[2]."</p>
<p><b><u>Product Description:</b></u></p>
<p>".$row[3]."</p>
<p><b><u>Product Spec:</b></u>";
//Count total product specifications and adjust bullet points
for($i=4;$i<9;$i++) {
if($row[$i]!='')
echo "<li>".$row[$i]."</li>";
}
echo"
<p><b>Price: </b>£".$row[9]."</p>
<p><b>Size:</b><select>";
//Count total product sizes available and adjust drop-down menu
for($i=10;$i<15;$i++) {
if($row[$i]!='')
echo "<option>".$row[$i]."</option>";
}
echo"</select>
</p>
</p>
</div>";
}
//Add Item to basket
echo "<div><input type='submit' value='Add to Basket'</div>";
}
//Retrieve Footer
include "footer.php";
?>
</div>
I have assumed in product.php that a variable $product_size will need to be actioned over to cart.php, however how do I collect the users selection into a variable?
Cart.php
<?php
//Start Session
session_start();
include "conn.php"; //Connect to database
include "header.php"; //Retrieve Header
//View the current shopping cart session
function viewcart(){
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart']; //store the cart array into a variable then display the content
echo "<table border=\"1\"> <tr> <th>Product</th> <th>Size</th> <th>Quantity</th> <th>Action</th></tr>";
foreach ($cart as $product=>$quantity){
$q = "SELECT ProductID FROM Products WHERE ProductName = '$product' LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_id = $row['ProductID'];
echo "<tr><td>$product</td>
<td>$product_size</td>
<td>$quantity</td><td>
-
+ </td> </tr>";
mysqli_free_result($result);
}
echo "</table>";
subtotal($cart); //display the subtotal
} else { //if shopping cart is empty
echo "<p>Your Basket is empty.</p>";
}
}
function subtotal($cart){
$total = 0; //initialise total
if (!empty($cart)){
foreach ($cart as $product => $quantity){
$q = "SELECT Price FROM Products WHERE ProductName ='$product' LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$price = $row['Price'];
$total += $price * $quantity;
}
echo "<p>Total: £$total |
Empty cart</p>";
} else {
unset($_SESSION['cart']); //destroy empty cart
echo "<p>Your Basket is empty.</p>";
}
}
function addproduct($product_id, $product_qty){
$q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['ProductName']; //get the product name from product id because it is better to display name than id in the cart
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
$cart[$product_name] += $product_qty;
}
else { //otherwise, add new product-quantity pair to the array
$cart[$product_name]=$product_qty;
}
$_SESSION['cart'] = $cart; //write the updated array back to session variable
}
else { //if shopping cart is empty
$cart = array($product_name=>$product_qty); //add product and quantity to the shopping cart
$_SESSION['cart'] = $cart; //write the updated array back
}
mysqli_free_result($result);
}
function deleteproduct($product_id, $product_qty){
$q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['ProductName'];
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if product exists, update quantity
$cart[$product_name] -= $product_qty;
if ($cart[$product_name] == 0){ //if the qty 0, delete key
unset($cart[$product_name]);
}
}
else { //exception
echo "<p>Error!</p>";
}
$_SESSION['cart'] = $cart; //write array back to session variable
} else {
echo "<p>Error!</p>";
}
mysqli_free_result($result);
}
function emptycart(){
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
unset($_SESSION['cart']);
}
else {
echo "<p>Error!</p>";
}
}
if (isset($_GET['action'])){
if ($_GET['action']=='view'){
viewcart();
} elseif ($_GET['action']=='add'){
if (isset($_GET['product'])){
$product_id = $_GET['product'];
$product_qty = 1; //default product value
addproduct($product_id, $product_qty);
viewcart();
} else {
echo "<p>There is an error?</p>";
}
}
elseif ($_GET['action'] == 'delete'){
if (isset($_GET['product'])){
$product_id = $_GET['product'];
$product_qty = 1; //default product value
deleteproduct($product_id, $product_qty);
viewcart();
}
else {
echo "<p>There is an error!</p>";
}
} elseif ($_GET['action']=='empty') {
emptycart();
viewcart();
}
else {
echo "<p>There is an error! </p>";
}
}
else { echo "<p>There is an error!</p>"; }
include "footer.php"; //template design part
?>
P.S I am aware of SQL injection issues.
Thank You!
I built something similar to this some time ago and faced the same (rather common) problem.
The solution requires you to create a session variable to store the selected product id's. I think I stored one or more arrays into the session and used the information to populate the checkout page.
I also stored the session data in a table so the user could access it between sessions,
but that was a more advanced feature.
Take Away: use a session variable to store an array of product id's
There are some fundamental flaws here.
To start, create valid HTML. Make sure the form is wrapped in <form></form> tags. That form should have an action: <form action="cart.php" method="POST">
Your select for "size" needs to have a name: <select name="productSize">.

php retain an array checkbox

I'm a complete noob but I have searched everywhere and can't find a solution.
What I have is an array of courses that I pull from my database (e.g.:
maths, art, science). These can change so I must add new courses all the time.
When a user ticks 2 of 3 courses (for example) but fails to add his username, then after the validation I want those 2 checkboxes to keep their old tick, so he must refill only his username in order to proceed.
What I get are all the checkboxes ticked :{
I'm so confused.
<?PHP
$check="unchecked";
?>
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
foreach ($_POST['cid'] as $cid ) {
$check="checked";
}
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>
You have to set your $checked variable independently for each checkbox.
$checkedBoxes = array();
foreach($cid as $id) {
$checkedBoxes[$id] = "checked='false'";
}
foreach ($_POST['cid'] as $cid) {
$checkedBoxes[$cid] = "checked='true'";
}
Then in your loop that outputs the checkboxes, print the corresponding $checked value.
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' {$checkedBoxes[$cid]}>"; // here are the courses(checkboxes)
}
Is this what you want?
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$cid_array = $_POST['cid'];
/*foreach ($_POST['cid'] as $cid ) {
$check="checked";
}*/
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
if(is_array($cid_array))
{
if(in_array($cid, $cid_array))
{
$check="checked='checked'";
}
else
{
$check="";
}
}
else//it is not array because nothing was checked
{
if($cid == $cid_array)
{
$check="checked='checked'";
}
else
{
$check="";
}
}
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>

Categories