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.
Related
If anyone could point me in the right direction with this code I would greatly appriciate it, tell me how to debugg or point me in the right direction.
When I click the save button, the database gets updated, what I want to do is to send the new data back to ajax and display it in the same columns as the inputs where.
Question: How do I return the data in a response from PHP to Ajax and update the columns with the new text?
I have implemented code from this thread into my project:
Allow editing of Text dynamic php table
This is my front end code:
<div class="planerarad momentrad" data-row="<?php echo $pmomentID; ?>" ondblclick="toggleaction<?php echo $pmomentID; ?>()">
<div data-column='name' class="ansvar <?php echo $rowp['status'];?>">
<?php echo $rowp['ansvarig'];?>
</div>
<div data-column='moment' class="moment <?php echo $rowp['status'];?>">
<?php echo $rowp['moment'];?>
</div>
<div data-column='deadline' class="deadline <?php echo $rowp['status'];?>">
<?php
echo $rowp['deadline'];?>
</div>
<div class="icon">
</div>
<div class="moment-meny">
<div class="m-current">
<?php if ($pstatus == 0) { ?>
<button type="button"><i class="far fa-question-circle"></i></button>
<?php
} elseif ($pstatus == 1) { ?>
<button><i class="fas fa-user-check"></i></button>
<?php
} elseif ($pstatus == 2) { ?>
<button><i class="fas fa-exclamation"></i></button>
<?php
} elseif ($pstatus == 3) { ?>
<button><i class="fas fa-check"></i></button>
<?php } ?>
</div>
<div class="ärendeadmin">
<div class="m-remove">
<form action="scripts/s_editPlan.php" method="post" id="deletePlan<?php echo $pmomentID; ?>">
<input type="hidden" name="momentid" value="<?php echo $pmomentID ;?>">
</form>
<button name="deleteMoment" type="submit" form="deletePlan<?php echo $pmomentID; ?>"><i class="fas fa-trash-alt"></i></button>
</div>
<div class="m-edit">
<button class="closeWindow btn-info"><i class='fas fa-edit'></i></button>
</div>
</div>
And here is the jquery to replace text with inputs and send to php file:
<script>
$( function(){
$(document).on("click", ".btn-info", function(){
var parent = $(this).closest(".momentrad");
var id = $(parent).attr("data-row");
var name = $(parent).children("[data-column='name']");
var moment = $(parent).children("[data-column='moment']");
var deadline = $(parent).children("[data-column='deadline']");
var nameTxt = $(name).html();
var momentTxt = $(moment).html();
var deadlineTxt = $(deadline).html();
$(name).html("<input class='input' list='users' name='name' data-dc='ansv' value='"+$.trim(nameTxt)+"'>");
$(moment).html("<input name='moment' data-dc='moment' value='"+$.trim(momentTxt)+"'>");
$(deadline).html("<input type='date' max='9999-12-31' data-dc='deadline' value='"+$.trim(deadlineTxt)+"' name='deadline'>");
$(this).replaceWith("<button class='btn-info-save'>Save</button>");
});
})
</script>
<script>
$(function(){
$(document).on("click", ".btn-info-save", function(){
var parent = $(this).closest(".momentrad");
var id = $(parent).attr("data-row");
var data = {id: id};
var name = $(parent).children("[data-column='name']");
var moment = $(parent).children("[data-column='moment']");
var deadline = $(parent).children("[data-column='deadline']");
$("[data-dc]").each( function(){
var col = $(this).attr("data-dc");
var val = $(this).val();
data[col] = val;
console.log(data);
});
$.ajax({
url: "scripts/s_editPlan.php", // Change this to your PHP update script!
type: 'POST',
dataType: 'json',
data: data,
success: function(ret){
$(name).html(data(ansv));
$(moment).html(data(moment));
$(deadline).html(data(deadline));
alert("Ändringen lyckades! '"+$.trim(deadlineTxt)+"' '"+$.trim(momentTxt)+"' '"+$.trim(nameTxt)+"' ");
console.log(ret.response);
},
error: function(ret){
console.log(ret.response);
alert("Ändringen lyckades inte, inget!");
}
});
});
})
</script>
This is the PHP file:
<?php
include "dbh-script.php";
header('Content-type: application/json');
if (isset($_POST['ansv'], $_POST['moment'], $_POST['deadline'], $_POST['id'])) {
$dataid = $_POST['id'];
$ansv = $_POST['ansv'];
$moment = $_POST['moment'];
$deadline = $_POST['deadline'];
$sql = "UPDATE todoaction SET ansvarig='$ansv', moment='$moment', deadline='$deadline' WHERE id='$dataid'";
if ($conn->query($sql) === TRUE) {
echo json_encode(print_r($_POST););
} else {
echo json_encode( ["response"=>"Någonting gick fel. Error: " . $sql . "<br>" . $conn->error] );
}
}
if (isset($_POST['momentid'])) {
$id = $_POST['momentid'];
}
if (isset($_POST['deleteMoment'])) {
$sql = "UPDATE todoaction SET status='4' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['acceptMoment'])) {
$sql = "UPDATE todoaction SET status='1' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['helpMoment'])) {
$sql = "UPDATE todoaction SET status='2' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['checkMoment'])) {
$sql = "UPDATE todoaction SET status='3' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
I'm aware that it might be alot of errors and strange coding since I'm trying to learn by doing.
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.
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';
}
I have a small line of code that will get the sum of a column
<?php
class ManageServices{
function getTotalSumByDateRange()
{
$query = $this->link->query("SELECT SUM(amount) as sum_of_date_range FROM services ");
$rowcount = $query->rowCount();
$result = $query->fetchAll();
return $result;
}
}
?>
//search.php
<?php
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$sum_of_date_range = $init->getTotalSumByDateRange();
?>
//search1
<?php
if(isset($_POST['submit']))
{
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$date_from =$_POST['to_date'];
$date_to =$_POST['from_date'];
if(empty($_POST['to_date']) && empty($_POST['from_date']))
{
$error = "No search query";
}
elseif(empty($_POST['to_date']) && !empty($_POST['from_date']))
{
$error ="Please specify your start date search";
}
elseif(!empty($_POST['to_date']) && empty($_POST['from_date']))
{
$error ="Please specify your end date search";
}
else
{
$total_by_date_range = 0;
$total_by_date_range = $init->getSumByDateRange($date_from, $date_to);
}
}
?>
//html
<?php
include_once('../../libs/search/search_sales_by_date.php');
include_once('../../libs/search1/total_sales.php');
?>
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>search by dates</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
</head>
<body>
<div>
<?php
if(isset($error))
{
echo $error;
}
?>
</div>
<h3>Search Sales</h3>
<p>From</p>
<form method="POST" action="search_sales_by_dates.php">
<p>Date: <input type="text" class="datepicker" name="from_date" id="field1"></p>
<p>To</p>
<p>Date: <input type="text" class="datepicker" name="to_date" id="field2"></p><br />
<input type="submit" value="search" name="submit" id="submitdata">
</form>
<div id ="fillmein1">
<?php foreach($sum_of_date_range as $sum): ?>
<td>Total Sales<span class="glyphicon glyphicon-usd" aria-hidden="true"></span><?php echo number_format($sum['total_sum'],2); ?></td>
<?php endforeach; ?>
</div>
<input type="hidden" value ="$total_by_date_range['sum_of_date_range'] ">//this is the problem
</body>
</html>
and in my table i have columns 'id','amount',date_of_service'.The query above will calculate all the 'amount' values and display in html, however, i want to add another query that will only get the sum of 'amount' column base on a date range input from html form.Any ideas on this?
Update..I think I'm almost there,after I updated search1.php,search.php,and html my problem now is I want to show the $total_by_date_range in same form.But when I submit the form, it shows no error but will not show the $total_by_date_range.anyway,the $sum_of_date range shows result in the same page
First you need to add another function:
class ManageServices {
function getTotalSumByDateRange() {
$query = $this->link->query("SELECT SUM(amount) as sum_of_date_range FROM services ");
$rowcount = $query->rowCount();
$result = $query->fetchAll();
return $result;
}
function getSumByDateRange($date_from, $date_to) {
$query = $this->link->query("SELECT SUM(amount) as sum_of_date_range FROM services where
date_of_service between '".$date_from."' and '".$date_to."'");
$rowcount = $query->rowCount();
$result = $query->fetch();
return $result;
}
}
Search.php
<?php
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$sum_of_date_range = $init->getTotalSumByDateRange();
$total_by_date_range = $init->getSumByDateRange($_POST['from_date'],$_POST['to_date']);
?>
HTML
<?php
include_once('../../libs/search/search_sales_by_date.php');
?>
<div>
<?php foreach($sum_of_date_range as $sum):?>
<td><span class="glyphicon glyphicon-usd" aria-hidden="true"></span><?php echo number_format($sum['sum_of_date_range'],2); ?></td>
<?php endforeach;?>
<?php
echo "Total by date range: ".$total_by_date_range;
?>
</div>
You can try something like this.
First, when from date and end date is not specified, you display all the sum. But if those exists you filter your query to display sum within the date range.
Here is my solution.
function getTotalSumByDateRange($fromDate = "", $toDate = "")
{
$sql = "SELECT SUM(amount) as sum_of_date_range FROM services ";
if (!empty($fromDate) && !empty($toDate) {
$sql .= "WHERE date_of_service BETWEEN '". $fromDate . "' AND '" . $toDate . "'";
}
$query = $this->link->query($sql);
$rowcount = $query->rowCount();
$result = $query->fetchAll();
return $result;
}
Now it's working.I rewrite my search.php
<?php
if(isset($_REQUEST['submit']))
{
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$date_to =$_REQUEST['to_date'];
$date_from =$_REQUEST['from_date'];
if(empty($date_from) && empty($date_to))
{
$error = "No search query";
}
elseif(empty($date_from) && !empty($date_to))
{
$error = "Specify your end date search";
}
elseif(!empty($date_from) && empty($date_to))
{
$error ="Specify your start date search";
}
else
{
if($date_from < $date_to)
{
$total_by_date_range = $init->getSumByDateRange($date_from, $date_to);
foreach ($total_by_date_range as $key)
{
$success ="Your Total amount of sales from ". $date_from . ' ' . "To" . ' ' .$date_to . ' ' ."is". ' ' ."P" .number_format($key['sum_of_date_range'],2);
}
}
else
{
$error = "You bitch, Start date should not greater than the end date on your search query";
}
}
}
else
{
$error = "Because you are an idiot, the script contains some bugs that is why it can't run on the browser!";
}
?>
and I also changed the date format of Jquery datepicker, similar to the format used by mysql,I found out that having different date format in html($_GET method) and the format used by mysql will result null in query.
I have a dynamic HTML table that allows users to enter receipt items in, and they can add as many rows as necessary.
If they forget to fill out a field upon form POST, I want all those rows with the data to stay shown, instead what happens, is they dynamic rows disappear and no values are saved in the one row that shows on default.
How can I achieve having those dynamic table rows shown with the values they've entered to avoid them having to enter all the data again?
<?php
if(isset($saveAdd))
{
$expenseType = safeDataMySQL($_POST['expenseType']);
//Save page, redirect to same page but increment receipt number.
if(empty($_POST['expenseNumber']))
{
//New expense so no records have been created as of yet. Otherwise, this would be stored in hidden field.
$getRef = mysql_query("SELECT CAST(SUBSTRING(refNumber,4) AS UNSIGNED INTEGER) AS referenceNumber FROM expense_main ORDER BY referenceNumber DESC LIMIT 1") or die("Ref No: " . mysql_error());
if(mysql_num_rows($getRef) > 0)
{
while($refData = mysql_fetch_array($getRef))
{
//Expense Number!
$refNumber = $refData['referenceNumber'];
$refNumber = ($refNumber + 1);
}
$ins = mysql_query("INSERT INTO `expense_main` (`respid`, `refNumber`, `dateCreated`, `draftMode`, `expenseType`) VALUES ('".$respid."', 'USA".$refNumber."', NOW(), '1', '".$expenseType."')") or die("Expense Insert: " . mysql_error());
$expClaimNumber = 'USA'.$refNumber;
}
}
else
{
$expClaimNumber = safeDataMySQL($_POST['expenseNumber']);
}
//Get the next receipt in line as well
$getRec = mysql_query("SELECT receiptNumber FROM expense_details ORDER BY receiptNumber DESC LIMIT 1") or die("Get Receipt: " . mysql_error());
if(mysql_num_rows($getRec) > 0)
{
while($recData = mysql_fetch_array($getRec))
{
$receiptNumber = $recData['receiptNumber'];
$receiptNumber = ($receiptNumber + 1);
}
}
$fields = array('recLineDate_', 'recLineCategory_', 'recLineDescr_', 'recLineAmount_');
foreach ($fields as $field)
{
foreach ($_POST[$field] as $key=>$line)
{
$returnArray[$key][$field] = $line;
}
}
foreach ($returnArray as $lineItem)
{
if(empty($lineItem['recLineDate_']))
{
$Errors[] = 'You forgot to enter the receipt date.';
}
else
{
$recDate = safeDataMySQL($lineItem['recLineDate_']);
}
if(empty($lineItem['recLineCategory_']))
{
$Errors[] = 'You forgot to enter a category.';
}
else
{
$recCategory = safeDataMySQL($lineItem['recLineCategory_']);
}
if(empty($lineItem['recLineDescr_']))
{
$Errors[] = 'You forgot to enter a description.';
}
else
{
$recDescr = safeDataMySQL($lineItem['recLineDescr_']);
}
if(empty($lineItem['recLineAmount_']))
{
$Errors[] = 'You forgot to enter your receipt amount.';
}
else
{
$recAmount = safeDataMySQL($lineItem['recLineAmount_']);
}
if(empty($_POST['alternateBranch']))
{
$alternateBranch = '0';
}
else
{
$alternateBrach = $_POST['alternateBranch'];
}
if(!isset($Errors))
{
$recDate = date("Y-m-d", strtotime($recDate));
$ins = mysql_query("INSERT INTO `expense_details` (`receiptNumber`, `claimId`, `alternateBranch`, `dateAdded`, `expenseDate`, `expenseDescription`, `expenseAmount`, `categoryId`)
VALUES ('".$receiptNumber."', '".$expClaimNumber."', '".$alternateBranch."', NOW(), '".$recDate."', '".$recDescr."', '".$recAmount."', '".$recCategory."')") or die("Could not insert receipt: " . mysql_error());
$nextReceipt = ($receiptNumber + 1);
//Redirect to same page, incrementing the receipt number by 1.
header('Location: createExpense.php?expenseNumber='.$expClaimNumber.'&receiptNum='.$nextReceipt);
}
}
}
$expenseNumber = safeData($_GET['expenseNumber']);
$receiptNumber = safeData($_GET['receiptNum']);
if (isset($Errors))
{
echo "<div align='center'><span class='errormessagered'><ul class='errors'>";
foreach ($Errors as $Error)
{
echo "<li>".$Error."</li>";
echo '<br />';
}
echo "</ul></span></div>";
}
?>
<form name="createNew" method="POST" action="">
<div id="row">
<div id="left">
<strong>Receipt Items:</strong>
</div>
<div id="right">
<i>Only add another line to the receipt below IF you have multiple items on one receipt.</i>
<br /><br />
<table border="0" width="825px" cellspacing="0" cellpadding="5" name="receipts" id = "receipts">
<thead>
<tr>
<th class="colheader" width="120px">Date</th>
<th class="colheader" width="120px">Category</th>
<th class="colheader" width="120px">Description</th>
<th class="colheader" width="120px">Amount</th>
<th class="colheader" width="145px"><span class="boldblacklinks">[Add +]</span></th>
</tr>
</thead>
<tbody class="lineBdy">
<tr id="line_1" class="spacer">
<td><input type="text" class="date fieldclasssm" id="recLineDate[]" name="recLineDate_[]" size="10" value = "<?=date("m/d/Y", strtotime($today))?>"/></td>
<td><select name="recLineCategory_[]" class="fieldclasssm">
<option value = "">Select a Category...</option>
<?php //Get Categories
$getCats = mysql_query("SELECT id, nominalName FROM expense_nominalCodes ORDER BY id") or die("Get Cats: " . mysql_error());
if(mysql_num_rows($getCats) > 0)
{
while($catData = mysql_fetch_array($getCats))
{
echo '<option value = "'.$catData['id'].'"'; if($catData['id'] == $_POST['recLineCategory_']) { echo "Selected = 'SELECTED'"; } echo '>'.$catData['nominalName'] . '</option>';
}
}
?>
</select>
</td>
<td><input type="text" class="lineDescr fieldclasssm" name="recLineDescr_[]" id="recLineDescr[]" value = "<?=$_POST['recLineDescr']?>" size="40" /></td>
<td colspan = "2"><input type="text" class="sum lineAmount fieldclasssm" name="recLineAmount_[]" id="recLineAmount[]" value = "<?=$_POST['recLineAmount']?>" size="12" /></td>
</tr>
</tbody>
</table>
</div>
" />
" />
<script type="text/javascript">
$(document).ready(function () {
$('.date').change(function () {
$('.date').val($('.date:nth-of-type(1)').val());
});
});
//Add new table row & clone date field
$('#add').on('click', function(){
addReceiptItem();
$('.date').focus(function() {
$(this).select();
});
$('.receipt').focus(function() {
$(this).select();
});
});
function addReceiptItem(){
var lastID = $('tr[id*="line_"]').length,
newTds = $('tr[id="line_' + lastID + '"] td').clone(),
newRow = document.createElement('tr');
// add new id and class to row, append cloned tds
$(newRow)
.attr('id', 'line_' + (lastID + 1 ))
.attr('class', 'spacer')
.append(newTds);
$(newRow).find('input').not(':eq(0)').val('');
// $(newRow).find('class').not(':eq(0)').not(':eq(0)').val('');
//add the new row to the table body
$('tbody.lineBdy').append(newRow);
$('.receipt').attr('readonly', true);
$('.date').attr('readonly', true);
};
</script>
Just to get you started. You can add the rows from $_POST["rows"]
foreach ($_POST["rows"] as $rowstring) {
list($date, $cat, $desc, $amt) = explode(",", $rowstring)
?>
<td><?php echo $date; ?></td>
<td><?php echo $cat; ?></td>
<td><?php echo $desc; ?></td>
<td><?php echo $amt; ?></td>
<td> </td>
<?php
}
Assuming you add a hidden input with a comma delimited string each time a dynamic row is added.
FWIW, I would also recommend doing all of the database queries (ie $getCats = ...) prior to rendering anything to the screen so that in case the 'or die()' happens, you wont get a half rendered page.