How to validate input field in update profile of a user - php

The Below code is the profile login system update user pade:
In the below code i have already data in the text box(retrive data from database). i want to validate if i erase data and submit:
help me friends i want to validate the input field if the input field is empty:
<?php
session_start(); // Must start session first thing
// Here we run a login check
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
//Connect to the database through our include
include_once "database.php";
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_POST['qualific']) {
$fullname = $_POST['fullname'];
$contact = $_POST['contact'];
$qualific = $_POST['qualific'];
$sql = mysql_query("UPDATE jobseeker_members SET fullname='$fullname', contact='$contact', qualification='$qualific' WHERE id='$id'");
echo 'Your account info has been updated, visitors to your profile will now see the new info.<br /><br />
To return to your profile edit area, click here';
exit();
} // close if post
?>
<?php
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM jobseeker_members WHERE id='$id' LIMIT 1");
while($row = mysql_fetch_array($sql)){
$fullname = $row["fullname"];
$contact = $row["contact"];
$qualific = $row["qualification"];
}
?>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" name="form" id="form" onsubmit="return validate_form ( );">
<label>FullName:</label>
<input class="txtbox" name="fullname" type="text" id="fullname"
value="<?php echo "$fullname"?>"/>
<label>Contact No:</label>
<input class="txtbox"name="contact" type="text" id="contact" value="<?php echo "$contact"; ?>" /><br>
<label>Qualification :</label>
<select class="txtbox" name = "qualific">
<option value="<?php echo "$qualific"; ?>"><?php echo "$qualific"; ?></option>
<option value="Below SSC(10 Std)">Below SSC(10 Std)</option>
<option value="SSC(10 Std) passed">SSC(10 Std) passed</option>
<option value="HSC(12 Std) passed">HSC(12 Std) passed</option>
<option value="Graduate">Graduate</option>
<option value="Post Graduate">Post Graduate</option>
</select>
<input class="submitbtn" name="Submit" type="submit" value="Save" />
</form>

just using Multi Conditional IF
if($_POST['fullname'] == '')
{
//value
}
elseif($_POST['qualific'] == '')
{
//value
}
and so on ...
If you want to check the data is changing or not you can use session to hold data from database and campare with data from the form.
while($row = mysql_fetch_array($sql)){
$fullname = $row["fullname"];
// Place Session variable 'fullname'
$fullname = $_SESSION[$fullname];
$contact = $row["contact"];
// Place Session variable 'contact'
$contact = $_SESSION[$contact];
$qualific = $row["qualification"];
// Place Session variable 'qualification'
$qualific = $_SESSION[$qualific];
}
And Compare it :
if($_SESSION['fullname'] !== $_POST['fullname'])
{
// do something
} elseif($_SESSION['fullname'] !== $_POST['fullname']) {
// do something
}
and so on...
btw, sorry for my english

Related

How to give a value to a checkbox if it is not selected - php

In my form I have two checkboxes
-role
-commercial
I implemented an if loop that sees that the checkbox called role must be used
the second "commercial" checkbox is optional but how can I pass the "N" value when it is not selected?
Because in the current state in the db the commercial field, if its checkbox is not selected and I send the form, it gives me a null result
code:
<?php
session_start();
if(isset($_SESSION['USER_ID']))
{
if ($_SESSION['RUOLO'] == 'N' )
{
if (isset($_POST['submit']))
{
include 'FILE_DI_CONNESSIONE.php';
$id = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['id']);
$role = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['role']);
$commerciali = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['commerciali']);
$query = mysqli_query($VARIABILE_FILE_DI_CONNESSIONE, "UPDATE tabella SET role='$role', commerciali='$commerciali' WHERE id = ".$_SESSION['USER_ID']);
if( $query )
{
if(isset($_POST['role']))
{
$role = ($_POST['role']);
echo "ok";
}
else
{
echo "errore";
}
}
}
}
}
?>
<form method="post" action="n.php">
<input class="form-control" name="id" value="<?php echo $_SESSION['USER_ID']; ?>"><br>
<label>Privacy</label>
<input class="form-control" type="checkbox" value="S" required name="role" placeholder="<?php echo $_SESSION['RUOLO']; ?>"><br>
<label>Termini e Condizioni</label>
<input class="form-control" type="checkbox" value="S" name="commerciali" placeholder="<?php echo $_SESSION['RUOLO']; ?>"><br>
<input class="btn btn-primary" name="submit" type="submit" value="Register..."><br>
</form>
maybe this is what you are looking for?
if(array_key_exists('submit', $_POST) {
if(isset($_SESSION['USER_ID'] && $_SESSION['RUOLO'] == 'N') {
include 'FILE_DI_CONNESSIONE.php';
$id = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['id']);
$role = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['role']);
if(!isset($_POST['commerciali'])) {
$commerciali = "N";
} else {
$commerciali = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['commerciali']);
}
$query = "UPDATE `tabella` SET `role`='$role', `commerciali`='$commerciali' WHERE `id` = $id";
$result = mysqli_query($VARIABILE_FILE_DI_CONNESSIONE, $query);
if($result && isset($_POST['role'])) {
$role = ($_POST['role']);
echo "ok";
} else {
echo "error";
}
}
the if(array_key_exists('submit',$_POST) { helps check that unless the form's submit button is clicked and sent with the form's post array.. nothing should run.. personally find more secure cause of bots that are capable of submitting forms with their own data.. also takes care of the if statement for submit check.
And answering your question is the if(!isset($_POST['commerciali'])) {part.
I hope this helps!

Post New Checkbox values to db after edited

I have a edit form that has some checkboxes on it and I am having trouble getting the new checkbox values posted back to the db after it has been changed. So far the form will load in the current values in the db but after you click different check boxes it wont update the change in the db. Any help would be appreciated.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>"/><br/>
<strong>Contact Name: *</strong> <input type="text" name="contactname" value="<?php echo $contactname; ?>"/><br/>
<strong>Phone Number: *</strong> <input type="text" name="phone" value="<?php echo $phone; ?>"/><br/>
<strong>Type: *</strong>
<select name="type">
<option value="">Select...</option>
<option value="Inpatient Hospital" <?php if($type=="Inpatient Hospital")echo "selected=\"selected\""; ?>>Inpatient Hospital</option>
<option value="Residential Facility"<?php if($type=="Residential Facility")echo "selected=\"selected\""; ?>>Residential Facility</option>
<option value="Behavioral Treatment Facility"<?php if($type=="Behavioral Treatment Facility")echo "selected=\"selected\""; ?>>Behavioral Treatment Facility</option>
<option value="Therapeutic Group Home"<?php if($type=="Therapeutic Group Home")echo "selected=\"selected\""; ?>>Therapeutic Group Home</option>
<option value="Drug or Addictions Rehab"<?php if($type=="Drug or Addictions Rehab")echo "selected=\"selected\""; ?>>Drug or Addictions Rehab</option>
</select><br/>
<input type="radio" name="sex" value="Male" <?php echo ($sex=="Male")?'checked="checked"':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=="Female")?'checked="checked"':'' ?> size="17">Female
<input type="radio" name="sex" value="Both" <?php echo ($sex=="Both")?'checked="checked"':'' ?> size="17">Both<br/>
<strong>Markers: *</strong> <input type="text" name="markers" value="<?php echo $markers; ?>"/><br/>
<?php
// Create connection
$con=mysqli_connect("localhost","un","pw","childcare");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT FMarkers FROM faci WHERE ID='$id'");
while($row = mysqli_fetch_array($result))
{
$focus=explode(",",$row['FMarkers']);
?>
Autism<input type="checkbox" name="FMarkers[]" value="Autism" <?php if(in_array("Autism",$focus)) { ?> checked="checked" <?php } ?> >
Attachement Disorder<input type="checkbox" name="FMarkers[]" value="Attachement Disorder" <?php if(in_array("Attachement Disorder",$focus)) { ?> checked="checked" <?php } ?> >
Dissociative Disorder<input type="checkbox" name="FMarkers[]" value="Dissociative Disorder" <?php if(in_array("Dissociative Disorder",$focus)) { ?> checked="checked" <?php } ?> >
ODD<input type="checkbox" name="FMarkers[]" value="ODD" <?php if(in_array("ODD",$focus)) { ?> checked="checked" <?php } ?> >
ADHD<input type="checkbox" name="FMarkers[]" value="ADHD" <?php if(in_array("ADHD",$focus)) { ?> checked="checked" <?php } ?> >
<?php
//print_r(array_values($focus));
//echo("<pre>\n");
//print_r($_POST);
//echo("</pre>\n");
//var_dump($dog);
//these below are different ways I have tried to get it to work
//$markers = implode(',', $_POST['dog']);
//$markers=$_POST['focus'];
//$markers = implode(",",$markers);
//$markers = implode(",",$_POST['focus']);
//$check = isset($_POST['focus']) ? $_POST['focus'] : '';
//$markers = is_array($check) ? implode(", ", $check) : '';
//echo $markers;
?>
<?php
}
?>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$contactname = mysql_real_escape_string(htmlspecialchars($_POST['contactname']));
$phone = mysql_real_escape_string(htmlspecialchars($_POST['phone']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$sex = mysql_real_escape_string(htmlspecialchars($_POST['sex']));
$markers = mysql_real_escape_string(htmlspecialchars($_POST['markers']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $contactname == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE faci SET FName='$firstname', FContact='$contactname', FPhone='$phone', FType='$type', FSex='$sex', FMarkers='$markers' WHERE ID='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: facility-view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM faci WHERE ID=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$firstname = $row['FName'];
$contactname = $row['FContact'];
$phone = $row['FPhone'];
$type = $row['FType'];
$sex = $row['FSex'];
$markers = $row['FMarkers'];
// show form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>

How to create a selection dropdown in php form

I am working on a project and would like to give the user per-determined values when updating a record.
Here is my code so far.
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$Name = mysql_real_escape_string(htmlspecialchars($_POST['Name']));
$Status = mysql_real_escape_string(htmlspecialchars($_POST['Status']));
$Comments = mysql_real_escape_string(htmlspecialchars($_POST['Comments']));
$Type = mysql_real_escape_string(htmlspecialchars($_POST['Type']));
// check that firstname/lastname fields are both filled in
if ($Name == '' || $Type == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $Name, $Status, $Comments, $Type, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE Schools SET Name='$Name', Status='$Status', Comments='$Comments', Type='$Type' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM Schools WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$Name = $row['Name'];
$Status = $row['Status'];
$Comments = $row['Comments'];
$Type = $row['Type'];
// show form
renderForm($id, $Name, $Status, $Comments, $Type, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
I am wanting to replace the status text filed with a drop down list of options.
Replace your <input by <select :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<option value="1">Status 1</option>
<option value="2">Status 2</option>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
If your statuses are in a table, fill the <select> with a query :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<?php
$result = mysql_query("SELECT * FROM tbl_status",$cnx);
while ( $row = mysql_fetch_array($result) )
echo "<option value='" . $row["id"] . "'>" . $row["text"] . "</option>";
?>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
You could use the html <datalist> or the <select> tag.
I hope I could help.
First of all you need to switch from mysql_* to mysqli_* as it going to get removed in php 7.0 I'm using this function i created and it might help you
here is the php code
function GetOptions($request)
{
global $con;
$sql = "SELECT * FROM data GROUP BY $request ORDER BY $request";
$sql_result = mysqli_query($con, $sql) or die('request "Could not execute SQL query" ' . $sql);
while ($row = mysqli_fetch_assoc($sql_result)) {
echo "<option value='" . $row["$request"] . "'" . ($row["$request"] == $_REQUEST["$request"] ? " selected" : "") . ">" . $row["$request"] . "$x</option>";
}
}
and the html code goes like
<label>genre</label>
<select name="genre">
<option value="all">all</option>
<?php
GetOptions("genre");
?>
</select>

Code sees error, sends error message, but submits form data into session cart

The code between the asterisk lines checks for an empty field, and displays an error message above the form field.
Similar code that checks if an ID already exists in the cart is just below it. The difference between the two is that the code in question does not function as intended. It interprets an error, it sees an empty field was submitted, and triggers its error message.
The problem is that it also submits the empty string into the cart. I cannot figure out why.
I included all the code, if anyone wanted to test it. I hope someone sees what I cannot see. Thank you.
<?php
session_start();
// If no cart exists, create $_SESSION['cart'] array
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
// Add item to array
if(isset($_POST['action']) && $_POST['action'] === 'add'){
/***************************************************/
// Check if input is empty / null
if(empty($_POST['id'])){
$error = '*Please enter an ID number.';
}
/***************************************************/
// Check if form data exists
if(isset($_POST['id'])){
$id = $_POST['id'];
}
// Check if ID already in cart
if(isset($_SESSION['cart'][$id])){
$error = '*Item already in cart.';
}
// Add new ID to array (hard-code some data for test file)
$newitem = array(
'id' => $id,
'part_number' => '369A7170-11',
'quantity' => '1'
);
// Add new data to cart with ID as key
$_SESSION['cart'][$id] = $newitem;
}
// Add item to array
if(isset($_POST['action']) && $_POST['action'] === 'update'){
// Check if input is empty / null
if(empty($_POST['id'])){
$error = '*Please select item and quantity.';
include 'error.html.php';
exit();
}
// Check if form data exists
if(isset($_POST['id']) && isset($_POST['quantity'])){
$id = $_POST['id'];
$quantity = (int)$_POST['quantity'];
}
$_SESSION['cart'][$id]['quantity'] = $quantity;
}
// Remove item from array
if(isset($_POST['action']) && $_POST['action'] === 'remove'){
// Check if form data exists
if(isset($_POST['id'])){
$id = $_POST['id'];
}
unset($_SESSION['cart'][$id]);
}
// Empty cart
if(isset($_POST['action']) && $_POST['action'] === 'empty'){
unset($_SESSION['cart']);
}
// Initialize $count variable; get item count
$count = '';
if(isset($_SESSION['cart'])) $count = count($_SESSION['cart']);
// Display results
if(isset($_SESSION['cart'])){
$show_cart = var_dump($_SESSION['cart']);
echo $show_cart;
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cart</title>
</head>
<body>
<h3>Cart Management</h3>
<p style="color:#ff0000;"><?php if(isset($error)) echo htmlentities($error, ENT_QUOTES); ?></p>
<p>Items in cart: <?php if(isset($count) && $count > 0)echo htmlentities($count, ENT_QUOTES); else echo 'none'; ?></p>
<form action="" method="post">
<label for="id"> </label>
<input type="text" name="id" id="id" placeholder="Enter ID number" autofocus>
<input type="hidden" name="action" value="add">
<input type="submit" value="Add">
</form>
<form action="" method="post">
<label for="id"> </label>
<select name="id" id="id">
<option value="">Select ID</option>
<?php foreach($_SESSION['cart'] as $key => $item): ?>
<option value="<?php echo htmlentities($item['id'], ENT_QUOTES); ?>"><?php echo htmlentities($item['id'], ENT_QUOTES); ?></option>
<?php endforeach; ?>
</select>
<input type="hidden" name="action" value="remove">
<input type="submit" value="Remove">
</form>
<form action="" method="post">
<label for="id"> </label>
<select name="id" id="id">
<option value="">Select ID</option>
<?php foreach($_SESSION['cart'] as $key => $item): ?>
<option value="<?php echo htmlentities($item['id'], ENT_QUOTES); ?>"><?php echo htmlentities($item['id'], ENT_QUOTES); ?></option>
<?php endforeach; ?>
</select><br>
<label for="quantity"> </label>
<input type="text" name="quantity" id="quantity" size="2">
<input type="hidden" name="action" value="update">
<input type="submit" value="Update quantity">
</form>
<form action="" method="post">
<input type="hidden" name="action" value="empty">
<input onclick="return confirm('Are you sure you want to empty the cart?');" type="submit" value="Empty cart">
</form>
</body>
</html>
In certain scenarios, you're adding an item with a key of NULL. Here is the fix:
// Check if form data exists
if(isset($_POST['id'])){
$id = $_POST['id'];
} else {
$id = null;
}
if ($id)
{
// Check if ID already in cart
if(isset($_SESSION['cart'][$id])){
$error = '*Item already in cart.';
} else {
// Add new ID to array (hard-code some data for test file)
$newitem = array(
'id' => $id,
'part_number' => '369A7170-11',
'quantity' => '1'
);
// Add new data to cart with ID as key
$_SESSION['cart'][$id] = $newitem;
}
}
The idea is that we do not want to add any entries to the cart if the id is empty. Also, just to be safe, lets not redefine and add $newitem if it is already there.
So you set $error, and print it and nothing else. And this line (that I think this is the line that adds it to the cart) will be executed anyway:
$_SESSION['cart'][$id] = $newitem;
You have to check the error before doing that. For example:
if(!isset($error))
$_SESSION['cart'][$id] = $newitem;

change dropdown from array to check box

I would like a change from the drop down to the checkbox, I want to change it because I want firstly select the list in the array can be selected before store to database via the checkbox, so the dropdown script was as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1">
<select name="from">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<option value="<?php echo $key; ?>" selected="selected"><?php echo $stock; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $stock; ?></option>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Convert">
</form>
and i Changed it to the checkbox as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1"><input type="submit" name="submit" value="Convert">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>" checked="checked"><?php echo $stock; ?>
<?php
}
else
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>"><?php echo $stock; ?>
<?php
}
}
?>
</form>
but does not work, am I need to display Other codes related?
Thanks if some one help, and appreciated it
UPDATED:
ok post the first apparently less obvious, so I will add the problem of error
the error is
Fatal error: Call to undefined method st_exchange_conv::convert() in C:\xampp\htdocs\test\do.php on line 21
line 21 is $st->convert($from,$key,$date);
session_start();
if(isset($_POST['submit']))
{
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
Why I want to change it from dropdown to checkbox?
because with via checkbox list I will be able to choose which ones I checked it was the entrance to the database, then it seem not simple to me, I looking for some help< thanks So much For You mate.
You have not removed the opening <select> tag.
But you removed the <submit> button.
You changed the name from "from" to "from[]".
EDIT: After your additions:
Using the dropdown list you were only able to select one value for from. Now you changed it to checkboxes and thus are able to select multiple entries. This results in receiving an array from[] in your script in do.php. Your functions there are not able to handle arrays or multiple selections in any way.
You have to re-design do.php, change your form back to a dropdown list or use ratio buttons instead.

Categories