This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Why does this PDO statement silently fail?
(2 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
function e_type($connect) {
$output1 = '';
$query = "SELECT * FROM elimo_type ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output1 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output1;
}
function hw_type($connect) {
$output2 = '';
$query = "SELECT * FROM hw_version ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output2 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output2;
}
function sw_type($connect) {
$output3 = '';
$query = "SELECT * FROM sw_version ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output3 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output3;
}
?>
<?php
include 'header.php';
?>
<div class="container">
<h3 align="center">Purchase</h3>
<br />
<h4 align="center">Enter Purchase Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Serial No</th>
<th>Type</th>
<th>Hardware Version</th>
<th>Software Version</th>
<th>Key</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$(document).on('click', '.add', function () {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="serial_no[]" class="form-control serial_no" /></td>';
html += '<td><select name="e_type[]" class="form-control e_type"><option value="">Select Type</option><?php echo e_type($connect); ?></select></td>';
html += '<td><select name="hw_type[]" class="form-control hw_type"><option value="">Select Hardware Version</option><?php echo hw_type($connect); ?></select></td>';
html += '<td><select name="sw_type[]" class="form-control sw_type"><option value="">Select Software Version</option><?php echo sw_type($connect); ?></select></td>';
html += '<td><input type="text" name="key[]" class="form-control key" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function () {
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function (event) {
event.preventDefault();
var error = '';
$('.serial_no').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Enter Serial no at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.e_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Type at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.hw_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Hardware Version at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.sw_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Software Version at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.key').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Enter Key at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '')
{
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function (data)
{
if (data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Purchase Details Saved</div>');
}
}
});
} else
{
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
});
</script>
<?php
//insert.php;
if (isset($_POST["serial_no"])) {
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
$id = uniqid();
for ($count = 0; $count < count($_POST["serial_no"]); $count++) {
$query = "INSERT INTO elimo_purchase
(id,serial_no, e_type, hw_type, sw_type,key)
VALUES (:id,:serial_no, :e_type, :hw_type, :sw_type,:key)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $id,
':serial_no' => $_POST["serial_no"][$count],
':e_type' => $_POST["e_type"][$count],
':hw_type' => $_POST["hw_type"][$count],
':sw_type' => $_POST["sw_type"][$count],
':key' => $_POST["key"][$count]
)
);
}
$result = $statement->fetchAll();
if (isset($result)) {
echo 'ok';
}
}
?>
I'm getting output as purchase details saved but result is not stored into database.
You need to debug as per below,
Check all the values which you pass in insert query print all and check values.
Then print the query and fire the same query manually and check it was inserted or not
When you're doing an INSERT query, you can't use a fetch function, because it doesn't return any data. That can only be used with SELECT. You need to check the result of $statement->execute().
if(isset($_POST["serial_no"]))
{
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
$id = uniqid();
$query = "INSERT INTO elimo_purchase (id,serial_no, e_type, hw_type, sw_type,key)
VALUES (:id,:serial_no, :e_type, :hw_type, :sw_type,:key)";
$statement = $connect->prepare($query);
for($count = 0; $count < count($_POST["serial_no"]); $count++)
{
if (!$statement->execute(
array(
':id' => $id,
':serial_no' => $_POST["serial_no"][$count],
':e_type' => $_POST["e_type"][$count],
':hw_type' => $_POST["hw_type"][$count],
':sw_type' => $_POST["sw_type"][$count],
':key' => $_POST["key"][$count]
)
)) {
die('not ok');
}
}
echo 'ok';
}
Related
i am poorly trapped and also not getting any proper support from the Godaddy customer care. I have a comment section which is working perfectly on localhost and some other hosting but it is not working on Godaddy hosting. I don't understand, why this only occurs on godaddy.
Here is my html :
<div class="comment-form-container">
<form id="frm-comment">
<div class="input-row">
<input type="hidden" name="comment_id" id="commentId" placeholder="Name" /> <input class="input-field" type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="input-row">
<textarea class="input-field" type="text" name="comment" id="comment" placeholder="Add a Comment"> </textarea>
</div>
<div>
<input type="button" class="btn-submit" id="submitButton" value="Publish" /><div id="comment-message">Comments Added Successfully!</div>
</div>
</form>
</div>
<div id="output"></div>
Here is my script :
function postReply(commentId) {
$('#commentId').val(commentId);
$("#name").focus();
}
$("#submitButton").click(function () {
$("#comment-message").css('display', 'none');
var str = $("#frm-comment").serialize();
$.ajax({
url: "comment-add.php",
data: str,
type: 'post',
success: function (response) {
//var result = eval('(' + response + ')');
//var result = eval('(' + JSON.stringify(response) + ')');
if (response) {
$("#comment-message").css('display', 'inline-block');
$("#name").val("");
$("#comment").val("");
$("#commentId").val("");
listComment();
} else {
alert("Failed to add comments !");
return false;
}
}
});
});
$(document).ready(function () {
listComment();
});
function listComment() {
$.post("comment-list.php",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{
comments = "<div class='comment-row'>"+
"<div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$("#output").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "<div class='comment-row'>"+
" <div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
And I am 100% sure that there is no connectivity problem with database. Please help me out.
here is comment-add.php
<?php
require_once ("db.php");
date_default_timezone_set('Asia/Kolkata');
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date("Y-m-d H:i:s", time());
$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
?>
here is comment-list.php
<?php
require_once ("db.php");
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
?>
here is db.php
<?php
$conn = mysqli_connect("localhost","xxxxxxxxx","xxxxxxxx","xxxxxxxxxx");
?>
I am using jQuery and Ajax in php. I want to submit multiple rows at a time. but my code is not working properly due to the 'plantation_journal_no' which is a primary key of plantation_journal_details and the foreign key of past_history_species_details . I am badly stuck here. Can anyone please advice me that how can I solve this problem?? Thanks in advance guys. codes are given below :
index.php
<div class="row">
<form method="post" id="insert_form2" style="padding-right: 10px;">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table2">
<tr>
<th>Species</th>
<th>Product</th>
<th>Quantity</th>
<th>Value (Rs.)</th>
<th><button type="button" name="add2" class="btn btn-success btn-sm add2"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
</div>
<br>
<div align="right">
<input type="submit" name="submit4" class="btn btn-info" value="Add" onclick="move4()">
</div>
</form>
</div>
<script>
$(document).ready(function(){
$(document).on('click', '.add2', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="species[]" class="form-control species" /></td>';
html += '<td><select name="product[]" class="form-control product"><option value="">---Select---</option><option value="reserved">Reserved</option><option value="protected">Protected</option><option value="Unclassed">Unclassed</option></select></td>';
html += '<td><input type="text" name="quantity[]" class="form-control quantity" /></td>';
html += '<td><input type="text" name="value[]" class="form-control value" /></td>';
html += '<td><button type="button" name="remove2" class="btn btn-danger btn-sm remove2"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table2').append(html);
});
$(document).on('click', '.remove2', function(){
$(this).closest('tr').remove();
});
$('#insert_form2').on('submit', function(event){
event.preventDefault();
var error = '';
$('.species').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Name at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.product').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Quantity at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.quantity').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.value').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert2.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table2').find("tr:gt(0)").remove();
}
}
});
}
});
});
</script>
insert2.php
<?php
//insert.php;
if(isset($_POST["species"]))
{
$connect = new PDO("mysql:host=localhost;dbname=forestdb", "root", "");
$id=uniqid();
$sql="SELECT plantation_journal_no from plantation_journal_basic_details
where plantation_journal_no=(select max(plantation_journal_no) from
plantation_journal_basic_details);";
$state=$connect->prepare($sql);
$state->execute();
$row=$state->fetch();
$plantation_journal_no = $row['plantation_journal_no'];
for($count = 0; $count < count($_POST["species"]); $count++)
{
$query = "INSERT INTO past_history_species_details
(id, plantation_journal_no, species, product, quantity, value)
VALUES (:id, :plantation_journal_no, :species, :product, :quantity,
:value) ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $id,
':plantation_journal_no' => $plantation_journal_no,
':species' => $_POST["species"][$count],
':product' => $_POST["product"][$count],
':quantity' => $_POST["quantity"][$count],
':value' => $_POST["value"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
Frontend Table:
Backend Table
I'm guessing id is the primary key of the past_history_species_details table. You're using the same uniqid() for every row you try to insert. You need to get a new ID each time through the loop.
for($count = 0; $count < count($_POST["species"]); $count++)
{
$id = uniqid();
$query = "INSERT INTO past_history_species_details
(id, plantation_journal_no, species, product, quantity, value)
VALUES (:id, :plantation_journal_no, :species, :product, :quantity,
:value) ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $id,
':plantation_journal_no' => $plantation_journal_no,
':species' => $_POST["species"][$count],
':product' => $_POST["product"][$count],
':quantity' => $_POST["quantity"][$count],
':value' => $_POST["value"][$count]
)
);
}
Things would be easier if you made this an auto-increment column.
I'm trying to check the input from the database before inserting. However, it inserted multiple id in the parent table. It suppose to insert multiple child parent with the same parent id. I have 3 child table, toto_number, damacai_number, and magnum_number. You can have a look on the image I have provided. I'm trying to check the input from the database before inserting. So means it checking the availability of the number before inserting into database
Interface view
insert.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "2d_system";
$conn = new mysqli($servername, $username, $password, $dbname);
foreach ($_POST['gamecenter'] as $key => $value) { // all game centers will be looped here
$gamecenter = $_POST['gamecenter'][$key];
$number = $_POST['number'][$key];
$price = $_POST['price'][$key];
$result = mysqli_query($conn, "SELECT * FROM number_availability WHERE Number = '" . $number . "' AND GameCenter = '" . $gamecenter . "'");
$row = mysqli_fetch_assoc($result);
try {
if ($row['Availability'] > 0) {
if ($conn->query("INSERT INTO lottery_ticket(CreatedDateTime) VALUES (now())")) { // consider adding a default value of CURRENT_TIMESTAMP for CreatedDateTime
$lotteryTicketID = $conn->insert_id;
// foreach ($_POST['gamecenter'] as $k => $v) { // all game centers will be looped here
//$gamecenter = $_POST['gamecenter'][$k]; // make sure you need this, if the values are incorrect, then consider using
// $gamecenter = $v;
if ($stmt = $conn->prepare("INSERT INTO " . strtolower($gamecenter) . "_draw (LotteryId, " . $gamecenter . "_Number, Price) VALUES (?, ?, ?)")) { // This part is done to avoid creating so many duplicated queries and and shorten the code.
$number = $_POST['number'][$key];
$price = $_POST['price'][$key];
$stmt->bind_param('idd', $lotteryTicketID, $number, $price); // be careful with these values. If you change the name of your tables or columns, these might be affected.
$stmt->execute();
// }
if ($conn->errno) {
throw new Exception("Error: could not execute query/queries: " . $conn->error);
}
}
}
}
if ($conn->errno) {
throw new Exception("Error: could not execute query/queries: " . $conn->error);
}
echo "Records added successfully.";
}
catch (Exception $e) {
echo $e->getMessage();
}
}
$conn->close();
?>
//index.php
<?php
?>
<!DOCTYPE html>
<html>
<head>
<title>2D</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<br />
<h4 align="center">Enter Number Details</h4>
<br />
<form method="post" id="insert_form" action="test3.php">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>2D Number</th>
<th>Price (RM)</th>
<th>Game Center</th>
<th><button type="button" onclick="" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Check Number" />
</div>
</div>
</form>
</br>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="number[]" value="" class="form-control item_name" /></td>';
html += '<td><input type="text" name="price[]" class="form-control item_quantity" /></td>';
html += '<td><select name="gamecenter[]" class="form-control item_unit"><option value="">Select Unit</option><option value="Damacai">Damacai</option><option value="Magnum">Magnum</option><option value="Toto">Toto</option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.number').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Name at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.price').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Quantity at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.gamecenter').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data){
$(document.body).append(data);
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
This should do just fine. Let me know if there's any other issue further on.
<?php
try {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "2d_system";
$conn = new mysqli($servername, $username, $password, $dbname);
if($stmt = $conn->prepare($conn, "SELECT `Availability` FROM `number_availability` WHERE `Number`=? AND `GameCenter`=?")){
foreach($_POST['gamecenter'] as $key => $value){
$gamecenter = $_POST['gamecenter'][$key];
$number = $_POST['number'][$key];
$stmt->bind_param('ii', $number, $gamecenter); // if any of these values is a String, use 's' for that value instead (ii means integer-integer)
$stmt->execute();
if($conn->errno){
throw new Exception("Error: could not check for availability: " . $conn->error);
}
$result = $stmt->get_result();
$data = $result->fetch_array();
if($data['Availability'] <= 0){
unset($_POST['gamecenter'][$key]);
unset($_POST['number'][$key]);
unset($_POST['price'][$key]);
}
}
}
if($conn->errno){
throw new Exception("Error: could not check for availability: " . $conn->error);
}
if(count($_POST['gamecenter']) > 0){
if($conn->query("INSERT INTO `lottery_ticket` (`CreatedDateTime`) VALUES (now())")){
$lotteryTicketID = $conn->insert_id;
foreach($_POST['gamecenter'] as $key => $value){
$gamecenter = $_POST['gamecenter'][$key];
$number = $_POST['number'][$key];
$price = $_POST['price'][$key];
if($stmt = $conn->prepare("INSERT INTO `" . strtolower($gamecenter) . "_draw` (`LotteryId`, `" . $gamecenter . "_Number`, `Price`) VALUES (?, ?, ?)")){
$stmt->bind_param('idd', $lotteryTicketID, $number, $price);
$stmt->execute();
}
if($conn->errno){
throw new Exception("Error: could not execute query/queries: " . $conn->error);
}
}
}
if($conn->errno){
throw new Exception("Error: could not execute query/queries: " . $conn->error);
}
echo "Records added successfully.";
} else {
throw new Exception("Error: no available numbers.");
}
} catch(Exception $e){
echo $e->getMessage();
}
$conn->close();
?>
By the way, before you continue developing, read more about parameterized statements. Also, try to understand the code I'm giving you and read the comments. Last time I changed pretty much everything and I can see in this question that you ignored all that. Furthermore, you don't seem to understand the logic of your code, so give it some thought. Try writing every algorithm down in paper, then test the algorithm, and then build your applications based on that algorithm.
I got two dropdowns for my product in my cart.
All products are stored in sessions inside of a foreach loop.
But my dropdowns only work for the first product from loop.
Exemple: if i have 2 products in my cart the fisrt product row gets the cost based on both dorpdowns.
but the second product is getting the same cost from the first dropdown.
can someone please tell me how to fix this.
my script in checkout.php
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
var fabricID = $('.fabric').val();
var sizeID = $('.size').val();
var cost = $(this).attr('data-id');
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'calculates.php',
dataType : 'json',
data : {
prod_id:cost,
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(data) {
$('.icms' + cost).text(data.val);
});
}
}
});
My php foreach loop in cart.php
function cart(){
global $conn;
$fabric_options = '<option>Select Fabric</option>';
$query2 = "SELECT * FROM almofadas";
$result = mysqli_query($conn,$query2);
while($rows = mysqli_fetch_assoc($result)){
$tecido=$rows['tecido'];
$id_price=$rows['id_price'];
$t50='50';
$t45='45';
$fabric_options .= '<option value="'.$id_price.'">'.$tecido.'</option>';
}
if(!isset($_SESSION['icms'])) {
$_SESSION['icms']='0';
}else{
$_SESSION['icms'];
}
foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);
$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];
$btn_add ='<button type="button" class="btn btn-success actions plus" data-action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></button>';
$btn_remove ='<button type="button" class="btn btn-warning actions less" data-action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></button>';
$btn_delete ='<button type="button" class="btn btn-default actions" data-action="delete" product_id="'.$id.'" onclick="deleteRow(this)"><i class="fa fa-times fa-lg" aria-hidden="true"></i></button>';
if($rows['variante'] < 1){
$vari="";
}else{
$vari = "-".$rows['variante'];
}
$product = '
<tr>
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
<td style="width:15%;">
<select name="fabric" class="fabric select form-control selectpicker" required="" data-id="'.$id.'">
'. $fabric_options . '
</select>
</td>
<td>
<select data-id="'.$id.'" class="select size form-control selectpicker" required style="width:80%;" >
<option>Select size</option>
<option value="'.$t50.'">50x'.$t50.'</option>
<option value="'.$t45.'">45x'.$t45.'</option>
</select>
</td>
<td class="product'.$id.'">'.$value.'</td>
<td class="icms">R$: '.$_SESSION['icms'].'</td>
<td class="total'.$id.'" data-id="'.$id.'">R$: '.$value * $_SESSION['icms'] .' </td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;
}
}
}
}
}
and this is where my calculations are made..
calculates.php
<?php header('Content-Type: application/json');
include_once '../incluedes/conn_cms.php'; //session allways start here
if(isset($_GET["size_id"],$_GET["fabric_id"],$_GET['prod_id'])){
$size_id=$_GET["size_id"] ;
$fabric_id=$_GET["fabric_id"] ;
$prod = $_GET['prod_id'];
$prodname = 'product_'.$prod;
$query3 =" SELECT * FROM valores_almofadas WHERE size='$size_id' AND price_id ='$fabric_id'";
$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){
if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;
}
echo json_encode( $_SESSION['icms']);
}
how can i make my dropdown work foreach product?
The problem is that var fabricID = $(".fabric").val() is selecting the value from the first element it finds with the fabric class. This will be the same element (the first one) every time, no matter how many elements exist on the page with that class.
You need to select the value from the correct elements. This is made slightly trickier by the fact that you need to send both the fabric and size values simultaneously. Luckily you have got the row ID as a data attribute on both the <select> elements, so we can use this to match them up.
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
//use the data-id attribute of the selected element to match the correct elements
var id = $(this).data("id");
var fabricID = $('.fabric[data-id=' + id + ']').val();
var sizeID = $('.size[data-id=' + id + ']').val();
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'calculates.php',
dataType : 'json',
data : {
prod_id:id,
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(data) {
$('.icms' + id).text(data.val);
});
}
}
});
Here is my code, which is having a problem displaying the values of the second:
HTML: my form, the first drop down I get the elements from the database with query.
<form name="farmer" action="index.php" method="post">
<label>
<span>Chose Land:</span>
<select name="land" id="land">
<option value="">--land--</option>
<?php
$sql="SELECT `city` FROM `lands`";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
?>
<option value ="<?php echo $data['city'] ?>" ><?php echo $data['city'] ?></option>
<?php } ?>
</select>
</label>
<label>
<span>Region:</span>
<select name="region" id="region">
<option value="">--region--</option>
</select>
</label>
<input class="button4" type="submit" name="submit" value="Submit" />
</form>
JS
jQuery(document).ready(function() {
jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': jQuery('#land').val()
},
function(data, textStatus) {
jQuery('#region').empty();
if(data != null)
{
jQuery.each(data, function(index, value) {
jQuery('#region').append('<option value="' + value + '">' + value + '</option>');
});
}
else {
jQuery('#region').append('<option value="">Please select...</option>');
}
},
'json'
);
});
});
getList.json.php file - Here I make connection between region and land with query(JOIN).
<?php
mysql_connect("localhost", "root", "") or die( "Unable to connect to database");
mysql_select_db("farmer_fields") or die( "Unable to select database");
if($_POST && $_POST['land'] != "") {
$sql="SELECT region FROM regions
LEFT JOIN lands
ON regions.id_lands = lands.id";
$rows = array();
while ($data=mysql_fetch_assoc($sql)){
$rows['region'] = $data;
}
echo json_encode( $rows );
}
?>
No need of json here. You can simply do with jquery and ajax
jquery:
function get_region(country_id) {
if (country_id != 0) {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
$.post("ajax/ajax.php", {
country_id: country_id
}, function (data) {
var data_array = data.split(";");
var number_of_name = data_array.length - 1;
var value;
var text;
var opt;
var temp_array;
for (var i = 0; i < number_of_name; i++) {
temp_array = data_array[i].split(",");
value = temp_array[1];
//alert(value);
text = temp_array[0];
opt = new Option(text, value);
$('#region_id').append(opt);
$(opt).text(text);
}
$("#region_id").prop("disabled", false);
});
} else {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
}
}
ajax file that is ajax.php
if (isset($_POST["country_id"])) {
$country_id = $_POST["country_id"];
$region_select = mysql_query("select * from region where country_id='$country_id'");
$region = "";
$region_id = "";
while ($region_row = mysql_fetch_array($region_select)) {
$region = $region.$region_row["region"].
",".$region_id.$region_row["id"].
";";
}
echo $region;
}
HTML OF REGION SELECT BOX:
<select name="region_id" id="region_id" disabled="disabled">
<option value="0">Select Region</option>
</select>
You may change mysql_query to PDO for security purpose as mysql_query is depriciated.
Check this, works for me.
JS:
jQuery(document).ready(function() {
var region = jQuery('#region');
var land = jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': land.val()
},
function(data) {
jQuery('#region').empty();
if (data != null) {
region.append(data);
}
else {
region.append('<option value="">Please select...</option>');
}
},
'html'
);
});
});
PHP:
if($_POST && $_POST['land'] != "") {
$sql="SELECT region
FROM regions r
LEFT JOIN lands l ON r.id_lands = l.id
WHERE l.city = " . $_POST['land'];
$result = mysql_query($sql); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< UPD!
while ($data = mysql_fetch_assoc($result)) {
echo '<option value="' . $data['region'] . '">' . $data['region'] . '</option>';
}
}