This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 11 months ago.
Good day, I've seen a couple of threads with similar questions but I can't seem to implement the suggestions on my practice project.
is there any way I can add a function where my selected items can be deleted at once?
Here are my codes.
select.php
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
$output = '';
$sql = "SELECT * FROM appointments ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="5%">Checkbox</th>
<th width="10%">Id</th>
<th width="40%">Name</th>
<th width="40%">Email</th>
<th width="40%">Address</th>
<th width="10%">phoneNumber</th>
<th width="10%">appointmentTime</th>
<th width="10%">appointmentDate</th>
<th width="50%">message</th>
<th width="10%">delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
</td>
<td><input type="checkbox" /></td>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="email" data-id2="'.$row["id"].'" contenteditable>'.$row["email"].'</td>
<td class="address" data-id2="'.$row["id"].'" contenteditable>'.$row["address"].'</td>
<td class="phoneNumber" data-id2="'.$row["id"].'" contenteditable>'.$row["phoneNumber"].'</td>
<td class="appointmentTime" data-id2="'.$row["id"].'" contenteditable>'.$row["appointmentTime"].'</td>
<td class="appointmentDate" data-id2="'.$row["id"].'" contenteditable>'.$row["appointmentDate"].'</td>
<td class="message" data-id2="'.$row["id"].'" contenteditable>'.$row["message"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-danger btn_delete">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '<tr>
<td colspan="10"><center><p style="color:red">No Data Found</p></center></td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
Here's the delete function for a single row.
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
$sql = "DELETE FROM appointments WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
Here's my display page.
<?php
require("config.php");
if(empty($_SESSION['user']))
{
header("Location: success.php");
die("Redirecting to index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Simple Sidebar - Start Bootstrap Template</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/simple-sidebar.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div id="wrapper">
<!-- Sidebar -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand">
<a href="#">
Hope Medi Clinic
</a>
</li>
<li>
Logout
</li>
<li>
Main Website
</li>
</ul>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Appointments</h3><br />
<div id="live_data"></div>
Toggle Menu
</div>
</div>
<!-- /#page-content-wrapper -->
</div>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
/* ............. */
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.email', function(){
var id = $(this).data("id2");
var email = $(this).text();
edit_data(id, email, "email");
});
$(document).on('blur', '.address', function(){
var id = $(this).data("id2");
var address = $(this).text();
edit_data(id, address, "address");
});
$(document).on('blur', '.phoneNumber', function(){
var id = $(this).data("id2");
var phoneNumber = $(this).text();
edit_data(id, phoneNumber, "phoneNumber");
});
$(document).on('blur', '.appointmentTime', function(){
var id = $(this).data("id2");
var appointmentTime = $(this).text();
edit_data(id, appointmentTime, "appointmentTime");
});
$(document).on('blur', '.appointmentDate', function(){
var id = $(this).data("id2");
var appointmentDate = $(this).text();
edit_data(id, appointmentDate, "appointmentDate");
});
$(document).on('blur', '.message', function(){
var id = $(this).data("id2");
var message = $(this).text();
edit_data(id, message, "message");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
</body>
</html>
It will be cleaner and more professional to send an array of ids to your php file as suggested by earlier answers:
<input name="ids[]" value="<?php echo $id; ?>" type="checkbox">
...then make just one trip to the database to delete multiple rows.
if (
empty($_POST['ids'])
// || array_filter($_POST['ids'], function($v) { return !ctype_digit($v); })
) {
exit('Missing/Invalid data submitted'); // be deliberately vague
}
$connect = new mysqli("localhost", "root", "root", "appointments");
$count = count($_POST['ids']);
$stmt = $connect->prepare(
sprintf(
"DELETE FROM appointments WHERE id IN (%s)",
implode(',', array_fill(0, $count, '?')) // e.g if 3 ids, then "?,?,?"
)
);
$stmt->bind_param(str_repeat('i', $count), ...$_POST['ids']);
$stmt->execute();
printf('Deleted %d row(s)', $stmt->affected_rows());
This resembles a similar post of mine: SELECT with dynamic number of values in IN()
I'm not sure exactly how you are sending the data from the HTML to the PHP page in this example, so I will give you a generic simple implementation and hopefully you can figure out how to work it into your project.
HTML:
Using checkboxes, you can send multiple values as an array to a php script like so.
<form action="delete.php" method="POST">
<input name="delete[]" value="id_of_row" type="checkbox">
<input name="delete[]" value="id_of_another_row" type="checkbox">
<button type="submit">Submit</button>
</form>
This will send an array of whatever is in the value attribute of each box that is checked. You would then be able to delete every row that was checked with the following php script.
PHP:
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
foreach($_POST['delete'] as $id){
$sql = "DELETE FROM appointments WHERE id = '" . $id . "';
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
}
?>
This should be what you need to somehow implement into your existing project so that you can delete multiple rows at once.
You should be using array for this.
<td><input type="checkbox" name='check[]' value=".$row['id']." /></td>
and in delete function you should be doing something like this.
<?php
$connect = new mysqli("localhost", "root", "root", "appointments");
$totalCheckboxChecked = sizeof($_POST['check']);
for($i=0;$i<$totalCheckboxChecked;$i++)
{
$idToDelete = $check[$i];
$sql = "DELETE FROM appointments WHERE id = $idToDelete";
$result=$connect->query($sql);
}
Related
I'd like to get an interactive block in my page that onchange of one of the 3 search fields only reloads the div 'mydata' and reruns the query with a new filter. I know it probably can be done with ajax but i'm stuck in finding the right piece of code.
Here's my testcode
Main php file users2.php:
<head>
<title>Test</title>
<script src="../jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script src="../jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script>
$.ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?id=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<?PHP
include '../conf/config.inc.php';
include 'users_functions2.php';
?>
</body>
And here the include file users_functions2.php:
<?php
echo "<div id='mydata'>";
echo "<table><tr><th>ID</th><th>Name</th><th>City</th></tr>";
echo "<tr>";
echo "<td><input type=text placeholder='search' name=search_id</td>";
echo "<td><input type=text placeholder='search' name=search_name</td>";
echo "<td><input type=text placeholder='search' name=search_city</td>";
echo "</tr>";
$sql="select id, name, city from users;";
if (isset($_GET['search_name'])) { $sql .= "WHERE vo_name LIKE \"%".$_GET['search_name']."%\""; }
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
echo "<tr><td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['city']."</td></tr>";
}
echo "</table>";
echo "</div>";
?>
Hope Chris is ok with this, i'd like my question being answered with a working example:
File 1:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?search_name=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th><th>Name</th><th>City</th>
</tr>
<tr>
<th><input type=text placeholder='search' name=search_id></th>
<th><input type=text placeholder='search' id='search_name' name=search_name></th>
<th><input type=text placeholder='search' name=search_city></th>
</tr>
</thead>
<tbody id="mydata">
<?PHP
include 'users_functions2.php';
?>
</tbody>
</table>
</div>
</body>
File 2:
<?php
include '../conf/config.inc.php';
$sql="SELECT id, `name`, city FROM users";
$search_name = filter_input(INPUT_GET, 'search_name');
if ($search_name) {
$sql .= " WHERE vo_name LIKE \"%$search_name%\"";
}
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
extract($row);
echo "<tr><td>$id</td><td>$name</td><td>$city</td></tr>";
}
?>
In my index.php I am fetching data from the database. I put an edit button on that and I have used a datatable to view data information in this form. I have four field: Name, Age, Email, Update through mysqli_fetch_array I have fetched the data.
This is the index.php file:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
// using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
<link rel="stylesheet" href="DataTables/datatables.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/dataTables.bootstrap.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/jquery.dataTables.css" type="text/css">
<script src="DataTables/datatables.js"></script>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/datatable.js"></script>
<script src="DataTables/DataTables/js/dataTables.bootstrap.js"></script>
<script src="DataTables/DataTables/js/jquery.dataTables.js"></script>
</head>
<body>
Add New Data<br/><br/>
<table id="datatable" class="display" width='100%' border=0>
<thead>
<tr bgcolor='#CCCCCC'>
<td>Name</td>
<td>Age</td>
<td>Email</td>
<td>Update</td>
</tr>
</thead>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
//$action=$_POST["action"];
//if($action=='showroom')
{
$result = mysqli_query($mysqli, "SELECT * FROM users ORDER BY id DESC");
while ($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $res['name'] . "</td>";
echo "<td>" . $res['age'] . "</td>";
echo "<td>" . $res['email'] . "</td>";
echo "<td>Edit | Delete</td>";
}
}
?>
</table>
</body>
</html>
This is my edit.php file. First I check empty fields, after that I run updating the table query redirecting to the display page. In our case, it is index.php then getting id from url, selecting data associated with this particular id, fetching data through mysqli_fetch_array .
<?php
// including the database connection file
include_once("config.php");
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if (empty($name) || empty($age) || empty($email)) {
if (empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if (empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if (empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while ($res = mysqli_fetch_array($result)) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age; ?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email; ?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id']; ?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Finally, this is my edit.js file. In this file I try to do edit the form through AJAX, but I can't find where I doing mistakes.
<script>
$(document).ready(function (e) {
$('#update').click(function (event)
{
event.preventDefault();
$.ajax({
data: $('form').serialize(),
url: "edit.php", //php page URL where we post this data to save in database
type: 'POST',
success: function (strMessage) {
$('#message').text("strMessage");
}
})
});
});
</script>
You are doing edit and update on same file so you have to add condition on file. change your code as below:
edit.php
<?php
// including the database connection file
include_once("config.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if(empty($name) || empty($age) || empty($email)) {
if(empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
What I want to be able to do:
I have a page setup so that a table is populated with values from the database. I also generate a button for each of the rows on the table. The button is connected to the database to a field called status. It is initially at 0. When the button is clicked, I want to be able to update this value by incrementing it by 1.So after the button is clicked on the webpage, the database status value is incremented by 1.
I have tried using AJAX for this, but I havent seemed to have much luck.
view.php (Where the table is populated from the database)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>View</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
<?php
include 'php/connect.php';
include 'php/status.php';
function getStatus($num){
$status = "";
switch ($num) {
case ($num == 0):
$status = "Pending";
case ($num == 1):
$status = "Completed";
default:
$status = "Pending";
}
return $status;
}
?>
<div class="container">
<div class="row">
<div class="col-md-12 center-block">
<h1>View the Commissions</h1>
<div class="panel panel-default">
<div class="panel-heading">Commissions</div>
<div class="panel-body">
<p></p>
</div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Alias</th>
<th>Description</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect, "SELECT * FROM orders") or die(mysql_error());
while ($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<th scope=\"row\">";
echo $row['orderID'];
echo "</th>";
echo "<th>".$row['alias']."</th>";
echo "<th>".$row['description']."</th>";
echo "<th>$".$row['price']."</th>";
echo "<th><button type=\"button\" class=\"btn btn-default btn-info\" name=\"" .$row['orderID']. "\">".getStatus($row['status'])."</button></th>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
</script>
</html>
As you can see, for each row in the database the table is populated. Here is an image of the webpage:
I did have this code for the AJAX. It did give me the correct output in the console of the browser, but I wasnt able to get this value into the process.php page
$.ajax({
url: 'php/process.php',
type: 'POST',
data: {
orderID: obj.id
},
success: function (data) {
console.log(data);
}
});
How would I have it so that as soon as the button is clicked, it updates the value and refreshes the page. Any help would be greatly appreciated
TLDR; When I click the "Pending" button, a value in the database is incremented by 1.
Your getStatus() function didn't have break statement. for simple POST use $.post. I have added .status class to your button to use it as selector with jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>View</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
<?php
include 'php/connect.php';
include 'php/status.php';
// fixed this function by adding break and removing $num from case statement
function getStatus($num)
{
$status = "";
switch ($num) {
case 0:
$status = "Pending";
break;
case 1:
$status = "Completed";
break;
default:
$status = "Pending";
}
return $status;
}
?>
<div class="container">
<div class="row">
<div class="col-md-12 center-block">
<h1>View the Commissions</h1>
<div class="panel panel-default">
<div class="panel-heading">Commissions</div>
<div class="panel-body">
<p></p>
</div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Alias</th>
<th>Description</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect, "SELECT * FROM orders") or die(mysql_error());
while ($row = mysqli_fetch_array($query)) : ?>
<tr>
<th scope="row"><?php echo $row['orderID']; ?></th>
<th><?php echo $row['alias']; ?></th>
<th><?php echo $row['description']; ?></th>
<th><?php echo $row['price']; ?></th>
<th>
// added .status class here
<button type="button" class="btn btn-default btn-info status"
name="<?php echo $row['orderID']; ?>"><?php echo getStatus($row['status']); ?></button>
</th>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
// the AJAX for updating the status
$('.status').on('click', function () {
var id = $(this).attr('name');
var btn = $(this);
$.post('php/process.php', {orderId: id}, function (response) {
var res = JSON.parse(response);
if (res.results == true) {
btn.html('Completed');
}
})
})
</script>
</html>
In php/process.php
<?php
include 'php/connect.php';
if (isset($_POST['orderId'])) {
$orderId = $_POST['orderId'];
$sql = "UPDATE `orders` SET `status`= 1 WHERE `orderID` = $orderId";
if (mysqli_query($connect, $sql)) {
echo json_encode(['results' => true]); // when update is ok
}else {
echo json_encode(['results' => false]); // when update fail
}
}
So, I think I may be in over my head. I've looked around on here for a quite some time but have not been able to find something that will help me.
I am trying to build a display order from, similar to what you would see in a restaurant or fast food, that automatically and smoothly updates when a new entry has been entered into the MySQL table.
I tryed using AJAX but I could not get it to work
Main PHP page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/fulfillment.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
</head>
<body>
<div class="container">
<h1>Orders</h1>
<p>Area that displays all of the active and past orders.</p>
<div align="right">
<input id="toggle-event" type="checkbox" checked data-toggle="toggle" data-on="Active" data-off="Past">
</div>
<!-- Active Orders -->
<?php
include '../connect.php';
//get information form tblOrder
$sql = "SELECT * FROM tblOrder WHERE Filled=0";
$result = $db->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
<!-- Build the table -->
<h2>Active</h2>
<table ID = "myTable" class="table table-striped">
<thead>
<tr>
<th>Order Number</th>
<th>User ID</th> <!-- will turn to user name later down the road -->
<th>Food</th>
<th>Pick Up Time</th>
<th>Filled</th>
</tr>
</thead>
<tbody>
<?php
// run though tblOrders
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//assign all of the values
$OrderNumber = $row["Order_Number"];
$FoodID = $row["F_ID"];
$DrinkID = $row["D_ID"];
$UserID = $row["User_ID"];
$Filled = $row["Filled"];
$RequestTime = $row["Request_Time"];?>
<!-- out put each line of the value -->
<tr>
<td><?php echo $OrderNumber; ?></td>
<td><?php echo $UserID; ?></td> <!-- switch to name once it is avalible ->
<td><!-- put food order here --></td>
<td><?php echo $RequestTime; ?></td>
<td><input type="button" class="btn btn-default" value="Complete"onclick="toPast(this, <?php echo $OrderNumber?>)"/></td>
</tr>
<?php
}
}
//close the data connection
$db->close();
?>
</tbody>
</table>
JavaScript
function toPast(btn, ONum) {
var dataString = 'OrderNumber=' + ONum + '&UpdateNumber=' + '1';
$.ajax({
type: "POST",
url: "update_sucess.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
});
}
Could anyone point me in the right direction or know someplace has a "how-to" on how to do this that I could read?
I'm trying to update the two locked textboxes with information that I get from my database. I enter a phone number in the "Telefon" checkbox, and I want it to get the firstname and lasttname for that phone number. Which works by the way, but it's not the way I want it. I want the information to be automatically put into the textboxes without refreshing the page. and for some odd reason my code got split in two here. I've tried to look for a solution for hours. I'm very new to coding, and I would love some help!
<?php
SESSION_START();
$output = NULL;
if(isset($_POST['btn_checkTelefon'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$fornavnoutput_Database = $rows['Fornavn'];
$etternavnoutput_Database = $rows['Etternavn'];
}
echo '<script type = "text/javascript">';
echo 'function sayHi() {';
echo 'val1 = document.getElementById("telefon_Input").value;';
echo 'if(val1 == "") {';
echo ' alert("Vennligst skriv inn ditt telefon nummer!");';
echo '}';
echo 'if(val1 !== "") { ';
echo ' document.getElementById("check_Fornavn").value = "<?php echo $fornavnoutput_Database?>";';
echo ' document.getElementById("check_Etternavn").value = "<?php echo $etternavnoutput_Database?>";';
echo '}';
echo '}';
echo '</script>';
} else {
$output = "No results";
}
}
$fornavnoutput_Database2 = "Fornavn";
$etternavnoutput_Database2 = "Etternavn";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
</script>
<script type = "text/javascript"></script>
<title></title>
</head>
<body>
<?php
include 'connectdb.php';
?>
<form name="form1" action="">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="Valgt skap" disabled value= <?php
if(isset($_POST["radios"])){
echo $_POST["radios"];
} else {
//header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button type="button" name ="btn_checkTelefon" id="sjekkTelefon" onclick = "sayHi()">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
</form>
<?php echo $output; ?>
</body>
You need to use AJAX for this. Example $.ajax() -> shortcuts $.post(), $("id").load("url"), ... Look it up a lot in depth explanation about these on stackoverflow.
Please never mix JavaScript with php.
Use it in separate file.
Edit: So have you fixed it yet?
The easier way to load paged dynamicaly is with load method + actions. $.post is used if you need to do something with returned data from php. I will give you example of load.
I will give a proper example how to code.
Universal function for a link that look at href value and load HTML parts (form in this case) from PHP dynamicaly to your page, you do need to implement actions or just call your ordinary page if you have only one default action there. I use jQuery library here. This script must be in separate file else it will work but you will get a sync warning in your console.
$(function() {
$('a').on("click", function(e) {
e.preventDefault();
e.stopPropagation();
var URL = $(this).attr('href');
$('body').load(URL, 'form');
})
})
php example
prefered showsomethingfunction in separate file like showfunctions.php
function myLinks() {
echo "<a href='index.php?action=showsomething'>showsomething</a>"
}
index.php + included showfunctions.php
<?php
myLinks();
if(isset($_GET["action"]){
// do your ordinary thing like open connection with database.
switch($_GET["action"]))
{
case "showsomething":
//show showsomething() function with html
break;
//further you can add more action instead of showsomething if you have several links
}
//close database.
}
?>
You need to separate your code else it will be a mess if it gets even more complicated. HTML code must be ONLY in showfunctions.php for example in function to call for actions.
Code is not tested but I think it will work. This code will also work without javascript but then it will just reload pages.
You have to use jQuery $.post() for that.
first You have to create php file which will process Your data.
For example lets create file query.php with the following content:
<?php
if(isset($_POST['telefon_Search'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
$row = $resultSet->fetch_assoc();
echo json_encode($row);
}
}
next on Your page You have to create function which will send phone number to our query.php file and which will return Name and Surname if they exist.
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
var user = $.parseJSON(data);
$('#check_Fornavn').val(user.Fornavn);
$('#check_Etternavn').val(user.Etternavn);
});
});
and complete html will looks like:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title></title>
</head>
<body>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button name ="btn_checkTelefon" id="sjekkTelefon">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
$('#check_Fornavn').val(data.Fornavn);
$('#check_Etternavn').val(data.Etternavn);
});
});
</script>
</body>
</html>