I made a server that checks if people are online if they logged in, and want to put that information into a html table.
<?php
session_start();
include_once '../php\connect.php';
function removeRefresh(){
$query = connection()->prepare("UPDATE `online` SET `time` = `time`+1");
$query->execute();
$query = connection()->prepare("DELETE FROM `online` WHERE `time` > 5");
$query->execute();
}
function addOrRefresh($ID){
$query = connection()->prepare("SELECT COUNT('id') FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
$count = $query->fetchColumn();
if($count == 0){
$query = connection()->prepare("INSERT INTO `online`(`ID`, `time`) VALUES(:ID, 0)");
$query->bindParam(':ID', $ID);
$query->execute();
}
else{
$query = connection()->prepare("UPDATE `online` SET `time` = 0 WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
}
$action = filter_input(INPUT_GET, 'action');
if($action == 'heartbeat'){
removeRefresh();
$ID = $_GET['id'];
addOrRefresh($ID);
$query = connection()->prepare("SELECT u.username FROM `nusers` u INNER JOIN `online` o ON o.ID = u.ID");
$query->execute();
$onlineUsers = $query->fetchAll(PDO::FETCH_ASSOC);
$resultaat = "";
foreach($onlineUsers as $user){
$resultaat .= "<p>{$user['username']} <br></p>";
}
echo "$resultaat";
}
?>
You can register, and when you log in into the lobby, you are added into an 'online' table, that checks every second with the function 'heartbeat'.
Please excuse my poor English.
EDIT: I have systems working. I merely want to change the 'echo "$resultaat"' so that it puts the $resultaat into a tablerow.
adding after a '}' won't work, I've tried working around that, not certain if I tried all posibilities in that retrospect. After request, I've posted the entire document.
the other javascript part is integrated into another document; containing:
<?php
session_start();
$ID = $_SESSION['ID'];
if (isset($_POST['logout'])) {
session_destroy();
$query = connection()->prepare("DELETE FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
?>
<html>
<head>
<title>Stratego</title>
<Link href="../layout/style.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="./js/HeartBeat.js"></script>
<script>
$(document).ready(function () {
heartbeat.setSpelerId( <?php echo $ID; ?> );
heartbeat.polling();
});
</script>
</head>
<body>
<form method='post' name='logout' action="../setup/logout.php">
<input type='submit' name='loggout' value='Log me out'>
</form>
Singleplayer
<div id="online-list">
</div>
</body>
<?php echo "<script>
function heartbeat(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById(\"online-list\").innerHTML = xhttp.responseText;
}
};
xhttp.open(\"GET\", \"./wachtruimterInterface.php?action=heartbeat&id=" . $ID . "\", true);
console.log('keeping in touch ༼つ ◕_◕ ༽つ');
xhttp.send();
}
setInterval(heartbeat, 1000);
</script>"; ?>
</html>
The console log is there to check if the connection is being maintained. People use their ID to login, no passwords.
This is how it looks now, with 1 person being online; named Luuk.
http://www.filedropper.com/screenproof
My goal is to get all the people that are online into a table.
I've tried
$resultaat .= "<tr><td>{$user['username']} <br></td></tr>";
}
echo "<table>$resultaat</table>";
Just now, doesn't seem to work, any tips on how to progress?
I've fixed the issue;
$resultaat = "";
foreach($onlineUsers as $user){
$naam= $user['username']
$resultaat .= "<tr><td>$naam</td></tr>";
}
echo "<table border=1>$resultaat</table>";
Related
This is my deleteriddle.php but it doesn't work. Please help me
<?php
require("dbcon.php");
$ridid = isset ($_GET['riddleid'])?$_GET['riddleid']:"";
$query = sprintf("DELETE FROM riddle WHERE riddleid= '$ridid'");
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
else {
echo '<script type="text/javascript">
alert("Riddle successfully delete");
window.location.href = "viewriddle.php";
</script>';
}
mysql_close($dbcon);
?>
Try this :
$query = sprintf("DELETE FROM riddle WHERE riddleid= %u", $ridid);
I am selecting input values from the database and I want to send it to the javascript function addVal() so that I can retrieve this value. I do not want to use echo. It is not working right now and I don't know how I can make it work.
<h1>trial,</h1>
<div id ="val"> </div>
<?php
$name = $_POST['postname'];
$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name="big";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected";
$sql = "SELECT input FROM trial_db";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$value = $row['input'];
addVal ($value);
}
}
?>
<script>
function addVal (value){
document.getElementById("val").innerHTML+= value ;
}
</script>
Calling js function from php will not work remove that code from php.
And change in js.
<script>
function addVal (){
var value = "<?php echo $value; ?>";
document.getElementById("val").innerHTML+= value ;
}
</script>
Will only work if js and php codes are in same php file.
I'm trying to make a program that takes 5 words from a database randomly and inserts them into an array. The page initially loads as desired, but nothing happens after the button is clicked. None of the alerts are ever triggered, so the function must never be entered, but why is beyond me. Also, I get an error saying name isn't a legitimate index (referencing line 13) the first time I try running it on a browser, so advice about that would be great too.
lingo.php:
<?php
session_start();
if (empty($_POST["name"])):
$_SESSION["error"] = "You did not enter a name.";
header("Location: entername.php");
else:
$name = $_POST["name"];
setcookie("name", "$name", time()+3600);
endif;
?>
<html>
<head>
<b>Welcome to Lingo, <?php echo $_COOKIE["name"]; ?></b><br />
<script src = "http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript" language = "javascript">
var arr = [];
function collectWords() {
$.post("getWord.php",
function(data) {
arr[word1] = $(data).find("Word1").text();
alert("function reached");
alert(arr[word1]);
arr[word2] = $(data).find("Word2").text();
alert(arr[word2]);
arr[word3] = $(data).find("Word3").text();
alert(arr[word3]);
arr[word4] = $(data).find("Word4").text();
alert(arr[word4]);
arr[word5] = $(data).find("Word5").text();
alert(arr[word5]);
});
}
</script>
</head>
<body>
<table id = "theTable" border = "1" class = "thetable"> </table>
<input type = "submit" value = "Start" onclick = "collectWords()">
</body>
</html>
getWord.php
<?php
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
if ($db->connect_error):
die ("Could not connect to db " . $db->connect_error);
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word1>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word1>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word2>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word2>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word3>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word3>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word4>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word4>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word5>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word5>";
else:
die ("DB Error");
endif;
?>
You get the error on $_COOKIE["name"]; because said cookie isn't set until you set it. You don't set the cookie until someone has entered their names, so on the first load it will give an error.
http://www.thesitewizard.com/php/set-cookies.shtml
"Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:"
Found under the header: "How to get the contents of a cookie.
Fix this with a shorthand if statement, like so:
<b>Welcome to Lingo,
<?php isset($_COOKIE["name"]) ? $_COOKIE["name"] : $_POST["name"]; //Checks if the cookie is set. If not, uses the $_POST name ?>! </b><br />
I have another question:
Why are your words requested 1 at a time? Why not get all 5 words in 1 query? Also, why send them back as XML data? Since you seem to be handling the data yourself, I would personally recommend a simple loop on the PHP side, returning it as a handy pre-made JSON array.
edit: Also important, PHP does not echo any content automatically. An AJAX call can only receive printed data. You need to echo your results at the end of your php script or you will return nothing
Like so:
$query = "select word from Words order by rand() limit 5";
$result = $db->query($query);
$rows = $result->num_rows;
$array = array();
if ($rows >= 1):
$i = 0;//start the wordcount
//While there are results, loop. (Results are limited to 5, so it won't loop more than 5 times)
while($row = $result->fetch_row()){
$i++;//Put this on top so it starts with "1"
$array["word$i"] = $row[0]; //create the array
}
echo json_encode($array); //Turn array into json and echo it.
else:
die ("DB Error");
endif;
Now, you will also need to change your Javascriptside a tiny bit.
This is how you will access the new array (created by php)
<script type = "text/javascript" language = "javascript">
function collectWords() {
$.post("getWord.php",
function(data) {
alert(data); // show whether you get any data back in the first place. thanks #jDo
var arr = $.parseJSON(data);
alert(arr.word1);
alert(arr.word2);
alert(arr.word3);
alert(arr.word4);
alert(arr.word5);
});
}
</script>
As you can see, this way saves you quite a lot of code and saves you a lot of word replacements
please friends i want to run a javascript code to load a php page which is based on $_GET variable. here is the actual page:
<?php
$online = mysqli_query($con, "SELECT * FROM (SELECT user as user FROM online) as a INNER JOIN
(SELECT one as f1 FROM friends WHERE two='$my_id'
UNION SELECT two as f2 FROM friends WHERE one='$my_id') as b
ON a.user = b.f1");
while($query = mysqli_fetch_array($online)){
$active = $query['user'];
$first = getuser($active, 'first');
$nick = getuser($active, 'nick');
$last = getuser($active, 'last');
?>
<?php
echo "<font class='driver'>$first $nick $last</font>";
<div style="width:100%;height:82%;overflow-x:no;overflow-y:auto;" id="show">
<script type="text/javascript" src="jscript.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('active_chat.php')
}, 2000);
});
</script>
</div>
so i want this line $('#show').load('active_chat.php') to look something like this $('#show').load('active_chat.php?id=$active') so that it will display information entered by only a user for each $active, here is the active_chat.php;
<?php
include 'connect.php';
include 'functions.php';
$my_id = $_SESSION['user_id'];
$user = $_GET['id'];
$query = mysqli_query($con, "SELECT * FROM all_msgs WHERE (my_id='$my_id' AND user_id='$user') OR (my_id='$user' AND user_id='$my_id') AND delet !='$my_id' ORDER BY id DESC");
while($sql = mysqli_fetch_array($query)){
$msg = $sql['msg_body'];
$sender = $sql['my_id'];
$first = getuser($sender, 'first');
$nick = getuser($sender, 'nick');
$last = getuser($sender, 'last');
$photo = getuser($sender, 'photo');
echo $first." ".$nick." ".$last;
} ?>
So I have a user page in which I include several tables, one of which uses a pagination script that is handled by javascript (so that I dont have to refresh the page when looking through the pages) now I'm trying to include this on my user.php page but it doesnt seem to work, any help appreciated
User.php page
<?php require 'session.php';
require 'header.php';
require 'includes/database.php';
$userid = $_GET['id'];
$con = mysql_connect($servername, $username, $password);
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname);
//CLIENT INFO TABLE
include 'user/clientinfo.php';
echo "<br>";
// XLRSTATS TABLE
include 'user/xlrstatsinfo.php';
echo "<br>";
//ALIAS TABLE
include 'user/aliases.php';
//IP TABLE
include 'user/ipaliases.php';
//PENALTY TABLE
include 'user/penalties.php';
//PENALTY TABLE
include 'user/userchatlog.php';
?>
userchatlog.php page
<?php
require '../session.php';
?>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="../images/ajax-loader.gif" />
</div>
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<script type = "text/javascript" src = "../includes/js/jquery-1.7.1.min.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload
getdata( 1 );
});
function getdata( pageno ){
var targetURL = '../includes/pagination/userchatlog/search_results.php?page=' + pageno;
$('#retrieved-data').html('<p><img src="../images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
and my search_results.php
<!-- include style -->
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<?php
//open database
include '../../database.php';
//include our awesome pagination
//class (library)
include 'ps_pagination.php';
//connect to mysql server
$mysqli = new mysqli($servername, $username, $password, $dbname);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
function _ago($tm,$rcs = 0) {
$cur_tm = time(); $dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no); if($no <> 1) $pds[$v] .='s ago'; $x=sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
return $x;
}
//query all data anyway you want
$sql = "SELECT * FROM chatlog WHERE msg NOT LIKE '%RADIO%' ORDER BY id DESC";
//now, where gonna use our pagination class
//this is a significant part of our pagination
//i will explain the PS_Pagination parameters
//$conn is a variable from our config_open_db.php
//$sql is our sql statement above
//3 is the number of records retrieved per page
//4 is the number of page numbers rendered below
//null - i used null since in dont have any other
//parameters to pass (i.e. param1=valu1¶m2=value2)
//you can use this if you're gonna use this class for search
//results since you will have to pass search keywords
$pager = new PS_Pagination( $mysqli, $sql, 45, 4, null );
//our pagination class will render new
//recordset (search results now are limited
//for pagination)
$rs = $pager->paginate();
//get retrieved rows to check if
//there are retrieved data
$num = $rs->num_rows;
if($num >= 1 ){
//creating our table header
echo "<table id='my-tbl'>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Name</th>";
echo "<th>Message</th>";
echo "</tr>";
//looping through the records retrieved
while( $row = $rs->fetch_assoc() ){
$msg=$row['msg'];
$team=$row['client_team'];
$team = str_replace("42","<img src=images/green.png>",$team);
$team = str_replace("3","<img src=images/red.png>",$team);
$team = str_replace("2","<img src=images/blue.png>",$team);
$team = str_replace("1","<img src=images/grey.png>",$team);
$msg = str_replace("^0","</font><font color=black>",$msg);
$msg = str_replace("^1","</font><font color=red>",$msg);
$msg = str_replace("^2","</font><font color=lime>",$msg);
$msg = str_replace("^3","</font><font color=yellow>",$msg);
$msg = str_replace("^4","</font><font color=blue>",$msg);
$msg = str_replace("^5","</font><font color=aqua>",$msg);
$msg = str_replace("^6","</font><font color=#FF00FF>",$msg);
$msg = str_replace("^7","</font><font color=white>",$msg);
$msg = str_replace("^8","</font><font color=white>",$msg);
$msg = str_replace("^9","</font><font color=gray>",$msg);
$name=$row['client_name'];
$name=htmlentities($name);
$time=$row['msg_time'];
echo "<tr class='data-tr' align='center'>";
echo "<td align=center>";
echo _ago($time);
echo "</td>";
echo "<td align=center>";
echo $team;
echo "<a href='http://144.76.158.173/ech/user.php?id=".$row["client_id"]."' > $name </a></td>";
echo "<td align=left> $msg </td>";
echo "</tr>";
}
echo "</table>";
}else{
//if no records found
echo "No records found!";
}
//page-nav class to control
//the appearance of our page
//number navigation
echo "<div class='page-nav' align='center'>";
//display our page number navigation
echo $pager->renderFullNav();
echo "</div>";
?>