Javascript MYSQL Dropdown - javascript

Apologies in advance if a) this question has already been answered, I did search but am not able to use the answers I've found and b) I am not the a very skilled programmer and am trying to learn...
To make this as short as possible...
I have a fully functioning site with a searchable and sortable database (that a co-worker pretty much build for me a long time ago, hence why I am extra confused)
I would like to add a dropdown filter that populates from the database
The code references javascript and PHP. From what I understand, the PHP populates the table data for me and the javascript triggers the 'show xx entries' filter and the search box - which are both awesome
My issue is I cannot get any code for the dropdown I would like to add to work. I can get the dropdown to populate but not actually filter the data :(
<?php
$dbhost = 'localhost';
$dbuser = 'database';
$dbpass = 'password;
$dbname = 'marchmadness';
$table = 'leaderboard';
//connect to the database
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Leaderboard</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/png" href="/favicon.ico" />
<link rel="stylesheet" type="text/css" href="assets/css/main.css">
<link rel="stylesheet" type="text/css" href="assets/css/listing.css" media="all" />
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="assets/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/* This triggers the cool filtering stuff, without this it's just a normal table of data */
$('table').dataTable({
"iDisplayLength": 10
});
});
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
</script>
</head>
<body id="listing">
<div id="wrapper">
<div id="topbox" align="center">
<img src="_Images/maddnessheader.png" width="539" height="296" align="center" /></div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<?
$sql="SELECT Title FROM leaderboard";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["leaderboard"];
$thing=$row["Title"];
$options.="<OPTION VALUE=\"$id\">".$thing.'</option>';
}
?>
<SELECT NAME=thing>
<OPTION VALUE=0>Choose
<?=$options?>
</SELEC
T>
<table align="center">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
<th>Call Coding (%)</th>
<th>FizzBack SAT Score (%)</th>
</tr>
</thead>
<tbody>
<?php
//get the information from the database
$result = mysql_query("SELECT * FROM `$table`;") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo '<tr>';
// print out the data from the database. Notice how the text inside $row[] matches up with the headers in phpmyadmin
echo '<td>' . htmlentities($row['Title']) . '</td>';
echo '<td>' . htmlentities($row['Name']) . '</td>';
echo '<td>' . htmlentities($row['CC']) . '</td>';
echo '<td>' . htmlentities($row['FZB']) . '</td>';
echo "</tr>\n";
}
?>
</tbody>
</table>
</div>
</body>
</html>
I think I would have to manipulate the javascript to add what I need, as that's where the the working dropdown and search box come from... but I suck a javascript :-\ If anyone could help I would REALLY appreciate it. I can share the existing Java as well if needed :D
Cheers!

Give this a try, Ive edited a few things which didn't seem quite right and added some code which should hopefully filter stuff. Bit of a guess as I've never used datatables and I dont know what the datatypes are.
<?php
$dbhost = 'localhost';
$dbuser = 'database';
$dbpass = 'password';
$dbname = 'marchmadness';
$table = 'leaderboard';
//connect to the database
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
?>
<!doctype html>
<html lang="en">
<head>
<title>Leaderboard</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/png" href="/favicon.ico" />
<link rel="stylesheet" type="text/css" href="assets/css/main.css">
<link rel="stylesheet" type="text/css" href="assets/css/listing.css" media="all" />
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="assets/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var table; // used to store a reference later
$.fn.dataTablesExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
if (aData[0].toLowerCase() == $('#title_filter').val().toLowerCase()) {
return true;
} else {
return false;
}
}
);
$(document).ready(function() {
/* This triggers the cool filtering stuff, without this it's just a normal table of data */
table = $('table').dataTable({ "iDisplayLength": 10 }); // this starts the datatable stuff and returns a reference to it
});
$("#title_filter").onchange(function() {
table.fnDraw(); // forgot this line - whoops
});
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
</script>
</head>
<body id="listing">
<div id="wrapper">
<div id="topbox" align="center">
<img src="_Images/maddnessheader.png" width="539" height="296" align="center" /></div>
<?php
$sql="SELECT Title FROM leaderboard";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["leaderboard"];
$thing=$row["Title"];
$options.="<option value=\"$thing\">".$thing.'</option>';
}
?>
<select id="title_filter">
<?=$options?>
</select>
<table align="center">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
<th>Call Coding (%)</th>
<th>FizzBack SAT Score (%)</th>
</tr>
</thead>
<tbody>
<?php
//get the information from the database
$result = mysql_query("SELECT * FROM `$table`;") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo '<tr>';
// print out the data from the database. Notice how the text inside $row[] matches up with the headers in phpmyadmin
echo '<td>' . htmlentities($row['Title']) . '</td>';
echo '<td>' . htmlentities($row['Name']) . '</td>';
echo '<td>' . htmlentities($row['CC']) . '</td>';
echo '<td>' . htmlentities($row['FZB']) . '</td>';
echo "</tr>\n";
}
?>
</tbody>
</table>
</div>
</body>
</html>

Related

Refresh sub php page onchange

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>";
}
?>

Smoothy update PHP table when new data is entered into SQL table

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?

Delete Multiple Selected Data in PHP/MySQL [duplicate]

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);
}

Html Dropdown Menu Displays nothing

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>

Having trouble with code - Deleting records from database - JS / PHP

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!

Categories