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>";
}
?>
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?
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);
}
I'm trying to diplay my table when I click a value in Dropdown list. When I view page code source, the table values are there but it's not showing. I would like to query from mysql using the value from dropdown and populate the table with datas from mysql query.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
function jsFunction(value){
<?php
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='value'";
echo '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['brgy'] . "</td>";
echo "<td>" . $row['case_type'] . "</td>";
echo "<td>" . $row['total_case_brgy'] . "</td>";
echo "</tr>";
}
echo '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<select id ="ddl" name="ddl" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</body>
</html>
Originally, in my other webpages, the php code is inside the body. But this time, I can't make it work if I use dropdown menu so that's why I put it inside the function for me to be able to use onchange function. I've read some answers using AJAX or JSON but I'm not familiar with those so if possible I only want to use javascript as maybe it is the simplest way.
What you are trying to do here is run PHP code in the browser, which you cannot do. All the HTML, CSS, and JavaScript is sent down to the client ( your browser ) and then is rendered and initialized by the browser. When you are calling your onchange event to call the jsFunction() you are trying to execute PHP within that function but- you are on the client-side running in chrome or firefox or some browser and you cannot execute PHP there. PHP has to run on page load and then can change the html, css, or JavaScript before it is sent down to the client.
There are two ways of doing what you want to do. You can send an Ajax request ( call your server using javascript ) to get new data or you can submit a form that reloads the page and you can run PHP like you are comfortable with- modifying the html, css, and/or javascript before it is returned to the client (browser).
Here is the non-ajax way which just keeps reloading the page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<?php
$value = isset( $_POST['ddl'] ) ? $_POST['dll'] : 1; // we are setting 1 as the default
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='{$value}'";
$html= '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
$html.= "<tr>";
$html.= "<td>" . $row['brgy'] . "</td>";
$html.= "<td>" . $row['case_type'] . "</td>";
$html.= "<td>" . $row['total_case_brgy'] . "</td>";
$html.= "</tr>";
}
$html.= '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<form method="POST" action="">
<select id="ddl" name="ddl">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</form>
<script>
$("select#ddl").on("change",function(){
$('form').submit();
});
</script>
<?php echo $html; ?>
</body>
</html>
I'm having some trouble with this code pinpointing exactly where the problems coming from, I'm not sure if theres a problem with the javascript but when I go to select a record from select.php it just ends up stalling.. (nothing happens ;/)
confirmDelete.js
function fnConfirm(delUrl) {
if (confirm("Are you sure you want to delete this record?")) {
window.location = delUrl;
}
var linkDel = document.getElementById("linkDelete");
linkDel.onclick= fnConfirm;
select.php
<?php header("Cache-Control:no-cache"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Cabin -AdminPanel</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<script src="confirmDelete.js"></script>
<h2>Select from the cabins listed below to delete:</h2>
<?php
//connect to server and database
include 'sqldb_connect.inc.php';
//set up query
$query = "SELECT * FROM tblCabins";
//execute query
$result = mysql_query($query);
if(!$result)
{
mysql_close();
exit("Error retrieving cabins from database");
}
//get the number of rows in the cabins table and store in a variable
if(mysql_num_rows($result) <1)
{
mysql_close();
exit("No cabin entries found");
}
//start table
?>
<!--.......................................................................-->
<table>
<tr>
<th>cabinID</th>
<th>Cabin Type</th>
<th>Cabin Description</th>
<th>Price per night</th>
<th>Price per week</th>
<th>Photo</th>
<th> </th>
</tr>
<!--.......................................................................-->
<?php
//fetch the next row (or record) of the result set until there are no more left
while($row = mysql_fetch_array($result))
{
//store the results in variables
$cabinID = $row['cabinID'];
$cabintype = $row['cabinType'];
$cabindesc = $row['cabinDescription'];
$pricepern = $row['pricePerNight'];
$priceperw = $row['pricePerWeek'];
$photo = $row['PHOTO'];
?>
<!--.......................................................................-->
<tr>
<td><?= $cabinID; ?></td>
<td><?= $cabintype; ?></td>
<td><?= $cabindesc; ?></td>
<td><?= $pricepern; ?></td>
<td><?= $priceperw; ?></td>
<td><?= $photo; ?></td>
<td><a id="linkDelete" href="javascript:fnConfirm('cabinDelete_process.php?cabinID=<?= "$cabinID"; ?>')">Delete</a></td>
</tr>
<!--.................................................................................-->
<?php
}
mysql_close();
?>
<!--.................................................................................-->
</table>
</body>
</html>
process.php
<?php header("Cache-Control:no-cache"); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deleteCabinProcess - adminPanel</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<?php
//this page will delete the cabin
//selected from the previous page
//read cabinID passed to this page
$cabinID = $_GET['cabinID'];
//connect to server and database
include 'sqldb_connect.inc.php';
//set up query
$query = "DELETE FROM tblCabins WHERE cabinID = '$cabinID'";
//execute query
$result = mysql_query($query);
if(!$result)
{
mysql_close();
exit("Error deleting Cabin from the database");
}
mysql_close();
exit ("Successfully deleted the record from the database ");
?>
</body>
</html>
If anyone can see any problems it'd be greatly appreciated.. Brb need to go outside and adjust my eyes!