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.
Related
I successfully created a script that will delete the rows of a table if a checkbox is checked on that row (the checkbox holds the rowID). The checkboxes and button to delete these rows are inside of the same form tags. Now I want to create another button that uses the value of the checkboxes to do a different update statement, but the values of the checkboxes are not appearing in $_POST on this separate page.
Does anyone know how to make the checkbox values accessible outside of the form action it is inside of? Here is my reduced code for the delete that works:
The function below is called on PickTicket.php to display a table.
Function DisplayPickTicket() {
$conn = getDBConnection();
$sql = "SELECT * FROM dbo.BK_NotesRecord WHERE StatusID = 1 ";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
echo '<form action="updatepickstatus.php" method="post">';
// Delete Checkbox header.
echo '<th class="table-header" style="width:5px;">';
echo 'Delete';
echo '</th>';
// Inventory number header.
echo '<th class="table-header" style="width:90px;">';
echo 'Inventory #';
echo '</th>';
//InventoryID Header
echo '<th class="table-header" style="width:40px;">';
echo 'InventoryID';
echo '</th>';
if (sqlsrv_has_rows($stmt)) {
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo '<tr>';
//Delete checkbox
echo '<td class="cell"><div class="cell">';
echo '<input type = "checkbox" name="chkbox[]" value= "' .$row['InventoryID'].
'">';
echo '</td>';
// Inventory#
echo '<td class="cell"><div class="cell">';
echo $row["InventoryNumber"];
echo '</td>';
// InventoryID.
echo '<td class="cell"><div class="cell">';
echo $row["InventoryID"];
echo '</td>';
}
}
echo "<tr>";
echo "<td>";
echo "<input type='submit' name='submit' Value='Remove'>";
echo '</form>';
echo "</td>";
echo "</tr>";
This is updatepickstatus.php:
<?php
$serverName = "(local)";
$connectionOptions = array("Database"=>"Powerlink");
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn === false ) {
echo "Connection failed!<br>";
die( print_r( sqlsrv_errors(), true));
}
if (isset($_POST['chkbox'])) {
foreach($_POST['chkbox'] as $Update) {
$sql = "UPDATE BK_NotesRecord set StatusID = '2' WHERE InventoryID LIKE '".$Update."'";
$stmt = sqlsrv_query( $conn, $sql );
//echo '$ids';
}
}
print_r($_POST);
?>
^^I want to accomplish this same basic task, but outside of updatepickstatus.php. When applying similar logic to check the values of the selected checkboxes on a different I get an empty array. Any thoughts?
Try declaring a variable and passing the value you want to use to it then use sessions to move it where ever you want.
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.
What I have is a table that is pulled from a database. The goal is that I want to be able to click on any team and have a self posted page produce a table with previous yearly results per row (multiple tables, year by year) and a row of total stats. For example: Click on San Jose and get 2014-2015 stats in 1 row, 2015-2016 in the next row and then a total of all the seasons added up. Not really sure how to implement it. I would love to get some suggestions on the best way to attack this problem.
Link To My Project
Here is some of my code, so you can see how I am doing it so far.
$query = "SELECT * FROM standings2015_2016 WHERE confid='2' ORDER BY pts DESC, losses ASC, otl ASC, gf-ga DESC";
$result = $db->query($query);
echo "<h3>Western Conference</h3>";
echo "<table class='table sortable'>";
echo "<tr class='TableHeaders'>";
echo "<td class='hover'>Place</td>";
echo "<td class='hover'>Team</td>";
echo "<td class='hover'>Wins</td>";
echo "<td class='hover'>Losses</td>";
echo "<td class='hover'>OTL</td>";
echo "<td class='hover'>Points</td>";
echo "<td class='hover'>GF</td>";
echo "<td class='hover'>GA</td>";
echo "<td class='hover'>+ / -</td>";
echo "</tr>";
$i = 0;
foreach ($result as $row) {
$i++;
$plusMinus = ($row['gf'] - $row['ga']);
echo "<tr>";
echo "<td>";
echo $i;
echo "</td><td class='hover2'>";
echo stripslashes($row['name']);
echo "</td><td>";
echo stripslashes($row['wins']);
echo "</td><td>";
echo stripslashes($row['losses']);
echo "</td><td>";
echo stripslashes($row['otl']);
echo "</td><td>";
echo stripslashes($row['pts']);
echo "</td><td>";
echo stripslashes($row['gf']);
echo "</td><td>";
echo stripslashes($row['ga']);
echo "</td><td>";
echo $plusMinus;
echo "</td>";
echo "</tr>";
}
echo "</table>";
So echo stripslashes($row['name']); is the team name I want to click on. Can this be done with an onclick event to prompt a query and a self post?
In order to do what you want, we can use jQuery and Ajax.
First is to download jQuery here.
Then create a link element for each team name that has class and data-artid tag:
echo ''.stripslashes($row['name']).'';
Then create the script:
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript">
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$(".teamname").click(function(){ /* WHEN A TEAM IS CLICKED */
var elem = $(this); /* STORE THE CLICKED TEAM */
var teamid = elem.attr("data-artid"); /* GET THE ID OF THE CLICKED TEAM NAME */
$.ajax({ /* PREPARE THE AJAX */
type: "POST", /* METHOD TO BE USED TO PROCESS THE PASSED DATA */
url: "action.php", /* THE PAGE WHERE THE DATA WILL BE PROCESSED */
data: {"teamid": teamid}, /* THE DATA WE WILL PASS */
success: function(result){
$("#content").html(result); /* WE WILL SHOW THE RETURNED DATA TO YOUR CONTENT DIV */
} /* END OF SUCCESS */
}); /* END OF AJAX */
});
});
</script>
And for your action.php, which will process the passed on data using Ajax:
<?php
/* INCLUDE YOUR DB CONNECTION HERE */
if(!empty($_POST["teamid"])){
$tr = '
<table class="table sortable">
<tr class="TableHeaders">
<td class="hover">Team</td>
<td class="hover">Wins</td>
<td class="hover">Losses</td>
<td class="hover">OTL</td>
<td class="hover">Points</td>
<td class="hover">GF</td>
<td class="hover">GA</td>
</tr>
';
$result = $db->query("SELECT name, wins, losses, otl, pts, gf, ga FROM standings2014_2015 WHERE teamid = '".$_POST["teamid"]."'");
foreach ($result as $row) {
$tr .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["wins"].'</td>
<td>'.$row["losses"].'</td>
<td>'.$row["otl"].'</td>
<td>'.$row["pts"].'</td>
<td>'.$row["gf"].'</td>
<td>'.$row["ga"].'</td>
</tr>
';
} /* END OF LOOP */
$tr .= '</table>';
echo $tr; /* RETURN THIS TO AJAX */
} /* END OF NOT EMPTY teamid */
?>
You can assign an ID to each one of the teams in your database and then use that ID to pull the information in one php file. In that file you can just get the ID perform the query search and display the information in a different page.
In the index.php where you display all the teams you can add a link to the team.php.
echo "<a href=\"team.php?Id=".$team['Id']."\">";
team.php
if (isset($_GET['Id']) && is_numeric($_GET['Id']))
{
// Perform database query
$teamID = mysql_escape_string($_GET['Id']);
// Assign the query to a variable
$query = "SELECT name, wins, losses, otl, pts, gf, ga FROM standings2014_2015 WHERE Id=".$teamID.";";
$result = $conn->query($query);
// If the user exists
if ($result)
{
while ($team = $result->fetch_assoc())
{
echo $team["name"];
echo $team["wins"];
....
// Display the information in the table
}
}
I suggest this code:
For standings.php modify this:
echo stripslashes($row['name']);
by:
echo "<a href=\"standings.php?name=".stripslashes($row['name'])."\">";
Then standings.php should view like this:
if (isset($_GET['name']) && !is_empty($_GET['name']))
{
$kname = mysql_escape_string($_GET['name']);
$query = "SELECT name, wins, losses, otl, pts, gf, ga FROM standings2014_2015 WHERE name=".$kname.";";
$result = $db->query($query);
if ($result)
{ echo "<table class='table sortable'>";
foreach ($result as $row)
{
$tr .= '
<tr>
<td>'.$name.'</td>
<td>'.$wins.'</td>
<td>'.$losses.'</td>
<td>'.$otl.'</td>
<td>'.$pts.'</td>
<td>'.$gf.'</td>
<td>'.$ga.'</td>
</tr>
';
echo $tr;
}
echo "</table>";
}
}else{
//YOUR ACTUAL CODE
}
I have a php function which displays all the data in my mysql table and allows the user to delete data not needed. I managed to get the data to show in a table, get the delete button to ask for confirmation using javascript, but when i try to get the value in the 2nd cell of the table with the query result (the name) and display it on the confirmation tab, it says undefined. Why is that happening? From what i understand, document.getElementById("myText").value where myText is the id of the cell, should return the value in the cell, correct? Also, how would i call and send that value to another php file that has the delete query?
<?php
$row = mysqli_fetch_array($result);
echo "<table>";
echo "<tr class='header'><td class='header'>Delete</td>";
echo "<td class='header'>Added</td>";
echo "<td class='header'>Name</td>";
echo "<td class='header'>Genre</td>";
echo "<td class='header'>Developer</td>";
echo "<td class='header'>Rating</td></tr>";
?>
<script type="text/javascript">
function ConfirmDelete(){
var name = document.getElementById("name").value;
if (confirm("Delete" +name+"?")){
//send the value and call the php
}
}
</script>
<?php
for ($x=0; $row; $x++) {
echo "<tr><td><input type='button' onclick='ConfirmDelete()' name='deleteGame' value='DELETE'></td><td>$row[Added]</td><td id='name'>$row[Name]</td><td>$row[Genre]</td><td>$row[Developer]</td><td align='right'>$row[Rating]</td></tr>";
$row = mysqli_fetch_array($result);
}
?>
</table>
please in need help in updating multiple rows based on dynamic data fetched from mysql database. I have implemented this using $_Post to udate.php file, but how can i do this using ajax.
//THIS SCRIPT FETCH FROM DATABASE
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("student") or die("Unable to select database");
$sql = "SELECT * FROM students ORDER BY id";
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$i = 0;
echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Address</td>';
echo '</tr>';
echo "<form name='form_update' method='post' action='update.php'>\n";
while ($students = mysql_fetch_array($result)) {
echo '<tr>';
echo "<td>{$students['id']}<input type='hidden' name='id[$i]'value='{$students['id']}' /></td>";
echo "<td>{$students['name']}</td>";
echo "<td><input type='text' size='40' name='address[$i]' value='{$students['address']}' /></td>";
echo '</tr>';
++$i;
}
echo '<tr>';
echo "<td><input type='submit' value='submit' /></td>";
echo '</tr>';
echo "</form>";
echo '</table>';
echo $i; ?>
</body>
// HERE IS THE UPDATE SCRIPT
// On clicking submit all rows are updated but i still cant achieve dis with ajax.
UPDATE.PHP
$size = count($_POST['address']);
$i = 0;
while ($i < $size) {
$address= $_POST['address'][$i];
$id = $_POST['id'][$i];
$query = "UPDATE students SET address = '$address' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$address<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
?>
HERE IS WHAT I HAVE TRIED ON AJAX
function update(){
var j=0;
while(j< <?php echo $i ; ?>){
var id=$("#id" + j);
var address=$("#address" + j);
$.ajax(
{
url:"update.php",
type:"post",
data:{id:id.val(),address:address.val()},
success:function(response)
{
}
});
}
ANY HELP WILL BE APPRECIATED
You shouldn't need to loop and execute multiple POSTs. Simply serialize the form data and send it to the script, e.g.:
$.ajax({
url: 'update.php',
type: 'post',
data: $('#your-form-id').serialize(),
success:function(response){
// do something
}
});
Also, you should consider revising your PHP to prevent SQL injection: How can I prevent SQL injection in PHP?