I have paginated table and input field. I want to allow user to create new process. Created table allow user to view already existed processes.
hmtl code:
<div class="inner">
<center><table class="paginated">
<?php
$result = getProcessData();
if (mysqli_num_rows($result) > 0)
{
echo '
<thead>
<tr>
<th>Process</th>
<th>Created By</th>
</tr>
</thead>';
}
$count = 0;
if (mysqli_num_rows($result) > 0)
while($row = mysqli_fetch_array($result))
{
$process = $row['theme_name'];
$createdBy = $row['createby'];
echo '
<tbody>
<tr valign="top">
<td>' .$process. '</td>
<td>' .$createdBy. '</td>
</tr>
</tbody>';
$count++;
}
?>
</table></center>
<form id="reguserform" method="post" action="process.php#err" style="margin-top:40px;">
<?php
$res = verifyFormFields();
?>
<!-- Username field -->
<input type="text" class="input name" placeholder="Process name (required)" name="process" required/>
<!--<label class="tooll tool1">- No special Characters except _<br>- Character Limit: 4 to 20<br>- Username must be Unique</label>-->
<center><input type="submit" class="button small" name="submit" value="Create Process"/></center>
<div id="registerModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog" data-options="close_on_background_click:false">
<h2 id="modalTitle">Success!</h2>
<div>
<div id="testRegister" style="font-weight: 400;font-size: 1.5em; font-family: 'Raleway', Arial, sans-serif;"></div>
<div class="right">
Ok
</div>
</div>
</div>
<?php
if($count == 1)
{
if($res=="")
{
registerProcess();
echo"<script>document.getElementById('testRegister').innerHTML=registerStr;callShowAlert();</script>";
}
else{
echo "
<a style='color:red';>
$res
</a>
";
}
}
?>
</form>
</div>
I validate the field and the inserting process into database:
function registerProcess(){
$con = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
global $process;
// To protect MySQL injection (more detail about MySQL injection)
$process = cleanInputData($process);
$process = mysqli_real_escape_string($con, $process);
//query result
$result = insertNewProcess(NULL,$process,$_SESSION['login_user'],1);
// Check result
if (!$result) {
$msg2= "Process is already added. You cannot add same process twice!";
echo $msg2;
die('Invalid queryyyy: ' . mysqli_error($con));
}
// the message
$msg = "Process is added!";
// use wordwrap() if lines are longer than 70 characters
echo "<script>var registerStr = 'Process Is Added';</script>";
//echo "<meta http-equiv='refresh' content='0'>";
}
function verifyFormFields(){
global $process;
if(empty($process)){
return "<p id ='err'>Please Input Process</p>";
}
else return "";
}
Also I use javascript to call pop up window and make table paginated:
<script type="text/javascript">
(function() {
$(document).foundation();
});
function callShowAlert()
{
$('#registerModal').foundation('reveal', 'open');
}
function popUpNo()
{
$('#registerModal').foundation('reveal', 'close');
location.href = 'process.php';
}
var testVal = 0;
</script>
<script>
$(document).ready(function() {
$('table.paginated').each(function() {
var currentPage = 0;
var numPerPage = 5;
var $table = $(this);
$table.bind('repaginate', function() {
$table.find('tbody tr').hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
});
$table.trigger('repaginate');
var numRows = $table.find('tbody tr').length;
var numPages = Math.ceil(numRows / numPerPage);
var $pager = $('<div class="pager"></div>');
for (var page = 0; page < numPages; page++) {
$('<span class="page-number"></span>').text(page + 1).bind('click', {
newPage: page
}, function(event) {
currentPage = event.data['newPage'];
$table.trigger('repaginate');
$(this).addClass('active').siblings().removeClass('active');
}).appendTo($pager).addClass('clickable');
}
$pager.insertBefore($table).find('span.page-number:first').addClass('active');
});
} );
</script>
it works perfect, I got popup window and system inserts record to database but only if there is only input field and submit button. When I put table it doesnt work. System does not reload and not insert record into database. Why?
So I solved this problem by simply putting table after form:
<div class="inner">
<form id="reguserform" method="post" action="process.php#err" style="margin-top:40px;">
<?php
$res = verifyFormFields();
?>
<!-- Username field -->
<input type="text" class="input name" placeholder="Process name (required)" name="process" required/>
<!--<label class="tooll tool1">- No special Characters except _<br>- Character Limit: 4 to 20<br>- Username must be Unique</label>-->
<center><input type="submit" class="button small" name="submit" value="Create Process"/></center>
<div id="registerModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog" data-options="close_on_background_click:false">
<h2 id="modalTitle">Success!</h2>
<div>
<div id="testRegister" style="font-weight: 400;font-size: 1.5em; font-family: 'Raleway', Arial, sans-serif;"></div>
<div class="right">
Ok
</div>
</div>
</div>
<?php
if($count == 1)
{
if($res=="")
{
registerProcess();
echo"<script>document.getElementById('testRegister').innerHTML=registerStr;callShowAlert();</script>";
}
else{
echo "
<a style='color:red';>
$res
</a>
";
}
}
?>
</form>
<center><table class="paginated">
<?php
$result = getProcessData();
if (mysqli_num_rows($result) > 0)
{
echo '
<thead>
<tr>
<th>Process</th>
<th>Created By</th>
</tr>
</thead>';
}
$count = 0;
if (mysqli_num_rows($result) > 0)
while($row = mysqli_fetch_array($result))
{
$process = $row['theme_name'];
$createdBy = $row['createby'];
echo '
<tbody>
<tr valign="top">
<td>' .$process. '</td>
<td>' .$createdBy. '</td>
</tr>
</tbody>';
$count++;
}
?>
</table></center>
</div>
So as I got it, table cannot be updated before from.
Related
I want to make a clone of node to get the UID encrypting the data into the clipboard. I got the id from the internal server but I don't know how to clone the node so it understands the correct location it copied.
<div class="container">
<div class="wrapper" id="form-inf">
<h3>Information</h3>
Import UID
Select
<table style="width:100%" class="form-main-table">
<tr>
<th>STT</th>
<th>ID</th>
<th>UID</th>
<th>Day Create</th>
<th>Action</th>
</tr>
<?php
require '../connect/connect.php';
// $sql = "SELECT * FROM category";
$sql = "DELETE FROM tbl_new_uid WHERE cd_del=1";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error deleting record: " . $conn->error;
}
$sql = "SELECT * FROM tbl_new_uid ORDER BY date_create DESC";
$result = $conn->query($sql) or die($conn->error);
$stt = 1;
while($row = $result -> fetch_assoc()){
?>
<tr>
<td><?=$stt++?></td>
<td><?=$row['id']?></td>
<td id="inf_copy"><?=$row['uid_new']?></td>
<td><?=$row['date_create']?></td>
<td>Edit
Delete
<button id="btn_copy" class="btn btn-warning" style="width: 100px;">Copy</button></td>
</tr>
<?php }
$conn->close();
?>
</table>
</div>
</div>
<script>
// setTimeout('window.location.reload();',3000);
</script>
<script>
$('#btn_copy').on('click', function() {
var text = $('#inf_copy').html();
var tempElement = $('<input>').val(text).appendTo('body').select();
document.execCommand('copy');
tempElement.remove();
var elem = document.getElementById("inf_copy");
elem.style.background = "yellow";
elem.style.fontWeight = "bold";
});
</script>
Update id for "td" tag, that you want to copy text from
Update Button "id" As id must have to be uniqe
Updated Coding Lines are as bellow
HTML CODE UPDATE
<td id="inf_copy_<?php echo $row['uid_new']; ?>"><?=$row['uid_new']?></td>
<td>Edit
Delete
<button id="btn_copy_<?php echo $row['uid_new']; ?>" class="btn btn-warning btn_copy" style="width: 100px;">Copy</button>
</td>
JS CODE UPDATE
$('.btn_copy').on('click', function() {
var btn_copy = this.id;
btn_copy = btn_copy.replace('btn_','inf_');
var text = $('#'+btn_copy).html();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I've got some code where I have to input my contact data from client, and output data from MySQL database which creates new rows in table
Also there's additional function which has to be inside the code - but I've no idea how to handle this problem. I have to count the amount of element pieces x their weight in real-time to show the client the total weight the order is going to have.
The problem is I don't know how to make the client see it whenever they change the value of Pieces in <input>.
Lastly, the data from the form and table has to be sent to employee via email.
PHP Code:
<html>
<head>
<meta charset="utf-8" />
<meta name="calculator" content="width=device-width, initial-scale=1"/>
<title>Test</title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<h1>TEST</h1>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="<?= $form['EMAIL']; ?>" class="form-contact" required><br>
<input id="Country" type="text" placeholder="<?= $form['COUNTRY']; ?>" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="<?= $form['PHONE']; ?>" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<table class="table-responsive" border="1">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".'<input class="pcs-input" min=0 maxlength="3" value=0 size="2px" style="background-color: white;" name="inputs[]">';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sumWeight'></div></td></tr>";
}
} else {
echo "0 Results";
}
mysqli_close($connection);
?>
</tbody>
</table>
<!-- Counting all needed atributes -->
<div id="totalWeight">totalWeight</div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
</html>
JavaScript Code
<script type="text/javascript">
document.addEventListener(function()
input.OnChange = calculateForm();
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
totalWeight += sumWeight;
}
});
document.write(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
Updated
Well it doesn't work again, no errors, just doesn't multiply
I think the problem might be with transporting data from table/database into the variable, any solution?
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' id='inputs' data-weight=".$row["weight"];
echo "></input>";
# echo "<tr><td>".$row["id"].'';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sum-Weight2'></div></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).parent().parent().find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('.totalGewicht').html(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
<!-- Counting all needed atributes -->
<div id="totalWeight"></div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
Overall there are quite a few issues with your code, which can be summarised as problems with
invalid HTML (e.g. duplicate IDs, incorrectly written input element, un-closed table rows, un-closed data attributes)
over-complicated HTML
typing or case errors (e.g. W instead of w)
incorrect CSS selectors in the JavaScript
lack of initial default data (e.g. if there are no numbers in any one of the input boxes, the calculation will fail because trying to add a blank value to another number results in NaN (Not a Number)
calculation did not run when page loads, so data is missing until the user changes something (which is no use, if they want to see the current weight before changing any values)
This client-side demo demonstrates the HTML you need to get your PHP to produce, and the correct JavaScript / jQuery code in order to do the calculations and display the results:
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
table
{
border-collapse:collapse;
}
td
{
border: solid 1px black;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td><input type='number' class='pcs-input' data-weight='3' value='1' /></td>
<td>Nr. 14536</td>
<td>Test 1</td>
<td>3 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='15' value='1' /></td>
<td>Nr. 23431</td>
<td>Test 2</td>
<td>15 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='4' value='1' /></td>
<td>Nr. 33125</td>
<td>Test 3</td>
<td>4 kg</td>
<td class='sum-weight2'></td>
</tr>
</tbody>
</table>
Total Weight: <span id="totalWeight"></span>
Remember you need to move the focus from the textbox to another element (using mouse or tab key) before the "change" event will fire. (It will also run if you use the up/down buttons on the input box.)
So this means, as well as editing the JavaScript as I've shown, you need to alter the PHP so it outputs the HTML table rows with the structure and data I've demonstrated above.
This should work:
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='1' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
Resolution:
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="Email" class="form-contact" required><br>
<input id="Country" type="text" placeholder="49" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="Tel" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class=".table-responsive">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='0' min='0' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
</script>
<!-- Counting all needed atributes -->
Total Weight: <span id="totalWeight"></span>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
Can someone help me on pagination syntax for php webpage. I have a set a pagination code to display 20 records per page. The records are displaying based on 'start date' and 'end date'.
The issue is, it works on page 1 but when I click on page 2 in pagination then it won't work. I assume the values of $_POST['startdate'] and $_POST['enddate] are not forwarding on page2.
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="multitab/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
.inline{
display: inline-block;
float: right;
margin: 20px 0px;
}
input, button{
height: 34px;
}
</style>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<table>
<tr>
<td><b>Start date:</b></td>
<td><input type="date" id="startdate" name="startdate" size="10"> </td>
<td><b>End date:</b></td>
<td><input type="date" id="enddate" name="enddate" size="10" max=<?php echo date('Y-m-d');?>></td>
<td><input type="submit" value="Search" name="Search" onClick="return check()"></td>
</tr>
</table>
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abc_db",$con);
$limit = 20;
if (isset($_GET["page"])) {
$pn = $_GET["page"];
}
else {
$pn=1;
};
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
$start_from = ($pn-1) * $limit;
$serial = (($pn-1) * $limit) + 1;
$today1= date("Y/m/d");
$days14_ago = date('Y/m/d', mktime(0, 0, 0, date("m") , date("d") - 14, date("Y")));
if ($startdate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$startdate1' LIMIT $start_from, $limit";
} else if ($enddate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$enddate1' LIMIT $start_from, $limit";
} else {
$sql = "SELECT * FROM hd where datearrival between '$days14_ago' and '$today1' LIMIT $start_from, $limit";
}
if (($startdate !=Null) && ($enddate !=Null)) {
$sql = "SELECT * FROM hd where datearrival between '$startdate1' and '$enddate1' LIMIT $start_from, $limit";
}
$rs_result = mysql_query ($sql);
?>
<div class="container">
<button style="height:25px;width:70px;" onclick="window.location.reload(true);">Refresh</button>
<br>
<div>
<font face='cambria'><p><span style="display:inline-block; margin-left: 650px; ">
</span></p> </font>
<font face="Cambria" size="2"> <table class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th width="5%" valign="top">Sr#</th>
<th width="10%" valign="top">Date arrival</th>
<th width="10%" valign="top">Pno</th>
<th width="10%" valign="top">First name</th>
<th valign="top"></th>
<th valign="top"></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($rs_result, MYSQL_ASSOC)) {
$pno1=$row['pno'];
$datearrival1=$row['datearrival'];
$sr_num = $serial++;
?>
<tr>
<td><?php echo $sr_num; ?></td>
<td><?php echo date("d/m/Y", strtotime($row['datearrival'])); ?></td>
<td><?php echo $row["pno"]; ?></td>
<td><?php echo $row["first_name"]; ?></td>
<td><p align="center">edit</font></td>
<td><p align="center">delete</font></td>
</tr>
<?php
};
?>
</tbody>
</table>
</font>
<div>
<ul class="pagination">
<?php
$sql = "SELECT COUNT(*) FROM hd where datearrival between '$startdate1' and '$enddate1'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$k = (($pn+4>$total_pages)?$total_pages-4:(($pn-4<1)?5:$pn));
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."'> >> </a></li>";
}
?>
</ul>
<div class="inline">
<input id="pn" type="number" min="1" max="<?php echo $total_pages?>"
placeholder="<?php echo $pn."/".$total_pages; ?>" required>
<button onclick="go2Page();">Go</button>
</div>
</div>
</div>
</div>
<script>
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'qm.php?page='+pn;
}
/* start and end date- validation checks */
function check(){
var startdatea=document.getElementById("startdate").value;
var enddatea=document.getElementById("enddate").value;
if(Date.parse(startdatea)>Date.parse(enddatea)){
alert("Please select a different End Date.");
return false;
}
}
</script>
</body>
</html>
$_POST superglobal variable is populated by PHP when a POST HTTP request is processed. This is the case on the request for page 1.
However, your go2page() function is mutating location.href, which generates a GET HTTP request, and so does pagination links.
You should append your startdate and enddate params to the pagination URLs, to forward your params to the next/previous requests :
qm.php?page=<YOUR-PAGE-NUMBER>&startdate=<YOUR-START-DATE>&enddate=<YOUR-END-DATE>';
And use $_GET['startdate'] and $_GET['enddate] to retrieve those when processing GET requests.
More about $_POST https://www.php.net/manual/en/reserved.variables.post.php
More about GET AND POST HTTP requests : https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
There's an error in your isset($_POST['Search'])
your code:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
possible working solution:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
Though I didn't try it yet, but I assume this is the cause, pagination in page2 will not work since the code is not executed after the error which is the pagination for page2.
EDIT: The . fixes things.
echo "Start date : ".$startdate1", ";
is different than
echo "Start date : ".$startdate1.", ";
Add values of your $_POST inside links and use them as $_GET so you would use both.
$startdate1=$enddate1=null; //to hide notice
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
} else if (!empty($_GET['startdate']) && !empty($_GET['enddate'])){
$startdate1 = $_GET['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_GET['enddate'];
echo "End date : ".$enddate1;
}
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
For your need:
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1&startdate=".startdate1."&enddate=".$enddate1."'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."&startdate=".startdate1."&enddate=".$enddate1."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."&startdate=".startdate1."&enddate=".$enddate1."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."&startdate=".startdate1."&enddate=".$enddate1."'> >> </a></li>";
}
That would help you to move dates to next page.
You need to set it to all paging links. Also you can make extra if statement to not pass empty GET
EDIT:
As I already told: You need to set it to all paging links. Also you can make extra if statement to not pass empty GET (that includes javascript)
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'teztz.php?page='+pn+'&startdate=<?=startdate1;?>&enddate=<?=$enddate1;?>';
}
I am trying to insert in other table using for invoicing
I've tried to create insert function but it is not inserting into table and every time I click the page or even the input tag its always says localhost but empty.
Here is the form:
<form class="form-vertical" name="save" id="save" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group row">
<label for="inv_date" >Date</label>
<div class="col-sm-8">
<input type="date" class="form-control" autocomplete="off" id="inv_date" name="inv_date" required>
</div>
</div>
<div class="form-group row">
<label for="inv_num" >Inv Number</label>
<div class="col-sm-8">
<input type="number" class="form-control" autocomplete="off" id="inv_num" name="inv_num" required>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered" id="crud_table">
<tr>
<th width="30%">Item Name</th>
<th width="10%">Item Code</th>
<th width="45%">Description</th>
<th width="10%">Price</th>
<th width="5%"></th>
</tr>
<tr>
<td contenteditable="true" class="item_name"></td>
<td contenteditable="true" class="item_code"></td>
<td contenteditable="true" class="item_desc"></td>
<td contenteditable="true" class="item_price"></td>
<td></td>
</tr>
</table>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
</div>
<div align="center">
<button type="submit" name="save" id="save" class="btn btn-info">Save</button>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td contenteditable='true' class='item_name'></td>";
html_code += "<td contenteditable='true' class='item_code'></td>";
html_code += "<td contenteditable='true' class='item_desc'></td>";
html_code += "<td contenteditable='true' class='item_price' ></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var item_name = [];
var item_code = [];
var item_desc = [];
var item_price = [];
$('.item_name').each(function(){
item_name.push($(this).text());
});
$('.item_code').each(function(){
item_code.push($(this).text());
});
$('.item_desc').each(function(){
item_desc.push($(this).text());
});
$('.item_price').each(function(){
item_price.push($(this).text());
});
$.ajax({
url:"insert.php",
method:"POST",
data:{item_name:item_name,item_code:item_code, item_desc:item_desc, item_price:item_price},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
for(var i=2; i<= count; i++)
{
$('tr#'+i+'').remove();
}
}
});
});
});
</script>
and here is the insert page:
<?php
session_start();
//insert.php
require_once ('connect.php');
if((!empty($_POST['inv_date'])) && (!empty($_POST['inv_num']))){
$inv_date = $_POST["inv_date"];
$inv_num = $_POST["inv_num"];
$query = '';
$query = 'INSERT INTO invtran (inv_date, inv_num) VALUES ("'.$inv_date.'", "'.$inv_num.'")';
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(isset($_POST["item_name"]))
{
$item_name = $_POST["item_name"];
$item_code = $_POST["item_code"];
$item_desc = $_POST["item_desc"];
$item_price = $_POST["item_price"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($conn, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($conn, $item_code[$count]);
$item_desc_clean = mysqli_real_escape_string($conn, $item_desc[$count]);
$item_price_clean = mysqli_real_escape_string($conn, $item_price[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_desc_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO item(item_name, item_code, item_description, item_price)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_desc_clean.'", "'.$item_price_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($conn, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}else
{
echo 'All Fields are Required';
}
}
}
?>
It must be inserted in different table to call them out in different page.
instead of if(isset($_POST['item_name']))
I tried different approach like this:
if ($result) {
$j = 0;
$count = sizeof($_POST['po_qty']); // ive use the sizeof() to get the count of the rows
// Use insert_id property
$po_trans_id = $link->insert_id;
$user = $_SESSION["username"];
for ($j = 0; $j < $count; $j++) {
$query = "INSERT INTO request_po (item_name, item_code, item_description, item_price) VALUES (
'".$item_name[$j]."',
'".$item_code[$j]."',
'".$item_description[$j]."',
'".$item_price[$j]."');
I'm writing 2 queries and the first query is working fine but the 2nd query is not working. Please, Guide me.Thanks.
<table class="table table-bordered table-hover">
<form role="form" method="post" action="">
<div class="tablenav top">
<div class="alignleft actions bulkactions">
<label for="bulk-action-selector-top" class="screen-reader-text">Comment Action</label><select name="comment_status" id="bulk-action-selector-top">
<option value="" name="">Select Option</option>
<option value="Approve" name="Approve">Approve</option>
<option value="unapprove" name="unapprove" class="hide-if-no-js">Unapprove</option>
</select>
<input type="submit" name="submit" id="doaction" class="button action" value="Apply">
</div>
<br class="clear">
</div>
<thead>
<tr>
<th></th>
<th>Id</th>
<th>Author</th>
<th>Comments</th>
<th>Email</th>
<th>Author Url</th>
<th>Status</th>
<th>Date</th>
<th>Post Name</th>
<th>Edit</th>
<th>Delete</th>
<th>Reply</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM comments";
global $connection;
$select_comments = mysqli_query($connection, $query) or die('Could not look up user information; ' . mysqli_error($connection));
while ($row = mysqli_fetch_array($select_comments)) {
$comment_id = $row['comment_id'];
$comment_post_id = $row['comment_post_id'];
$comment_author = $row['comment_author'];
$comment_date = $row['comment_date'];
$comment_email = $row['comment_email'];
$comment_author_url = $row['comment_author_url'];
$comment_content = $row['comment_content'];
$comment_status = $row['comment_status'];
echo "<tr>
<td><input type='checkbox' name='check_list[]' value='$comment_id'></td>
<td>$comment_id</td>
<td>$comment_author</td>
<td>$comment_content</td>
<td>$comment_email</td>
<td>$comment_author_url</td>
<td>$comment_status</td>
<td>$comment_date</td>
</tr>";
}
if (isset($_POST['submit'])) {
global $connection;
global $errors;
$comment_status = $_POST['comment_status'];
$check_box = isset($_POST['check_list']) ? $_POST['check_list'] : '';
// error messages
$missingcheckbox = "<p><stong>Recored box not checked.Please check the checkbox.</strong></p>";
// for name feild
if (!$check_box) {
$errors .= $missingcheckbox;
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' . $errors . '</div>';
echo $resultMessage;
} else {
for ($i = 0; $i < count($_POST['check_list']); $i++) {
$id = $_POST['check_list'][$i];
if ($comment_status == 'Approve') {
$query = "UPDATE comments SET comment_status = 'approved' WHERE comment_id = $id";
} elseif ($comment_status == 'Unapprove') {
$query = "UPDATE comments SET comment_status = 'unapproved' WHERE comment_id = $id";
}
if ($approve_comments = mysqli_multi_query($connection, $query)) {
// header ("location: comments.php");
// exit;
$resultMessage = '<div class="alert alert-success">Data has been successfully Updated.<img src="../../assets/img/refresh.png" alt="Edit Client" title="Refresh" style="width:30px; height:30px; border:0;"></div>';
echo $resultMessage;
} else {
$resultMessage = '<div class="alert alert-warning">ERROR: Unable to excecute:' . $query . ' . ' . mysqli_error($connection) . '</div>';
echo $resultMessage;
}
}
}
}
?>
</tbody>
</table>
The first query is working fine but 2nd query is not working.I have problem in this code below:-
if($comment_status =='Approve'){
$query = "UPDATE comments SET comment_status = 'approved' WHERE comment_id = $id";
}elseif($comment_status =='Unapprove'){
$query = "UPDATE comments SET comment_status = 'unapproved' WHERE comment_id = $id";
}
Case matters when comparing two strings to be the same
<option value="unapprove"
^^^
and
elseif($comment_status =='Unapprove'){
^^^
$id its a variable and you are putting there as string. Example:
<?php
$a = "Hello ";
$b = $a . "World!"; // "Hello World!"
$a = "Hello ";
$a .= "World!"; // "Hello World!"
?>
You must do the same.