How to update database in php? - php

I wanna update my product when there's user login. Here's my code in edit.php
<?php
$id= (int)$_GET['id'];
$query = "SELECT * FROM game WHERE gameId=".$id."";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs))
{
?>
<form action="doUpdate.php" method="post">
<?php echo "<image src=\"images/".$id.".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <input type="text" value="<?php echo $data['gameName'];?>" name="gameName"/></div>
<div class="myLabel">Developer</div><div>: <input type="text" value="<?php echo $data['gameDeveloper'];?>" name="gameDeveloper"/></div>
<div class="myLabel">Price</div><div>: <input type="text" value="<?php echo $data['gamePrice'];?>" name="gamePrice"/></div>
<br/>
<div id="txtError" style="color:#D70005">
<?php
if(isset($err))
{
if($err==1) echo"All Fields must be filled";
else if($err==2) echo"Price must be numeric";
else if($err==3) echo"Price must be between 1-10";
}
?>
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/></span>
<?php
}
?>
</form>
This is my code in doUpdate.php
<?php
$nama = $_POST['gameName'];
$dev = $_POST['gameDeveloper'];
$harga =$_POST['gamePrice'];
$id= (int)$_REQUEST['id'];
if($nama == "" || $dev == "" || $harga == "" )
{
header("location:edit.php?err=1");
}
else if(!is_numeric($harga))
{
header("location:edit.php?err=2");
}
else if($harga < 1 || $harga >10)
{
header("location:edit.php?err=3");
}
else
{
$query = "UPDATE game SET gameName='".$nama."', gameDeveloper='".$dev."', gamePrice=".$harga." where gameId=".$id."";
mysql_query($query);
header("location:product.php");
}
?>
Why I can't change name, developer, or price even I already give the action in form? And why if I delete the name, developer, and price to know wether the validation works or not, it said that Undefined index in edit.php $id= (int)$_GET['id']; ?

You are trying to get $_REQUEST['id'] in doUpdate.php but there is no such field in the form.
You have to add it as a hidden field.
Also you have to format your strings.
Every string you're gonna put into query you have to escape special characters in.

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!

Is my statement not updating because of the way I have it layed out?

This "page" is part of many that are all linked together using includes, but because I can't make it work I'm going straight to the url that relates to this exact page, and I still can't make it work, or figure out why.
What is supposed to happen, is the query checks if that stock is in the db, if it is, echo the values of the row, and if a submit button is pressed update the db based on the input values. If it's not in, echo the blank form, and if a submit button gets pressed insert into the db. I can't get either update or insert to work.
I'm going to post the entire page (minus the mysql connect,) so hopefully someone can spot an error.
<?php
$status = 'Active';
$stock = (isset($_GET['stock'])) ? $_GET['stock'] : '';
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : '';
include ('../helper_content/title_data.php');
/* WHAT CATEGORY DO WE WANT? */
if($cat == "Sales") {
$table = "Titles";
if($stock) {$where = "stock = $stock";}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$status = $status;
$title_status = mysqli_real_escape_string($conn,$_POST['title_status']);
$title_number = mysqli_real_escape_string($conn,$_POST['title_number']);
$title_location = mysqli_real_escape_string($conn,$_POST['title_location']);
$title_owners = mysqli_real_escape_string($conn,$_POST['title_owners']);
$stock = $_GET['stock'];
}
}
/* Begin Main Query */
$sql5 = "SELECT * FROM `$table` WHERE $where";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// Stock exists, so submit will Update dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($update = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$update->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$update->execute();
};
if ($update->execute == TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating: " . $update->error;
}
}
// Display the HTML results
while($row5 = $result5->fetch_assoc()) {
echo "Found In Database";
// Title Number
$title_number = 'value="'.$row5['title_number'].'"';
$TitleStatus = $row5['title_status'];
$TitleLocation = $row5['title_location'];
$Owners = $row5['owners'];
}
} else {
// No Query Results Found
echo "Not Found In Database";
// Insert into dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($add = $conn->prepare("INSERT INTO `Titles` status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$add->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$add->execute();
};
if ($add->execute == TRUE) {
echo "Record added into database";
} else {
echo "Error adding: " . $add->error;
}
}
/* End Main Query */
}
// Title Status
foreach($title_statuses as $title_status){
$selected = ($TitleStatus == $title_status) ? ' selected="selected"' : '';
$Title_status .= '<option value="'.$title_status.'"'.$selected.'>'.$title_status.'</option>';
}
// Title Location
foreach($title_locations as $title_location){
$selected = ($TitleLocation == $title_location) ? ' selected="selected"' : '';
$Title_location .= '<option value="'.$title_location.'"'.$selected.'>'.$title_location.'</option>';
}
// Prior Owners
foreach($prior_owners as $owners){
$selected = ($Owners == $owners) ? ' selected="selected"' : '';
$Owners_drop .= '<option value="'.$owners.'"'.$selected.'>'.$owners.'</option>';
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>?stock=<?php echo $stock; ?>">
<section class="title">
<h3>Title Info - Stock #:<?php echo $stock; ?></h3>
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" <?php echo $title_number; ?>>
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php echo $Title_status; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<?php echo $Title_location; ?>
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<?php echo $Owners_drop; ?>
</select> <a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=<?php echo $vin; ?>"><i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i></a>
</p>
</section>
<input type="submit" id="Submit" value="Submit">
</form>
I would start by organizing your code a little differently. You have one of two things that can be true: either the form was submitted (a POST request), or the page was requested via URL (a GET request). So, start with this:
<?php
# Data for dropdowns
include ('../helper_content/title_data.php');
$error = array();
$status = "Active";
$title_number = "";
$title_status = "";
$title_location = "";
$title_owners = "";
$vin = "";
# Was the form submitted via POST?
if(isset($_POST['Submit']))
{
# Yes
# Is this a new stock item?
if(empty($_POST['stock']))
{
# Yes - insert
/*
... get your variables from the $_POST array
*/
$title_number = filter_var($_POST['title_number'], FILTER_SANITIZE_STRING);
# ... repeat for other variables
if ($stmt = $conn->prepare("INSERT INTO `Titles` (`status`,`title_status`,`title_number`,`title_location`,`title_owners`) VALUES (?,?,?,?,?)"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?inserted=true');
exit();
}
else
{
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
}
else
{
# No - update
$stock = $_POST['stock'];
/*
... get your variables from the $_POST array
*/
if ($stmt = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else
{
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated']))
{
$message = "Record updated";
}
else if(isset($_GET['inserted']))
{
$message = "Record added into database";
}
if($stock != "")
{
# Load the item?
$query = "SELECT * FROM `Sales` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $stock);
if($stmt->execute())
{
$result = $stmt->get_result();
if($result)
{
$row = $result->fetch_assoc();
$title_number = $row['title_number'];
$title_status = $row['title_status'];
$title_location = $row['title_location'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<section class="title">
<h3>Title Info - Stock #:<?= $stock; ?></h3>
<input type="hidden" name="stock" value="<?= $stock; ?>" />
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" value="<?= $title_number; ?>" />
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php foreach($title_statuses as $option): ?>
<option <?= $option == $title_status) ? 'selected="selected"' : '' ?>><?= $option ?></li>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
<a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=$vin">
<i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i>
</a>
</p>
</section>
<input type="submit" id="Submit" value="Submit" />
</form>
Here's a partial re-implementation of your page. I'm starting with the assumption that a stock number was part of the requesting URL, and looking that value up. I (for the moment) am ignoring loading the dropdown values in favor of getting a basic lookup to work.
You'll also notice I've switched to using shorttags in your markup - this is generally a more concise method of templating than sprinkling echos all over the place.
I've added a partial implementation of some save logic. You'll also notice that I added a hidden input to your form - you don't want to rely on a query string value when posting a form.
The code stores some simple error messages in an array, which gets echoed out if the insert or update fails. If successful, we redirect back to the same page with a simple flag variable, which we read on that request to know if we need to display an informational message. This is known as POST-REDIRECT-GET, and prevents users from accidentally (or purposefully) resubmitting the same form data over and over.

How to run SQL query on click using conditional PHP?

I am trying to create a room availability check page for a hostel and I am having an issue.
I have a database with a table named 'rooms' listing all type of rooms with these rows:
id [INT]
name (room type) [CHAR]
capacity (max capacity, not to be changed)[INT]
used (number of beds used, I want to change this dynamically!) [INT]
I created a code to generate the rooms list from the DB with PHP and I want the "+" and "-" buttons to either add or remove one unit in the used column for a specific room. How can I do this?
Here is my code:
<!-- SOME HTML/PHP THAT WORKS -->
<?php if ($roomlist->num_rows > 0) {
// output data of each row
while($room = $roomlist->fetch_assoc()) {
$roomid = $room["id"]; ?>
<div>
<!-- SOME OTHER HTML/PHP THAT WORKS -->
// THE ISSUE IS BELOW, IT SHOWS THE CORRECT AMOUNT BUT $room["used"] DOES NOT UPDATE
<div>
Used: <?php echo $room["used"] . " / " . $room["capacity"] ?>
</div>
<div>
<form action="" method="POST">
<input type="submit" name="remove" value="-" />
<input type="submit" name="add" value="+" />
<?php
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
?>
</form>
</div>
</div>
</div>
<?php }
} else {
echo "0 results";
} ?>
If you set the action of your form to whatever the name of your code is (e.g., "rooms.php"), then move
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
up to the top so it updates the table before you query the table to fill in the rest of the page, it should work. Right now, your php is updating the table after the SELECT query to populate your page, so it doesn't appear to be updating.
I think a better tack would be implementing AJAX so your form updates the Used field without reloading the page.
Alright so I figured out a way on my own in the end so I post it here for other people facing a similar issue to overcome it ;)
Here is the concerned part of the code in index.php:
<form action="update.php?id=<?php echo $roomid ?>&action=remove&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="remove" class="minus" value="-" />
</form>
<form action="update.php?id=<?php echo $roomid ?>&action=add&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="add" class="plus" value="+" />
</form>
And the code of update.php:
if (isset($_REQUEST['used']) && isset($_REQUEST['id']) && isset($_REQUEST['capacity'])) {
$roomid = $_REQUEST['id'];
$used = $_REQUEST['used'];
$capacity = $_REQUEST['capacity'];
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
if ($used >= $capacity) {
header("location: index.php");
} else {
$newValue = $used + 1;
$add_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'remove') {
if ($used <= 0) {
header("location: index.php");
} else {
$newValue = $used - 1;
$remove_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
}
}

edit_subject.php is not working, the error is saying about database query failed

This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.

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