I have here a sample of shopping cart using php. I tried to modify it to what I need. What I add here is a search function using ajax/jquery. The search engine working but the problem is the add button isn't working. Why I can't add a item in the list? What I does here is separate the table in index.php into search.php so when I try to search only the item what I need is going to display in table. Any help will appreciate.
Search.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_POST['bid'])) {
$search = $mysqli->real_escape_string($_POST['bid']);
$search = preg_replace("/[^A-Za-z0-9 ]/", '', $search);
$search = $_POST['bid'];
$results = $mysqli->query("SELECT * from app WHERE item_name LIKE '%$search%' ORDER BY item_name ASC");
echo'<table id="tfhover" cellspacing="0" class="table-list" style="text-transform:uppercase;" border="1">
<thead>
<tr>
<th></th>
</tr>
</thead>';
echo'<tbody>';
if(($results->num_rows)>= 1){
while($obj = $results->fetch_object())
{
echo '<form method="post" action="cart_update.php">';
echo '<tr>
<td style="text-align:left;">'.$obj->item_name.'</td>
<td><button class="add_to_cart" style="font-size:9px;">Add</button></td>
</tr>';
echo '<input type="hidden" name="product_code" value="'.$obj->counter.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
}
echo "</tbody></table>";
}
if(($results->num_rows)<= 0){
echo '<div style="margin-left:360px;">No Results</div>';
}
}
?>
Index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<input type="text" name="bid" id="bid" placeholder="Search" style="text-transform:uppercase;width:300px;text-align:center;"/>
<div id="bid_result"></div>
<script type="text/javascript">
$(document).ready(function () {
function load(query) {
$.post('search.php', {
bid: query
}, function (search_bid) {
$('#bid_result').stop(true, true).fadeIn(200).html(search_bid);
}); //End ajax call
}
load($("#bid").val());
//Live search
$("#bid").on('keyup', function () {
//Input field value
load($(this).val());
}); //End on function
}); //End document.ready state
</script>
Cart_update.php
Here's my complete code of cart_update.php http://pastebin.com/1iDENLa0
<?php
session_start();
include_once("config.php");
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); // product code
$return_url = base64_decode($_POST["return_url"]); //return url
}
?>
Ok, i changed some parts of your code, can you check this code? It should submit.
<?php
echo '
<table id="tfhover" cellspacing="0" class="table-list" style="text-transform:uppercase;" border="1">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>';
if(($results->num_rows)>= 1) {
while($obj = $results->fetch_object()) {
echo '
<form method="post" action="cart_update.php">
<input type="hidden" name="product_code" value="'.$obj->counter.'" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="'.$current_url.'" />
<input type="submit" class="add_to_cart" value="Add" style="font-size:9px;"/>
</form>';
}
echo '</tr></td>';
}
echo "</tbody></table>";
?>
Related
currently I have created a system that can perform multiple delete actions for a list of data rows that fetch from a SQL database and display at dashboard_engineer.php. Each data row contains a delete button. Each row also has a checkbox that enables the user to delete selected data rows. At the bottom of the data rows, there's a button to delete all the selected data rows.
My problem is on multiple delete, lets say, if I select two data rows, (id 4 and 5) it will only delete one ID.
Below is my code
dashboard_engineer2.php
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$team = $_REQUEST['team'];
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid
WHERE ot_report.status = 'yes' AND ot_users.team_id = :team AND report_date BETWEEN :from
AND :to ORDER BY ot_report.report_id DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to,);
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "25%">Supervisor</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
}
else {
$color="color:green";
}
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value="'.$report_id.'"></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$row['report_date'].'</td>';
echo '<td>'.$row["fullname"].'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center" style='.$color.'><strong>'.$status.'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post" target="_blank">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo '</td>';
echo '<td align="center">';
echo "<form action = 'remove2.php' method = 'post' onClick=\"return confirm('Do you want to remove this reports?')\">";
echo '<input type = "hidden" name = "from" value = "'.$from.'">';
echo '<input type = "hidden" name = "to" value = "'.$to.'">';
echo '<input type = "hidden" name = "team" value = "'.$team.'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Remove</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td>';
echo "<form action = 'delete_selected.php' method = 'post'>";
echo '<input type="hidden" id="checkItem" name="check[]" value="'.$report_id.'">';
echo '<button type="submit" class="btn-danger btn-sm">DELETE</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
?>
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++){
$report_id = $checkbox[$i];
$sql = "UPDATE ot_report SET status = 'no' WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
Can anyone help me to solve this problem? Thanks
OK - the following is based upon the question's code but in order to build a working demo it has been generalised. The important thing here is the use of Javascript to maintain the list of IDs selected ( either by clicking the select-all checkbox or by clicking individual checkboxes. Please ignore the content generated in the form - the dates are spurious and meaningless to this example.
You could copy this and create a test page which should run OK - the PHP that generates the pseudo SQL is simply to display the statements that would be executed and not how it should be executed ( should be as per question, prepared statement )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( isset( $_POST['ids'] ) ){
$items=explode( ',', $_POST['ids'][0] );
foreach($items as $id){
$sql=sprintf('UPDATE ot_report SET status="no" WHERE report_id=%d',$id);
echo $sql . '<br />';
}
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<table>
<?php
for( $i=1; $i <= 10; $i++ ){
/* example data for dates... */
$hrs=mt_rand(1,24);
$mins=mt_rand(0,60);
$secs=mt_rand(0,60);
$month=mt_rand(1,12);
$day=mt_rand(1,28);
$year=mt_rand(2000,2020);
$from=date('y-m-d',mktime($hrs,$mins,$secs,$month,$day,$year));
$to=date('y-m-d',mktime($hrs+3,$mins+20,$secs,$month,$day,$year));
printf('
<tr>
<td><input type="checkbox" name="check[]" value="%1$d" /></td>
<td>Some data %1$d</td>
<td>
<form method="post">
<input type="hidden" name="from" value="%2$s" />
<input type="hidden" name="to" value="%3$s" />
<input type="hidden" name="id" value="%1$d" />
<input type="submit" />
</form>
</td>
</tr>', $i, $from, $to );
}
?>
</table>
<form method='post'>
<input type='checkbox' name='selectall' value='Select-All' />
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='Update selected' />
</form>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
</body>
</html>
Will generate something akin to:
UPDATE ot_report SET status="no" WHERE report_id=10
UPDATE ot_report SET status="no" WHERE report_id=8
UPDATE ot_report SET status="no" WHERE report_id=6
UPDATE ot_report SET status="no" WHERE report_id=4
Quickly trying to adapt this example with your code :
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from=$_REQUEST['from'];
$to =$_REQUEST['to'];
$team=$_REQUEST['team'];
$result='';
$query="SELECT * FROM ot_report
LEFT JOIN ot_users ON ot_report.badgeid=ot_users.badgeid
WHERE ot_report.status='yes' AND ot_users.team_id=:team AND report_date BETWEEN :from AND :to
ORDER BY ot_report.report_id DESC";
$sql=$conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to);
$sql->execute();
if($sql->rowCount() > 0){
echo'
<table class="table-bordered" width="100%">
<thead>
<tr>
<th width="10%"><input type="hidden" name="selectall" value="Select-All">All</th>
<th width="3%">id</th>
<th width="15%">Date</th>
<th width="25%">Supervisor</th>
<th width="30%">Task Name</th>
<th width="10%">Status</th>
<th colspan="2" width="7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
} else {
$color="color:green";
}
$report_id=$row["report_id"];
echo'
<tr>
<td><input type="checkbox" name="check[]" value="'.$report_id.'"></td>
<td>'.$report_id.'</td>
<td>'.$row['report_date'].'</td>
<td>'.$row["fullname"].'</td>
<td>'.$row["task_name"].'</td>
<td align="center" style='.$color.'><strong>'.$status.'</strong></td>
<td align="center">
<form action="view_task/view_task.php" method="post" target="_blank">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-primary">View</button>
</form>
</td>
<td align="center">
<form action="remove2.php" method="post" onsubmit="return confirm(\'Do you want to remove this reports?\')">
<input type="hidden" name="from" value="'.$from.'">
<input type="hidden" name="to" value="'.$to.'">
<input type="hidden" name="team" value="'.$team.'">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-danger">Remove</button>
</form>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td>
<form action="delete_selected.php" method="post">
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='DELETE' />
</form>
</td>
</tr>';
}
}
?>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
and
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox=explode( ',', $_POST['ids'][0] );
for($i=0;$i < count($checkbox); $i++){
$report_id=$checkbox[$i];
$sql="UPDATE ot_report SET status='no' WHERE report_id=:report_id";
$query=$conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
I'm trying to develop a small "To Do List" application. The data for the app is stored in a database, and it needs to perform all CRUD operations. As it is right now, Select, Insert, and Delete work just fine. I'm stuck on updating though. The index.php page is shown below:
<?php
session_start();
require_once 'connect.php';
if (isset($_POST['DeleteTask'])) {
$sqldelete = "DELETE FROM Tasks WHERE dbTaskID = :bvTaskID";
$stmtdelete = $db->prepare($sqldelete);
$stmtdelete->bindValue(':bvTaskID', $_POST['taskID']);
$stmtdelete->execute();
echo "<div>Task successfully deleted</div>";
}
if (isset($_POST['theSubmit'])){
echo '<p>New task added</p>';
$formfield['ffTaskName'] = trim($_POST['taskName']);
$formfield['ffTaskDue'] = trim($_POST['taskDue']);
if(empty($formfield['ffTaskName'])){$errormsg .= "<p>Task field is empty.</p>";}
if(empty($formfield['ffTaskDue'])){$errormsg .= "<p>Deadline field is empty.</p>";}
if ($errormsg != "") {
echo "<div class='error'><p>Please fill out all fields before submitting.</p>";
echo $errormsg;
echo "</div>";
} else {
try {
$sqlinsert = 'INSERT INTO Tasks (dbTaskName, dbTaskDue, dbTaskDone)
VALUES (:bvTaskName, :bvTaskDue, :bvTaskDone)';
$stmtinsert = $db->prepare($sqlinsert);
$stmtinsert->bindValue(':bvTaskName', $formfield['ffTaskName']);
$stmtinsert->bindValue(':bvTaskDue', $formfield['ffTaskDue']);
$stmtinsert->bindValue(':bvTaskDone', 0);
$stmtinsert->execute();
echo "<div><p>There are no errors. Thank you.</p></div>";
} catch(PDOException $e){
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
$sqlselect = "SELECT * from Tasks";
$result = $db->prepare($sqlselect);
$result->execute();
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do Application</title>
</head>
<body>
<h1><u>To-Do List</u></h1>
<table border>
<tr>
<th>Task</th>
<th>Deadline</th>
<th>Status</th>
<th>Complete</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php
while ($row = $result->fetch()) {
if ($row['dbTaskDone'] == 0) {
$status = "Unfinished";
} else {
$status = "Finished";
}
echo '<tr><td>' . $row['dbTaskName']
. '</td><td>' . $row['dbTaskDue']
. '</td><td>' . $status;
/*if ($status == "Unfinished"){
echo '</td><td>';
echo '<form action="'. $_SERVER['PHP_SELF'] . '" method="post">';
echo '<input type="hidden" name="taskID" value"' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="CompleteTask" value="Complete Task">';
echo '</form>';
}*/
echo '</td><td>';
echo '<form action="updateTask.php" method="post">';
echo '<input type="hidden" name="taskID" value="' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="EditTask" id="EditTask" value="Edit Task">';
echo '</form></td><td>';
echo '<form action="'. $_SERVER['PHP_SELF'] . '" method="post">';
echo '<input type="hidden" name="taskID" value="' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="DeleteTask" value="Delete Task">';
echo '</td></tr>';
}
?>
</table>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="toDoForm">
<fieldset><legend>New Task</legend>
<table>
<tr>
<th>Task</th>
<td><input type="text" name="taskName" id="taskName"
value="<?php echo $formfield['ffTaskName']; ?>"></td>
</tr><tr>
<th>Deadline</th>
<td><input type="text" name="taskDue" id="taskDue"
value="<?php echo $formfield['ffTaskDue']; ?>"></td>
</tr>
</table>
<input type="submit" name = "theSubmit" value="Add Task">
</fieldset>
</form>
</body>
</html>
Each record displays an "Edit" button that grabs the PK from the "Tasks" table and sends it to the updateTask.php page:
<?php
require_once 'connect.php';
$errormsg = "";
if (isset($_POST['EditTask']) ) {
$formfield['ffTaskID'] = $_POST['taskID'];
$sqlselect = "SELECT * FROM Tasks WHERE dbTaskId = :bvTaskID";
$result = $db->prepare($sqlselect);
$result->bindValue(':bvTaskID', $formfield['ffTaskID']);
$result->execute();
$row = $result->fetch();
if( isset($_POST['theEdit']) )
{
$formfield['ffTaskID'] = $_POST['taskID'];
$formfield['ffTaskName'] = trim($_POST['taskName']);
$formfield['ffTaskDue'] = trim($_POST['taskDue']);
if(empty($formfield['ffTaskName'])){$errormsg .= "<p>Task field is empty.</p>";}
if(empty($formfield['ffTaskDue'])){$errormsg .= "<p>Deadline field is empty.</p>";}
if ($errormsg != "") {
echo "<div class='error'><p>Please fill out all fields before submitting.</p>";
echo $errormsg;
echo "</div>";
} else {
try
{
$sqlUpdate = "UPDATE Tasks SET dbTaskName = :bvTaskName,
dbTaskDue = :bvTaskDue
WHERE dbTaskID = :bvTaskID";
$stmtUpdate = $db->prepare($sqlUpdate);
$stmtUpdate->bindvalue(':bvTaskName', $formfield['ffTaskName']);
$stmtUpdate->bindvalue(':bvTaskDue', $formfield['ffTaskDue']);
$stmtUpdate->bindvalue(':bvTaskID', $formfield['ffTaskID']);
$stmtUpdate->execute();
}
catch(PDOException $e)
{
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do Application</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="editForm">
<fieldset><legend>Edit Task</legend>
<table>
<tr>
<th>Task</th>
<td><input type="text" name="taskName" id="taskName"
value="<?php echo $row['dbTaskName'];?>" ></td>
</tr><tr>
<th>Deadline</th>
<td><input type="text" name="taskDue" id="taskDue"
value="<?php echo $row['dbTaskDue']; ?>"></td>
</tr>
<tr>
<th>Submit Changes</th>
<input type="hidden" name="taskID" value="<?php echo $_formfield['ffTaskID']; ?>">
<td><input type="submit" name="theEdit" value="Submit Changes">
</table>
</fieldset>
</form>
</body>
</html>
The Name and Deadline fields populate appropriately based on the PK value passed from the last page. However, whenever I press the "Submit Changes" button, the update doesn't seem to execute. The page just refreshes and I see the table data remains unchanged in the database.
Solved the problem!
There were several issues that I discovered.
1.) In updateTask.php, I had the second if-statement nested within the first one. So it was running the update query as the page loaded, with no change to the data. So the 'theEdit' button did nothing since since it required the previous if statement's condition to run.
2.) The formfield 'ffTaskID' at the bottom of the form on updateTask.php to be passed on the 'theEdit' button press was typed incorrectly.
$_formfield
..should have been..
$formfield
At this point, the update query functions properly.
3.) The issue with the 'Edit' buttons has been fixed. Though I honestly can't say for certain how it was fixed. It may have been linked with the first part of the problem. So when that was fixed, so was this.
Either way, all seems to be functioning as it should. Thanks again to everyone who commented and helped.
I got a function.php which is in inc/function. This function contains a table. This table is generated in an MySQL statement.
My idea is quite easy - the user is able to go through the table with a next button and a back button.
Here is my code:
<div class="container-fluid">
<form action="fda.php" method="post">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<p>Bitte beantworten Sie die folgenden Fragen:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Nr.</th>
<th width="250">Frage</th>
<?php tbl_description() ?>
</tr>
</thead>
<tbody>
<?php tbl_showPage() ?>
</tbody>
</table>
</div>
<div class="col-md-6 col-md-offset-3 text-center">
<form action="functions.php" method="post">
<input type="submit" name="back" value="Zurück" id="back" class="btn btn-default">
<input type="submit" name="go" value="Weiter" id="go" class="btn btn-default">
<!--<input type="submit" value="FDA auswerten" class="btn btn-default">-->
</div>
</div>
</form>
</div>
this is the part from the fda.php file! Everything is working cool except the increase of the mysql statement which is in the function.php.
While clicking on next the statement should be "refreshed" and show me the 2nd page of the table. Its like an questionaire.
This is the code of the function php.
function tbl_showPage(){
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$connection=mysqli_connect($mysqlhost, $mysqluser, $mysqlpwd) or die ("Verbindungsversuch fehlgeschlagen");
mysqli_select_db($connection, $mysqldb) or die("Konnte die Datenbank nicht waehlen.");
if(isset($_POST['go']))
{
$page++;
}
elseif($_POST['back'])
{
$page--;
}
//if(isset($page)){
if($page<1)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='1'";
}
elseif($page>9)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='9'";
}
else
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
}
//}
$quest_query = mysqli_query($connection, $sql_tbl_questions) or die("Anfrage nicht erfolgreich");
$i = 0;
while ($question = mysqli_fetch_array($quest_query)) {
$i++;
echo '<tr>';
echo '<th>'.$i.'</th>';
echo '<th>'.$question['question'].'</th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="0" required></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="2.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="7.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="10"></th>';
echo '</tr>';
$dimensions = $question['dimension'];
}
echo '<tr>';
echo '<th></th>';
echo '<th>Kommentar/Ihre Anmerkung</th>';
echo '<th class="text-center" colspan=5><textarea rows=3 cols=50 name="Kommentar"></textarea></th>';
echo '</tr>';
echo '<input type="hidden" name="gesamt" value="'.$i.'">';
echo '<input type="hidden" name="dimensions" value="'.$dimensions.'">';
echo '<input type="hidden" name="size" value="'.$_POST['size'].'">';
echo '<input type="hidden" name="branche" value="'.$_POST['branche'].'">';
}
Maybe I am missing something? I really hope someone can help me!
I see two problems here:
The form is submitting both 'back' and 'go' variables, regardless of which one was clicked.
The PHP script is not tracking the $page variable across page loads. (If it is not tracked, it will re-initialize to 0 every time the page is loaded.)
Try having your form tell the PHP script which page to load:
<form action="functions.php" method="post">
<button type="submit" name="page" value="<?php echo $page - 1; ?>">Zurück</button>
<button type="submit" name="page value="<?php echo $page + 1; ?>">Weiter</button>
</form>
Then in your PHP, you would just check for the value of $_POST['page']
if(!empty($_POST['page'])) {
$page = intval($_POST['page']);
} else {
$page = 1;
}
You will also need to make the $page variable visible from the fda.php script into the function.php script. You could do that using global $page; next to your mysql variables. (That's not an optimal or clean way of doing things, but it would be the easiest addition to your code.)
I have a script that counts how many records it sees on the page :
<script>
document.write(document.getElementById('moon').rows.length-1);
document.write (' ');
document.write (' of ');
document.write (' ');
document.write(document.getElementById('moon').rows.length-1);
document.write (' pages');
</script>
How would I use this to paginate 10 records at a time?
Perhaps using a styling such as display:none or something and then linking to these hidden divs on the "page" count.
Thanks
Edit:
I have tried to use a PHP Mysql Query to do this with num_rows, but it always throws out errors even when I am getting data!
2nd EDIT
Ok, I am pulling the information and displaying it with:
<table class="std" id="moon" border="0" cellpadding="0" cellspacing="0">
<tr>
<?php
$pcounter = 1;
$userID = LedDB::getInstance()->get_user_id_by_name($_SESSION['user']);
$presult = LedDB::getInstance()->get_page_by_campaign_id($campaignID);
$i=0;
while ($row = mysqli_fetch_array($presult)):
$style = "";
if($i%2==0)
{
$style = 'style="background-color: #EFEFEF"';
}
echo "<tr ".$style.">";
echo "<td class='camp' style='padding-left:10px;'><b><a href='editPage.php?pageID=" .htmlentities($row['pid']) ."&campaignID=" .htmlentities($row['campaignid']) ."' class='camp'> Page" . $pcounter . "</a></b></td>";
echo "<td style='padding-left:10px;'></td>";
echo "<td style='padding-left:10px;'></td>";
echo "<td></td>";
echo "<td></td>";
$pageID = $row['pid'];
//The loop is left open
?>
<td>
<div class="buttons">
<form name="editPage" action="editPage.php" method="GET">
<input type="hidden" name="campaignID" value="<?php echo $campaignID ?>"/>
<input type="hidden" name="pageID" value="<?php echo $pageID ?>"/>
<button type="submit" name="editPage" value="Edit" class="blue" >
<img src="images/edit.png" width="20" height="20"></button>
</form>
</div>
</td>
<td>
<form name="deletePage" action="deletePage.php" method="POST">
<input type="hidden" name="pageID" value="<?php echo $pageID; ?>"/>
<div class="buttons">
<button type="submit" name="deletePage" value="Delete" class="negative">
<img src="images/delete_x.png" width="20" height="20"></button>
</div>
</form>
</td>
<?php
echo "</tr>\n";
$pcounter++;
$i++;
endwhile;
mysqli_free_result($presult);
?>
</table>
Where $presult = LedDB::getInstance()->get_page_by_campaign_id($campaignID); is this:
public function get_page_by_campaign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid,campaignid,message_text,message FROM pages WHERE campaignid =" . $campaignID );
}
Whenever I try to wrap this in a pagination class, it either returns a 0 value or just bombs out my entire script with sql_num_rows() errors...
That is the reason I thought javascript pagination would be the best solution in this case.
There are several examples on the web to get you started, thats where I'd start:
http://www.phpclasses.org/search.html?words=pagination&x=0&y=0&go_search=1
http://www.phpsnaps.com/snaps/view/php-pagination-class/
http://www.phpbuilder.com/board/showthread.php?t=10283679
http://phpsense.com/2007/php-pagination-script/
I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.