I would like to create a master - detail in php and javascript with two tables:
The First table is loaded from a database and it contains some categories.
When i click on a row in the first table I would like to view in a second table all subcategories of a selected category.
I have try with this but I'm not able to create the query for the subcategories table.
<div class="uk-grid">
<!-- First Table - List of Categories -->
<div class="uk-width-1-2" id="Gruppi" >
<div class="uk-panel uk-panel-box">
<h2>Gruppi</h2>
<?php
// Connessione al db
$con = mysqli_connect('localhost','root','','conti');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT Gruppo, Tipo FROM gruppi";
$result = mysqli_query($con,$sql);
echo "<section class=\"wrapper style5\">
<table id=\"table_gruppi\" class=\"uk-table uk-table-hover uk-table-striped uk-table-condensed\" > <thead> <tr>
<th>Gruppo</th>
<th>Entrata</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Gruppo'] . "</td>";
// Checkbox al posto di 1 o 0
if ($row["Tipo"]=='1') {
echo "<td> <input checked=\"\" type=\"checkbox\" disabled> </input> </td>";
} elseif ($row["Tipo"]=='0') {
echo "<td> <input type=\"checkbox\" disabled> </input> </td>";
}
echo "</tr>";
}
echo "</table></section>";
mysqli_close($con);
?>
</div>
</div>
<!-- Second Table - List of Subcategories -->
<div class="uk-width-1-2"><div class="uk-panel uk-panel-box"><h2>Sottogruppi</h2>
<p id="click-response"></p>
<?php
// Connessione al db
$con = mysqli_connect('localhost','root','','conti');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT Sottogruppo FROM sottogruppi WHERE Gruppo = ";
$result = mysqli_query($con,$sql);
echo "<section class=\"wrapper style5\">
<table id=\"table_gruppi\" class=\"uk-table uk-table-hover uk-table-striped uk-table-condensed\" > <thead> <tr>
<th>Sottogruppo</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Sottogruppo'] . "</td>";
echo "</tr>";
}
echo "</table></section>";
mysqli_close($con);
?>
</div></div>
<script type="text/javascript">
function onRowClick(tableId, callback) {
var table = document.getElementById(tableId),
rows = table.getElementsByTagName("tr"),
i;
for (i = 0; i < rows.length; i++) {
table.rows[i].onclick = function (row) {
return function () {
callback(row);
};
}(table.rows[i]);
}
};
onRowClick("table_gruppi", function (row){
var value = row.getElementsByTagName("td")[0].innerHTML;
document.getElementById('click-response').innerHTML = value + " clicked!";
console.log("value>>", value);
var sql_sottogruppi = "SELECT Sottogruppo FROM sottogruppi WHERE Gruppo = '" + value + "'"
});
</script>
I need some help or example.
thank you so much!
Related
Based on my question, I want to display the content of the div (id = "content") with a text (Data is empty) when there is no data to retrieve from the database. What I know is to use javascript. But I am still new in this programming skill. Can anyone help me?
Below is my code
<div class="row" id = "content">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card bg-light">
<div class="card-body double" style="height: 400px; overflow-y: scroll;">
<h4 class="card-title">All Booking</h4>
<table class="table table-bordered" >
<thead>
<tr>
<th>#</th>
<th>Requester</th>
<th>Factory</th>
<th>Room</th>
<th>Purpose</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody >
<?php
$query = $conn->query("SELECT * FROM booking LEFT JOIN room ON booking.Room_ID = room.Room_ID WHERE Admin_email = '$Email' AND EndTime > GETDATE() ORDER BY booking.Book_No DESC");
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$status=$row['Book_Status'];
if($status=="Approve")
{
$color="color:green";
}
else if($status=="Pending")
{
$color="color:blue";
}
else
{
$color="color:red";
}
echo "<tr>";
echo "<td>" . $row['Book_No'] . "</td>";
echo "<td>" . $row['Requested_by'] . "</td>";
echo "<td>" . $row['Fac_ID'] . "</td>";
echo "<td>" . $row['Room_Desc'] . "</td>";
echo "<td>" . $row['Meeting_Description'] . "</td>";
echo "<td style='$color'><strong>" . $status ."</strong></td>";
echo "<td>";
echo "<a class='btn btn-primary btn-block' href='../view_booking/view_booking.php?Book_No=". $row['Book_No'] ."' title='View Booking' data-toggle='tooltip'>View</a>";
echo "</td>";
echo "</tr>";
}
?>
</tbody>
</table><br>
</div>
</div>
</div>
</div>
You can wrap your <div> tag inside a condition based on your SQL query.
Example:
$query = $conn->query("SELECT * FROM booking LEFT JOIN room ON booking.Room_ID = room.Room_ID WHERE Admin_email = '$Email' AND EndTime > GETDATE() ORDER BY booking.Book_No DESC");
$count = mysqli_num_rows($query); // if your query doesn't returns any error.
if($count > 0) { ?>
<div id=content> your all contents here </div>
<?php } else { ?>
<div id="content"> Data is empty </div>
<?php } ?>
I want to remove DB row data from HTML table. I have an HTML table where I have called all the database table values. I want to give a delete order option to the user. I have used a delete button for that. To do this, I am trying to use ajax and jquery with php delete query. But the issue is When I click on delete it just deletes the HTML row data. It should delete that particular id row from DB as well. I need your help. Please let me know what I have done wrong? I am very much new to ajax and jquery.
remove.php
<?php
include "config.php";
$id = $_REQUEST['id'];
// Delete record
$query = "DELETE FROM mi_home_tv WHERE id='$id'";
mysqli_query($link,$query);
echo 1;
jquery+ajax code
<script src='jquery-3.0.0.js' type='text/javascript'></script>
<script type="text/javascript">
$(document).ready(function(){
// Delete
$('.delete').click(function(){
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
// AJAX Request
$.ajax({
url: 'remove.php',
type: 'POST',
data: { id:deleteid },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
});
});
</script>
Button Code:
echo "<td> <span id='del_<?php echo $id; ?>' type='submit' class=' delete btn c-theme-btn c-btn-uppercase btn-xs c-btn-square c-font-sm'>Delete</span> </td>";
php code:
<form method="post" action="remove.php">
<?php
echo " <thead>
<tr>
<th>Order ID</th>
<th>Date</th>
<th>Name</th>
<th>Store Name</th>
<th>Zip</th>
<th>City</th>
<th>Address</th>
<th>Contact</th>
<th>Tv Varient</th>
<th>Total</th>
<th>Delivery</th>
<th>Action</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
echo"<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rdate'] . "</td>";
echo "<td>" . $row['rname'] . "</td>";
echo "<td>" . $row['rstore'] . "</td>";
echo " <td>" . $row['rzip'] . "</td>";
echo "<td>" . $row['rcity'] . "</td>";
echo "<td>" . $row['raddress'] . "</td>";
echo "<td>" . $row['rphone'] . "</td>";
echo "<td>" . $row['rtv_varient'] . "</td>";
echo"<td>" . $row['ramount'] . "</td>";
echo"<td>" . $row['rdelivery'] . "</td>";
echo "<td> <input type='submit' value='delete' id='del_<?php echo $id; ?>' type='submit' class=' delete btn c-theme-btn c-btn-uppercase btn-xs c-btn-square c-font-sm'>Delete</button> </td>";
echo"</tr>";
}
?>
</form>
You should have a form which will have an input as follows:
<form method="post" action="remove.php">
<input type="submit" value="Delete" name="id" />
</form>
I have an SQL-database with many tables. Now I would like to create an input-form to be able to get data into the db without writing the entire sql-code every time. And this should work as follows:
All table names are listed in a drop-down menu. After having selected a table name, a new table with 4 columns is created automatically:
The first column of this table simply contains an increasing number.
The second column contains the field-names of the selected table.
In the third column there are empty input fields to enter the values for the database. Only in the third line (=product name) there is a drop-down menu with all product names from the main-table of the db.
The fourth column contains the data type (e.g. int or varchar)
All tables in the database have the same structure in the first 3 columns: the first column contains the table-id, the second column the foreign-key (=master_id) and the third column the product_name.
Up to this point, the script works well with the following 2 php-files (javasql.php and getuser.php):
javasql.php:
enter code here
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="" class="optdrugs">please select</option>
<?php
include("files/zugriff.inc.php"); // database Access
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'product'";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value="'. $row['TABLE_NAME'] . '">' .
$row['TABLE_NAME']. '</option>';
echo '<br>';
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Bitte Tabelle auswählen:</b>
<br>
<?php
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$q = $_POST['tablename'];
$column_passed = unserialize($_POST['column']); // content of array
$column is passed from getuser.php
foreach ($_POST["insertvalue"] as $key => $value) {
echo $value . "<br>";
$werte[] = "'$value'";
}
$sql="INSERT INTO $q ($column_passed) VALUES (" .
implode(", ", $werte) . ")"; // data entry
mysqli_query($db, $sql);
if (mysqli_affected_rows($db) > 0) {
echo "<h3 style='color:blue'>successful</h3>";
} else {
echo "<h3 style='color:red'>not
successful</h3>";
}
}
?>
</div>
</body>
</html>
enter code here
getuser.php:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<form id="formdatabase" name="formdatabase" action="javasql.php"
method="post">
<input type="hidden" name="sent" value="yes">
<?php
$q = strval($_GET['q']);
$con = mysqli_connect('localhost','root','','product');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM $q";
$result = mysqli_query($con,$sql);
$numcols = mysqli_num_fields($result); // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$data_type_array = array(
1=>'tinyint',
2=>'smallint',
3=>'int',
4=>'float',
5=>'double',
7=>'timestamp',
8=>'bigint',
9=>'mediumint',
10=>'date',
11=>'time',
12=>'datetime',
13=>'year',
16=>'bit',
252=>'text',
253=>'varchar',
254=>'char',
246=>'decimal'
);
$data_type_array = array_flip($data_type_array);
echo "<table>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th><th>" . 'Column names' . "</th>
<th>" . 'Values for db-entry' . "</th><th>" . 'Type' . "</th>";
echo "</tr>";
echo "<tr>";
$nr = 1;
for($x=0;$x<$numcols;$x++):?>
<td><?= $nr; ?></td>
<td><?= $field[$x]->name; ?></td>
<?= $column[] = $field[$x]->name; ?>
<td>
<?php
if ($field[$x]->name == 'Name') { // if-Beginn
?>
<select name="insertvalue[<?= $x; ?>]" id="insertvalue<?=
$x; ?>" size="1" onchange = "javascript:getSelectedRow()">
<?php
include("files/zugriff.inc.php");
$sql = "SELECT * FROM product_main ORDER BY Name";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value='. $row['Name'] . '>' .
$row['Name'] . '</option>';
echo '<br>';
}
?>
</select>
<?php
$name_option = "";
} else {
$name_option = "<input type='text' id='insertvalue" . $x . "'
name='insertvalue[" . $x . "]' size='50'>";
echo $name_option;
}
?>
</td>
<?php
$key = array_search($field[$x]->type, $data_type_array);
if($key !== false){
echo "<td>" . $key . "</td>";
}else{
echo "<td>" . $field[$x]->type . "</td>";
}
?>
<td><?= $field[$x]->type; ?></td>
<?= $nr = $nr + 1; ?>
</tr>
<?php endfor;
echo "</table>";
mysqli_close($con);
?>
<input type="hidden" name="tablename" value="<?= $q; ?>">
<input type="hidden" name="column" value="<?php echo htmlentities
(serialize($column)); ?>">
<input type="submit" value="Enter values" name="submit">
</form>
</body>
</html>
Since I need the master_id (= foreign key) in addition to the product-name for database entry, I would like to extend my script, so that the respective master_id is automatically sent to the input field in line 2, when a product-name is selected in line 3 ... without clicking a button. I tried to do this with javascript but it didn´t work. As far as I know, the solution would be to use AJAX but unfortunately, I am not very used to AJAX.
I would be more than happy, if someone could help me to solve this problem!
url only updates when pressed button is pressed once and has to be pressed again to show details. The reason I can press it twice is because the div='read' flashes blank the first time and with the details the second time.
Don't know how to fix the div from flashing and how to set url before it opens to div with the results.
PHP AT THE TOP OF ACCOUNT PAGE
$getmessages = "SELECT * FROM messages WHERE messages.receiver='$email' ORDER BY date DESC";
$messageresult = mysqli_query($conn, $getmessages) or die(mysqli_error($conn));
if (isset($_GET['msgid'])) {
$filter = $_GET["msgid"];
$getmessage = "SELECT * FROM messages WHERE messages.message_id ='$filter'";
$getresult = mysqli_query($conn, $getmessage) or die(mysqli_error($conn));
if (mysqli_num_rows($getresult) > 0) {
while ($row = mysqli_fetch_assoc($getresult)) {
$displaysub = $row["subject"];
$displaydate = $row["date"];
$displaysender = $row["sender"];
$displayreceiver = $row["receiver"];
$displaymessageid = $row["message_id"];
$displaymessage = $row["message"];
}
}
} else {
$displaysub = "";
$displaydate = "";
$displaysender = "";
$displayreceiver = "";
$displaymessageid = "";
$displaymessage = "";
}
mysqli_close($conn);
?>
MAIN HTML/PHP
<div id="msginbox">
<h4><strong>Inbox</strong></h4>
<table id="inbox" class="table table-bordered table-responsive ">
<thead>
<tr>
<th>Date</th>
<th>Sender</th>
<th>Subject</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if (mysqli_num_rows($messageresult) > 0) {
while ($row = mysqli_fetch_assoc($messageresult)) {
$sub = $row["subject"];
$rdate = $row["date"];
$sender = $row["sender"];
$messageid = $row["message_id"];
$message = $row["message"];
echo "<tr>";
echo "<td id='left'><p>" . $rdate . "</p></td>";
echo "<td id='left'><p>" . $sender . "</p></td>";
echo "<td id='left'><p>" . $sub . "</p></td>";
echo "<td>" . "<button value='account.php?msgid=$messageid' class='btn btn-primary replyback'>Reply</button>" . "</td>";
echo "</tr>";
}
}
?>
</tbody>
</table>
</div>
<div id="read">
<p><strong>From: </strong><?php echo $displaysender; ?><br></p>
<br>
<p><strong>Date: </strong><?php echo $displaydate; ?><br></p>
<br>
<p><strong>Subject: </strong><?php echo $displaysub; ?><br></p>
<br>
<p><strong>Message: </strong><?php echo $displaymessage; ?></p>
<br>
<button id="back">Back</button>
</div>
JQUERY
$(document).ready(function () {
$('.replyback').click(function (e) {
e.preventDefault();
$('#read').css('display', 'block');
$('#msginbox').css('display', 'none');
var newurl = $(this).attr("value");
window.location.href = newurl;
});
});
I have two tables on one page. The table at the top only has one row, because that particular table in the DB will only ever have one entry, the Tank of the Month. The bottom table shows the contents of another table in the database, 'uploads'. When an item is deleted from the bottom table, it deletes it from the DB and from the physical /uploads/ folder as expected. When an item is chosen from the bottom table as Tank of the Month, it is supposed to disappear from the bottom table, which it does correctly, then the top table is supposed to clear and the item that was chosen should automatically fade into the top table. I have tried many, many ways of doing this with no luck so far. The only way I can get the top table to refresh is by actually refreshing the page. This does what I want, but I want to do it without the page refresh.
totm.php (not the whole file as most of it works):
<!--put body stuff here-->
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card card-plain">
<div class="header">
<h4 class="title">Current Tank of the Month</h4>
<p class="category">This is your current tank of the month. </p>
</div>
<div class="content table-responsive table-full-width">
<?php
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
else
{
if (!$stmt = $mysqli->query("SELECT * FROM totm")) {
echo "Query Failed!: (" . $mysqli->errno . ") ". $mysqli->error;
}
echo "<table class='table table-hover'>";
echo "<thead>
<th>Image</th>
<th>Filename</th>
<th>Description</th>
</thead>
<tbody>";
while ($row = mysqli_fetch_array($stmt)) {
$i = $row["id"];
$f = $row["file"];
$d = $row["description"];
echo "<tr id='$i' file='$f' desc='$d'>";
echo "<td> <a href='../assets/img/totm/" . $row["file"] . "'><img class='thumbnail' src='../assets/img/totm/" . $row["file"] . "' alt='" . $row["file"] . "' /> </td>";
echo "<td>" . $row["file"] . "</td>";
echo "<td>" . $row["description"] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
if (mysqli_num_rows($stmt) == 0) {
echo "No records found.";
}
}
$stmt->free();
//$mysqli->close();
?>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card card-plain">
<div class="header">
<h4 class="title">Current Entries</h4>
<p class="category">Here you will find the current entries for the Tank of the Month contest. Select one as the new Tank of The Month and delete the rest. Keep it clean around here! </p>
</div>
<div class="content table-responsive table-full-width">
<?php
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
else
{
if (!$stmt = $mysqli->query("SELECT * FROM uploads")) {
echo "Query Failed!: (" . $mysqli->errno . ") ". $mysqli->error;
}
echo "<table class='table table-hover'>";
echo "<thead>
<th>Image</th>
<th>Name</th>
<th>Email</th>
<th>IP</th>
<th>Date</th>
<th>Description</th>
<th>Action</th>
</thead>
<tbody>";
while ($row = mysqli_fetch_array($stmt)) {
$i = $row["id"];
$f = $row["file"];
$d = $row["description"];
echo "<tr id='$i' file='$f' desc='$d'>";
echo "<td> <a href='../uploads/" . $row["file"] . "'><img class='thumbnail' src='../uploads/" . $row["file"] . "' alt='" . $row["file"] . "' /> </td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "<td>" . $row["ip"] . "</td>";
echo "<td>" . $row["date"] . "</td>";
echo "<td>" . $row["description"] . "</td>";
echo "<td>
<button class='btn btn-round btn-danger deleteitem'>Delete</button>
<div class='space-20'></div>
<button class='btn btn-round btn-success chooseitem'>Select</button>
</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
if (mysqli_num_rows($stmt) == 0) {
echo "No records found.";
}
}
$stmt->free();
$mysqli->close();
?>
</div>
</div>
</div>
</div>
</div>
</div>
totm-backend.js:
$(".deleteitem").click(function () {
var parent = $(this).closest('TR');
var id = parent.attr('id');
var file = parent.attr('file');
if (confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
data: { delete_id: id, delete_file : file },
URL: "totm.php",
success: function (msg) {
parent.fadeOut('slow', function () { $('#' + id).remove() });
}
});
}
return false;
});
$(".chooseitem").click(function () {
var parent = $(this).closest('tr');
var id = parent.attr('id');
var file = parent.attr('file');
var desc = parent.attr('desc');
if (confirm("Are you sure you want to promote this to Tank of the Month?")) {
$.ajax({
type: "POST",
data: { promote_id: id, promote_file: file, promote_desc: desc },
URL: "totm.php",
success: function (msg) {
parent.fadeOut('slow', function () { $('#' + id).remove() });
}
});
}
return false;
});
You could use the appendTo function to append the item into the proper table.
Check this post out on how to do it.
To get the "current" table, check out hasClass
I'm just learning javascript and jquery myself so there may be better ways.