moving changes from a html table to a database - javascript

I have written a table in html and made its rows contenteditable if user hits the edit button.
this table's data are coming from an mysql database. I want my user to be able to change the content editable fields and after hitting the save button changes send to mysql table again.
so firstly, i want to know how to save content editable changes in a string variable so i can be able to POST them to database. followings are my related codes:
<?php
$servername = "localhost";
$username = "hevak_neshat";
$password = "shir moz peste";
$dbname = "hevak_android_api";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM beacons";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<thead>
<tr>
<th>Major number</th>
<th>Minor number</th>
<th>Client</th>
<th>Location</th>
<th>Link to ad</th>
<th>Attachment</th>
<th>Edit</th>
</tr>
</thead>";
echo "<tbody>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["major"] . "</td><td>" . $row["minor"] . "</td><td>" . $row["client"] . "</td><td>" . $row["geolocation"] . "</td><td>" . $row["linktoadd"] . "</td><td>" . $row["attacment"] . "</td><td>";
echo "<button class=\"editbtn\">Edit</button>";
echo "<td><button class=\"savebtn\">Save</button></td>";
echo "</td>";
echo "</tr>";
}
echo "</tbody></table>";
} else {
echo "no results";
}
?>
And my Javascript:
$(document).on("click", ".editbtn", function (event) {
event.preventDefault();
alert("click on items to edit");
var currentTD = $(this).parents('tr').find('td');
if ($(this).html() == 'Edit') {
$.each(currentTD, function () {
$(this).prop('contenteditable', true)
});
} else {
$.each(currentTD, function () {
$(this).prop('contenteditable', false)
});
}
});
Update:
in my code i used content editable. but if anyone has any idea of moving user changes in a table to a database please tell me, even if it is a whole other way. just a table with ability to edit content and moving the content to db.

Related

Button to remove table row is not getting added to html table

I am trying to add a button to remove the table row when clicked. This should be placed next to data that is outputted from MySQL database.For some reason the button is not outputting, below is the code for my table:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Message</th>
<th>Have you replied?</th>
</tr>
</thead>
<?php //makes a connection to the database
$conn = mysqli_connect("localhost", "root", "", "messages");
if ($conn->connect_error) {
die("Connection Failed:" . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_messages";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //fills the table with the content in the database
while ($row = $result->fetch_assoc()) {
echo '<tr><td>' . $row["name"] . '</td><td>' . $row["email"] . '</td><td>' . $row["subject"] . '</td><td>' . $row["message"] . '</td><td><button id="replied" onclick="DeleteRow()"></button>' . '</td></tr>';
}
echo "</table";
} else {
echo "0 result";
}
$conn->close();
?>
</table>
And this is the javascript code to delete the table row:
<script>
function DeleteRow() {
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
}
</script>
Picture of my table row
The blank space underneath the "Have you replied" table header is where the button should be but its not there
I am still learning PHP so any replies on how I can fix this would be very helpful please

How do I create a link in <tr> using the same data requested from an SQL database?

I am trying to create a table which pulls data from an SQL database and each row on the table is a clickable link to it's corresponding page depending on the first column data in the database.
I have managed to do both parts separately i.e create a table with SQL data and i've managed making a table with each row a clickable link however I am struggling to combine the two.
I am using a .js to listen for clicks and send you off depending on the "tr data-href='url'".
My php script to create the table form SQL data creates the "tr" first, then populates the row with each cell, closes the "/tr" and repeats for all rows.
How can I make the php write the "tr data-href='url'" where 'url' is the same as the first column of data for each row?
My PHP script is below, followed by the five lines of JS.
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$db_name = "FFD";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT id,name,location,plots,blurb FROM Sites");
$all_property = array(); //declare an array for saving property
//showing property
echo '
<div class="content-container">
<h1>Table heading</h1>
<section>
<div class="tbl-header">
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<th>' . $property->name . '</th>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>
</thead>
</table>
</div>
<div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>';
//end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo '</tbody></table></div></section></div>';
?>
$(document).ready(function(){
$('tr[data-href]').on("click", function() {
document.location = $(this).data('href');
});
});
I could just be thick and missing something simple and obvious.
Thanks in advance!
You can concatenate your url, like this (assuming id is the column with the url)
while ($row = mysqli_fetch_array($result)) {
echo '<tr data-href="' . $row['id'] . '">';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>';
}
echo '</tr>';
}

Generating button for each row of record that will display row's full information

I have a database set up with several records and a table that displays each row of the record. For each row of the table, the only information that are displayed are the 'name', 'program' and 'course' taken from 'personal' and 'faculty' tables. I'm trying to add a button on each row that will retrieve and show all information regarding that specific row. here are my codes
<?php
$conn = mysqli_connect("localhost", "root", "", "project");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, Full_Name, Program, Course FROM personal, faculty";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo . $row["id"]. . $row["Full_Name"] .
. $row["Program"]. $row["Course"]. ;
}
} else { echo "0 results"; }
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Add a <a href link to each ID as it is output. I made up a name for the program to be called since you didn't tell us what it is.
while($row = $result->fetch_assoc()) {
echo '<a href="showdetails.php?id=' . $row['id'] . '">' .
$row['id'] . '</a>' .
$row['Full_Name'] .
$row['Program'] .
$row['Course'];
}

Retrieving Values for each line in Textarea Box

So I've came across an issue that I'm having regarding a textarea. My goal is to have a form with a textarea where a user can enter an alphanumeric name line by line and then it would pull that information from a database and display it into a table.
For example:
tt1
tt2
tt3
and on submit it would return all of the data associated with those 3 names.
I can get the textarea, parse it and get the raw values to be inserted into the sql query, but I'm getting stuck at outputting the results.
My code for now is as follows:
index.html
<form method="POST" action="getreport.php">
<div class="form-group">
<label for="textarea">Textarea</label>
<textarea class="form-control" name="textarea" id="textarea" class="textarea" rows="5" cols="50"></textarea>
</div>
<button type="submit" class="btn btn-primary" >Submit</button>
</form>
getreport.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = trim($_POST['textarea']);
$textAr = preg_split('/[\n\r]+/', $text); //<--- preg_split is where the magic happens
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
$sql = "SELECT * from guestlist WHERE guestname='$line'";
echo "$sql"; //just checking query output for now
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { //<---- take this while loop out
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr><th>Hostname</th><th>Guestname:</th><th>date</th><th>owner</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>";
echo $row['hostname'];
echo "</td><td>";
echo $row['guestname'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['owner'];
echo "</td></tr>";
}
echo "</table>";
} //<-----as well as the closing bracket
} else {
echo "0 results";
}
$conn->close();
?>
Any help or guidance on this would be appreciated.
Thanks
Not sure your approach to the problem is the correct one, and also as someone suggested you should be worried about SQL injection. Said that, this could be one solution:
$text = trim($_POST['textarea']);
$textAr = str_replace("/n",",", $text);
$sql = "SELECT * from guestlist WHERE FIND_IN_SET(guestname,'$line')>0";
$result = $conn->query($sql);
Another way could be just iteratin every time
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = trim($_POST['textarea']);
$textAr = explode("/n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
$sql = "SELECT * from guestlist WHERE guestname='$line'";
echo "$sql"; //just checking query output for now
$result = $conn->query($sql);
// <---------------- ITERATE INSIDE THE FOREACH
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr><th>Hostname</th><th>Guestname:</th><th>date</th><th>owner</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>";
echo $row['hostname'];
echo "</td><td>";
echo $row['guestname'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['owner'];
echo "</td></tr>";
}
echo "</table>";
}
} else {
echo "0 results";
}
} // Close the foreach
$conn->close();
?>
Not sure why you used 2 while loops - fetch_assoc and mysqli_fetch_array? Each call here moves the pointer to the next row. Maybe that's why your table is not displaying correct data? It seems you can remove the fetch_assoc loop.

PHP table auto update the data but not the table

I have a game server which has a chat function and logs all players' chat messages to my database. I'm trying to create a table that automatically updates the data but not the table itself, this is because on my table I want a dropdown list of actions for each player (kick player from server, ban player, mute player, slap player etc.) but my JavaScript code at the moment refreshes the whole table every 5 seconds. So, if I open my dropdown list, when the table refreshes it will close the dropdown list, at the moment I've changed the dropdown list to a button because of this problem.
Here is my code:
Index page that displays the table:
<?php require 'session.php';
require 'header.php'; ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#results').load('includes/online.php');
}, 3000); // refresh rate in milliseconds.
});
// ]]></script>
<div id="results">Loading data ...</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#results2').load('includes/chatlog.php');
}, 3000); // refresh rate in milliseconds.
});
// ]]></script>
<div id="results2">Loading data ...</div>
<?php
include 'database.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT *,current_clients.CID AS con_id FROM current_clients INNER JOIN groups ON current_clients.Level = groups.level Order By Team DESC, Score DESC";
$result = $conn->query($sql);
while( $row = mysql_fetch_array($result));
if ($result->num_rows > 0) {
echo "<div id=left>";
echo "<table class=table align=center><tr><th>ID</th><th>Name</th><th>Rank</th><th>Score</th><th>IP</th><th>Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$id=$row['con_id'];
$ip=$row['IP'];
$team=$row['Team'];
// $team = str_replace("3","<tr bgcolor=midnightblue>",$team);
// $team = str_replace("2","<tr bgcolor=darkred>",$team);
// $team = str_replace("1","<tr bgcolor=grey>",$team);
$name=$row['ColorName'];
$group=$row['name'];
$name=htmlentities($name);
$name = str_replace("^0","</font><font color=black>",$name);
$name = str_replace("^1","</font><font color=red>",$name);
$name = str_replace("^2","</font><font color=lime>",$name);
$name = str_replace("^3","</font><font color=yellow>",$name);
$name = str_replace("^4","</font><font color=blue>",$name);
$name = str_replace("^5","</font><font color=aqua>",$name);
$name = str_replace("^6","</font><font color=#FF00FF>",$name);
$name = str_replace("^7","</font><font color=white>",$name);
$name = str_replace("^8","</font><font color=white>",$name);
$name = str_replace("^9","</font><font color=gray>",$name);
$score=$row['Score'];
//echo $team;
echo "<td align=center> $id </td>";
echo "<td align=center><a href='user.php?id=".$row["DBID"]."' > $name </a></td>";
echo "<td align=center> $group </td>";
echo "<td align=center> $score </td>";
echo "<td align=center> $ip </td>";
echo "<td align=center>";
echo "<form action=q3/slap.php?id=$id method=POST><button type=submit>Slap</button></form>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "<table class=table align=center><tr><th>ID</th><th>Name</th><th>Rank</th><th>Score</th><th>IP</th><th>Action</th></tr>";
echo "<tr>";
echo "<td>";
echo "There are no players online";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
$conn->close();
?>
My "online players" table is above.
You could store a timestamp on the server that you update each time a change is made on the database. Then, in your setInterval first fetch the last update time from the server and compare it to the one from when the page was loaded; if they are different refresh the page, otherwise do nothing.

Categories

Resources