I am building a database of different devices which is displayed in a page which sells medical devices. When a user adds a quantity of the device to the cart, I want the database to be updated with (stock - quantity in cart) I am trying to do this on PHP but am having no luck. My attempt and code is below.
Here is a snippet of my attempt. I'm not sure where to place this in the code below.
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
$query = "UPDATE products SET stock= (stock-$product_qty) WHERE product_name=$product_name";
mysql_select_db('products');
$retval = mysql_query($query,$mysqli);
}
?>
This is code for index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Products </h1>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price, stock FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color">
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" id="updateb" class="add_to_cart">Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
</body>
</html>
This is code for cart_update.php
<?php
session_start();
include_once("config.php");
//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
//we need to get product name and price from database.
$statement = $mysqli->prepare("SELECT product_name, price, stock FROM products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $price, $stock);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $price;
$new_product["product_stock"] = $stock;
if(isset($_SESSION["cart_products"])){ //if session var already exist
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
}
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
//update item quantity in product session
if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
foreach($_POST["product_qty"] as $key => $value){
if(is_numeric($value)){
$_SESSION["cart_products"][$key]["product_qty"] = $value; //change
}
}
}
//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);
?>
This is code for view_cart.php
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$currency.$product_price.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>
</body>
</html>
your variables $product_qty and $product_name are not defined and in the query pass the product name in the quotes as your query is in double quotes so pass name in the single quotes.
Also it will be better if you update using primary id not by name.
Related
I have created a shopping cart script in order to add or delete products using PHP and MySQL.
The script works as expected, but it is not very comfortable. I am trying to use it with ajax calls.
1. I add the selected product in the shopping cart
$('#add-product').on('click',function() {
$.ajax({
var product_id = $(this).data('id'); //Product id
url: 'cart.php',
data:{add:product_id },
type:'GET',
success: function(data) {
if(!data.error){
$('#show-cart').html(data);
}
}
});
});
2. cart.php
<?php
require_once('resource/init.php');
//ADD A PRODUCT IN THE SHOPPING CART
if(isset($_GET['add'])) {
$query = query("SELECT * FROM products WHERE id = ".escape_string($_GET['add']));
confirm($query);
while ($row = fetch_array($query)) {
if($row['quantity'] != $_SESSION['product_'.$_GET['add']]){
$_SESSION['product_'.$_GET['add']] +=1;
}
}
}
//DELETE PRODUCT FROM SHOPPING CART
if(isset($_GET['delete'])) {
$_SESSION['product_'.$_GET['delete']] = '0';
unset($_SESSION['total']);
unset($_SESSION['quantity']);
}
$total = 0;
$item_quantity = 0;
$item_name = 1;
$item_number = 1;
$amount = 1;
$quantity = 1;
foreach ($_SESSION as $name => $value) {
if(substr($name, 0,8) == 'product_' && $value > 0){
$lenght =strlen($name);
$id = substr($name, 8, $lenght);
$query = query("SELECT * FROM products WHERE id = ".escape_string($id)." ");
confirm($query);
while($row = fetch_array($query)) {
$sub_price = pr_get_sub_price($row['price'],$row['discount'],$row['id'],$value,$lang);
$item_quantity += $value;
$product_image = 'images/products/'.$row['image'];
$price = show_product_price($row['price'],$row['discount'],$lang);
$discounted_price = get_product_price_by_discount($row['price'],$row['discount'],$row['id'],$lang);
?>
<!--THIS IS THE SHOPPING CART-->
<table>
<tr style="text-align:left">
<td><img src="<?php echo $product_image;?>" alt="cart-hover" style="float:left;width: 58px; margin-right:14px;"/></td>
<td><a title="<?php echo $row['title'];?>" href="#" style="margin-right:10px;"><span class="cart-title"><?php echo $row['title'];?> (<?php echo $value;?>)</span></a></td>
<td><span style="font-size: 90%; margin-right: 8px; position:relative;top:2px;"><?php echo $price;?> <?php echo $discounted_price;?></span></td>
<!--DELETE BUTTON-->
<td>
<button data-id = "<?php echo $row['id'];?>" class="delete-product"> <i class="fa fa-close"></i> Delete</button></td>
</tr>
</table>
<input type="hidden" name="item_name_<?php echo $item_name;?>" value="<?php echo $row['title'];?>">
<input type="hidden" name="item_number_<?php echo $item_number;?>" value="<?php echo $row['id'];?>">
<input type="hidden" name="amount_<?php echo $amount;?>" value="<?php echo $row['price'];?>">
<input type="hidden" name="quantity_<?php echo $quantity;?>" value="<?php echo $value;?>">
<?php
$item_name++;
$item_number++;
$amount++;
$quantity++;
$_SESSION['total'] = $total += $sub_price;
$_SESSION['quantity'] = $item_quantity;
}
}
}
?>
<!--DELETE PRODUCT-->
<script>
$('.delete-product').click(function() {
var product_id = $(this).data('id');//PRODUCT ID
$.ajax({
url: 'cart.php?delete=' + product_id,
type: 'get',
success:function(data){
$('#show-cart').html(data);
}
});
});
</script>
The scripts above work as expected, but not for the DELETE action.
If I have, for istance, a product in the shopping cart:
Product one (3) $250.00
and I click on the DELETE icon, the selected product continues to be shown in the shopping cart as it was in the beginning before clicking on the DELETE icon: Product one (3) $250.00
If I try to add the same product in the cart, then it will be displayed starting with the value 1: Product one (1) $250.00
This is the first time that I work using PHP/MySQL with Ajax and I do not know how to solve this issue.
Im trying to create a shopping cart style website. I'm able to display the products through setting the products as a class and passing that through to my shopping cart page. However, I need to save the list of products into a session so I can add and or clear each item added to the cart.
Products.php
<?php
require_once 'class_product.php';
$product = new product();
$product_id =(int)$_GET['product_id']; //get id from home page
$username = "";
$password = "";
$hostname = "";//blanked this out for public use
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");
echo '<form name="form1" method="post" action="cart.php" target="bottom_right">';
echo '<table class="Grocery-table">';
while($row = mysql_fetch_array($result))
{
$product->setProductId($row['product_id']);
$product->setProductName($row['product_name']);
$product->setStock($row['in_stock']);
$product->setUnitPrice($row['unit_price']);
$product->setUnitQuantity($row['unit_quantity']);
}
$_SESSION['product'] = serialize($product);
echo "<tr><td><b>Product ID</b></td>";
echo "<td>";
echo $product->getProductId();
echo "</td></tr>";
echo "<tr><td><b>Product Name</b></td>";
echo "<td>";
echo $product->getProductName();
echo "</td></tr>";
echo "<tr><td><b>Unit Price</b></td>";
echo "<td>";
echo $product->getUnitPrice();
echo "</td></tr>";
echo "<tr><td><b>Unit Quantity</b></td>";
echo "<td>";
echo $product->getUnitQuantity();
echo "</td></tr>";
echo "<tr><td><b>In Stock</b></td>";
echo "<td>";
echo $product->getStock();
echo "</td></tr>";
echo '<tr><td><b>Add</b></td><td><Input type="number" min="0" id="add_value" name="cart"></input>
<Input type="hidden" id="stock_value" name="stock_value" value ='.trim($product->getStock()).'></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
echo "</table>";
echo "</form>";
?>
cart.php
<?php
session_start();
?>
<html>
<style type="text/css">
</style>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Grocery Store</title>
</head>
<body>
<h2>Cart</h2>
<?php
require_once 'class_product.php';
$product = unserialize($_SESSION['product']);
//this allows me to see the information when i click submit
echo $product->getProductName();
echo $product->getProductId();
echo $product->getStock();
echo $product->getUnitPrice();
echo $_POST['cart'];
?>
</body>
</html>
How do i place the following $product->getProductName() etc into a Session that enables me to display all the products i've added to my cart.
Try this,
session_start();
$_SESSION['ProductName'] = $product->getProductName();
$_SESSION['ProductId'] = $product->getProductId();
$_SESSION['Stock'] = $product->getStock();
$_SESSION['UnitPrice'] = $product->getUnitPrice();
For multiple products, you may have to use an array of session.
<?php
session_start();
if(!isSet($_SESSION['cart_items']))
{
$_SESSION['cart_items'] = array();
}
$items =$product->getProductName()."|".$product->getProductId()."|".$product-
>getStock()."|".$product->getUnitPrice();
array_push($_SESSION['cart_items'],$items);
echo $_SESSION['cart_items'][0]; //First Product
echo "<br>";
echo $_SESSION['cart_items'][1]; //Second Product
?>
I am trying to input a value (Rating) from the database when an item is selected. I need to also be able to update that rating and then put that value into another table.
My problem is that I'm trying to figure out how to make the value in the text box be related to the selection made in the drop down. I've found coding to make another option box but cannot figure out how to make that a text box.
REWORDING: Originally when I posted the question I thought it was possible to do this without JQuery and was trying to copy the for loop and run a while loop to populate the text box. I now know that isn't possible and would like to figure out how to run a script to populate a text box on change for the drop down box. The problem being the function has to be connected to the database as well as the drop down.
1. pull the data for the drop down (from the JOURNAL table). 2. Select a journal from that drop down 3. Inside the JOURNAL table a JournalRating has been assigned to every journal pull that value and place inside a textbox.
What I've tried to do is
<?php
include 'dbc.php';
connect();
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
<script>
(function($){
$(function(){
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('Rating'));
});
});
})(jQuery);
</script>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyID">Faculty Name</label>
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear"/>
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $stmt->insert_id;
$facmemid = 0;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}
mysqli_close($conn);
?>
</body>
</html>
Add the rating to your HTML using a data attribute:
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
Then you can access this using jQuery .data():
(function($) {
$(function() {
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('rating'));
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="JournalID">
<option>Select a journal</option>
<option value="1" data-rating="3">Journal #1</option>
<option value="2" data-rating="2">Journal #2</option>
<option value="3" data-rating="5">Journal #3</option>
</select>
<br>
Rating: <input id="JournalRating">
I'm trying to create a form for my system, user could add the numbers of input fields, the input fields are mostly drop down box with the options coming from tables in the database. The forms would insert the data into two different database. But it shows error of "Array to string conversion" Right now the data only inserted into the first table. Here's what I'd done so far
My form's code:
<form method="post" name="maklumat_akaun" action="proses_daftar_akaun.php">
<label for="NoAkaun">No. Akaun</label>
<input type="text" id="NoAkaun" name="NoAkaun" class="required input_field" required/>
<div class="cleaner_h10"></div>
<label for="KodDaerah">Daerah</label>
<?php
include('dbase.php');$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="KodBahagian">Bahagian</label>
<?php
$sql = "SELECT KodBahagian, NamaBahagian FROM kodbahagian";
$result = mysql_query($sql);
echo "<select name='KodBahagian' id='KodBahagian' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodBahagian'].">" .$kod['NamaBahagian']."</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="KodKategori">Kategori Akaun</label>
<?php
$sql = "SELECT KodKategori, NamaKategori , SubKategori FROM kodkategori";
$result = mysql_query($sql);
echo "<select name='KodKategori' id='KodKategori' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodKategori'].">" .$kod['NamaKategori']." (".$kod['SubKategori'].")</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="Tarif">Tarif</label>
<input type="text" maxlength="4" size="4" id="Tarif" name="Tarif" class="required year_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')">
<div class="cleaner_h10"></div>
<!-----------------------------------------------------------//-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>'+
'<td> <?php
$sql = "SELECT KodLokasi, NamaLokasi FROM kodlokasi";
$result = mysql_query($sql);
echo "<select name=\'KodLokasi[]\' id=\'KodLokasi[]\' class=\'input_field\' required ><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodLokasi'].">" .$kod['NamaLokasi']. "</OPTION>";
}
echo "</select>";
?> </td> </tr>'+
'<tr> <td> <?php
$sql = "SELECT KodJenisAkaun, NamaJenisAkaun FROM kodjenisakaun";
$result = mysql_query($sql);
echo "<select name=\'KodJenisAkaun[]\' id=\'KodJenisAkaun[]\' class=\'input_field\' required ><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodJenisAkaun'].">" .$kod['NamaJenisAkaun']. "</OPTION>";
}
echo "</select>";
?> </td>'+
'<td> <input type="text" name="NoTelefon[]" id="NoTelefon[]" value="0" class="required input_field"> </td>' +
'Batal</tr></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
});
});
</script>
<fieldset>
<div class="input_fields_wrap">
<h3 class="add_field_button">Add More Fields</h3>
<table>
<tr>
<td> <label for="KodLokasi">Lokasi</label> </td> <td> <label for="KodJenisAkaun">Jenis Akaun</label> </td> <td> <label>No.Telefon:</label> </td>
</tr>
<tr>
<td> <?php
$sql = "SELECT KodLokasi, NamaLokasi FROM kodlokasi";
$result = mysql_query($sql);
echo "<select name='KodLokasi[]' id='KodLokasi' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodLokasi'].">" .$kod['NamaLokasi']."</OPTION>";
}
echo "</select>";
?>
</td>
<td> <?php
$sql = "SELECT KodJenisAkaun, NamaJenisAkaun FROM kodjenisakaun";
$result = mysql_query($sql);
echo "<select name='KodJenisAkaun[]' id='KodJenisAkaun' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodJenisAkaun'].">" .$kod['NamaJenisAkaun']."</OPTION>";
}
echo "</select>";
?>
</td>
<td> <input type="text" name="no_telefon[]" value="0" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')"> </td>
</tr>
</table>
</div>
</fieldset>
<!-----------------------------------------------------------//-->
<div class="cleaner_h10"></div>
<div class="cleaner_h10"></div>
<input type="submit" value="Daftar" id="submit" name="register-submit" class="submit_btn" />
<input type="reset" value="Batal" id="reset" name="reset" class="submit_btn" />
</table>
</form>
While this is my code for the inserting process.
<?php
require("dbase.php");
if ($_POST) {
$NoAkaun = isset($_POST['NoAkaun']) ? $_POST['NoAkaun'] : '';
$KodBahagian = isset($_POST['KodBahagian']) ? $_POST['KodBahagian'] : '';
$Tarif = ISSET($_POST['Tarif']) ? $_POST['Tarif'] : '';
$KodDaerah = isset($_POST['KodDaerah']) ? $_POST['KodDaerah'] : '';
$KodKategori = isset($_POST['KodKategori']) ? $_POST['KodKategori'] : '';
$NoTelefon = isset($_POST['NoTelefon']) ? $_POST['NoTelefon'] : '';
$KodLokasi = isset($_POST['KodLokasi']) ? $_POST['KodLokasi'] : '';
$KodJenisAkaun = isset($_POST['KodJenisAkaun']) ? $_POST['KodJenisAkaun'] : '';
$akaun_idAkaun = isset($_POST['akaun_idAkaun']) ? $_POST['akaun_idAkaun'] : '';
$sql = mysql_query("INSERT INTO maklumatakaun VALUES ('', '$NoAkaun' , '$KodBahagian' , '$KodDaerah' , '$KodKategori' , '$Tarif' )");
$akaun_idAkaun = mysql_insert_id();
foreach ($NoTelefon AS $i => $telefon) {
$sql = mysql_query("INSERT INTO detailakaun VALUES ('', '$KodLokasi[$i]', '$KodJenisAkaun' , '$telefon' , '$akaun_idAkaun' )");
}
echo "<script type='text/javascript'> alert('AKAUN BERJAYA DIDAFTARKAN')</script> ";
echo "<script type='text/javascript'>window.location='pilih_kategori_daftar.php'</script>";
}
?>
Can anyone help me figure this out?
The error "Array to string conversion" means you are using an array as a string somewhere in your code. That error message is usually followed by a filename and line number which should help you narrow down your search. One helpful way to see what is contained within a variable is to use the following:
echo '<pre>'; print_r($stuff); die();
If the error is happening on a line inside of a while loop you should put the echo '' before the while and the die(); after so that you can see all instances of the problem within the loop.
I found your problem on this statement
$sql = mysql_query("INSERT INTO detailakaun VALUES ('', '$KodLokasi[$i]', '$KodJenisAkaun' , '$telefon' , '$akaun_idAkaun' )");
$KodJenisAkaun is an array and you use it as a string
I have a bunch locker numbers in a drop down list (populated from MYSQL/PHP). I want to display the locker's combination and location when you select a locker number from the list in two input fields below on the same page.
I have used jquery to tell me which item in the list is selected dynamically. Then I used the $.ajax() function to send that item to my server.
My problem: Can I use $.ajax() to send my variable to the same page I am on? I have tried this and I get an error. I am not sure how to accomplish this. My knowledge of AJAX is very minimal.
My code is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Locker Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="form.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function show()
{
$('#addlocker').toggle();
}
function lockerSelected(sel)
{
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(){
alert(selected);
}
});
}
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<?php
$url = $_SERVER['REQUEST_URI'];
$studID = substr($url, strpos($url, "=") + 1);
$db_handle = mysql_connect("localhost", "root", "pickles") or die("Error connecting to database: ".mysql_error());
mysql_select_db("lockers",$db_handle) or die(mysql_error());
$result = mysql_query("SELECT * FROM students WHERE studID = $studID");
?>
<div class="container">
<header> <img src="images/headmast.png" alt="Insert Logo Here" width="686" height="180" id="Insert_logo" /> </header>
<div id="data1">
<form id ="studData" name="studData" action="update.php" medthod="post">
<fieldset>
<legend>Student Details</legend>
<?php
while($row = mysql_fetch_array($result))
{
echo '<ol>';
echo '<li>';
echo '<label for=studid>Student ID</label>';
echo '<input id=studid name=studid type=text value='.$row['studID'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>First Name</label>';
echo '<input id=fname name=fname type=text value='.$row['firstName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>Last Name</label>';
echo '<input id=lname name=lname type=text value='.$row['lastName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=email>Email</label>';
echo '<input id=email name=email type=text value='.$row['email'].'>';
echo '</il>';
echo '<li>';
echo '<label for=progam>Program</label>';
echo '<input id=progam name=progam type=text value='.$row['program'].'>';
echo '</il>';
echo '</ol>';
$program = $row['program']; //get name of program
}
?>
<input type="submit" value="Update" class="fButton"/>
</fieldset>
</form>
<form id="locker" name="locker" action="" method="post" >
<fieldset>
<input type="button" onclick="show()" value="Add Locker"/>
<div id="addlocker" style="display:none;">
<!--
query lockers where $program = program parsed in & student id is equal to 0 (this makes it available)
get select list to 10
populate select list --> <br/>
<legend>Lockers Available: </legend>
<select size="10" name="lockerSelect" multiple="yes" style="width:200px;" onChange="lockerSelected(this);">
<?php
$result1=mysql_query("SELECT * FROM lockers WHERE progName = '$program' && studID = 0") or die($result1."<br/><br/>".mysql_error());
while($row1 = mysql_fetch_array($result1))
{
echo '<option value=\"'.$row1['lockerScan'].'">'.$row1['lockerNo'].'</option>';
}
echo '</select>';
echo '<br>';
$lockerNo = $_POST['selected']; \\doesn't work - displays error
echo $lockerNo; \\errors out
?>
</div><!--end of add locker section-->
</fieldset>
</form>
</div><!--end of data1 -->
Search
</div><!-- end of container-->
</body>
</html>
Firstly, you can use :
function show()
{
$('#addlocker').toggle();
}
Then, you should learn more about Ajax and PHP. Your call shoud be :
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: {selected: selected},
success: function(data){
alert(data);
}
});
And in your PHP file :
<?php
$select = $_POST['selected'];
//....
// Do what you have to do then return your result
echo '<div>Send to your page !</div>';
First Arrange your files.
js's is in js folder
php's in php folder
best way is to assaign a seperate php page and then in js use on change event
$(document).on("change", "#selectfieldid", function(){
var selected = $('#selectfieldid').val();
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(data){
$('#addlocker').val(data); //echoed result placed here that has id addlocker
}
});
});
send those to a php page echo the result in that php.