Hello people please help me with this! what i want to achieve is similar to twitter update notification bar that displays the number of new tweets and when you click on it; it drops the latest tweets on the previous tweets. i have been banging my head over this for days now, Here is what i tried.
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
interval = setInterval(function(){
check_update($latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data);
}); //checks for number of updates
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty($_POST['get_num_update']) && is_numeric($_POST['get_num_update']))
{
$old_feed = $_POST['get_num_update'];
$query = "SELECT id FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$num_updates = mysqli_num_rows($exec);
echo ($num_updates > 0) ? $num_updates.' new updates' : '';
}
if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
//
when the user clicks on the update_bar div which will be displaying something like '5 new updates' i want the update to pull down the latest feed from the hidden div, so everything doesn't really work as i would expect someone please help me out
Not tested, but it should approximately work...
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
// made the parameter of check_update a js variable and not hard coded in PHP
var latest_new=$latest_news;
// add a temp js variable for the last feed received (but not displayed)
var last_received=$latest_news;
interval = setInterval(function(){
check_update(latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
// change your AJAX request to deal with JSON data and received several informations (number of new feed, insertion time of the last one)
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data.number_recents+" new updates.");
last_received=data.last_time;
},'json');
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
latest_new=last_received;
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty(get_num_update']))
{
// header to serve JSON data
header('application/json');
$old_feed = $_POST['get_num_update'];
// request the number of new feed and the mst recent insertion time
$query = "SELECT count(*) as number,max(insertion_time) as last_time FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$feed_info = mysqli_fetch_assoc($exec);
//write the JSON data
echo '{"number_recents":'.$feed_info['number'].',"last_time":'.last_time.'}';
} else if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
Related
Im trying to make my Webpage do an action (in this case play a sound) on the event of the highest ID (auto_increment) in my SQL table increasing, which happens when a new user is registered. E.g. : 3 users registered, highest ID = 3. When a new user registers, highest ID = 4. Webpage echos/plays sound if this happens.
The Js and PHP, respectively:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['firstName'];
echo $row['lastName'];
echo $row['inOrOut'] . '<br>';
$numId = $row['ID'] . '<br>';
echo $numId;
}
$value = 1;
$value = $numId;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
}
else
echo "nothing detected";
}
}
?>
As you can tell, I tried doing something with comparing the last and the newest ID value but failed miserably.
My attempt would be to store an initial value for oldID and then comparing this to newID before replacing it.
You can't do that only with PHP. But you could do it like this:
If you have a website, you set the current highest ID in the output of php. You can use javascript to call another php script every 5 minutes (or any other time span you find meaningful) that gives you back the current highest number. If the number from the php script is higher, than the number you have in javascript, you can let javascript play a sound for you.
Assuming your php script returns an id like this:
{"id":4}
an example for the javascript call would be this:
<html>
<head></head>
<script>
let highestId = 2;
window.setInterval(async function(){
const response = await fetch('http://localhost/jstest/index.php');
const myJson = await response.json();
console.log(console.log(myJson.id));
if (highestId < myJson.id) {
highestId = myJson.id
// here you can play your sound
$s = document.getElementById('myId');
$s.innerHTML = highestId;
}
}, 5000);
</script>
<body>
<span id="myId">0</span>
</body>
</html>
You can use a cookie variabale to do this. Set the cookie value using php and send the cookie value with php file call. This way you can identify a new highest id.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
var id = getCookie("highest_id");
$('#show').load('data.php?id='+id)
}, 3000);
});
</script>
Add set cookie in the code if the value is changed.
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
$numId = 0;
if ($row = $result->fetch_assoc()) {
$numId = $row['id'];
}
$value = $_GET['id'] ?? 0;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
setcookie("highest_id", $numId, time() - 3600);
} else {
echo "nothing detected";
}
}
?>
Note the points :
In PHP : setcookie("highest_id", $numId, time() - 3600);
In Script : getCookie("highest_id");
I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
I am building a website and I can not figure out one thing. I need a script that checks if 10 seconds have past since load time, then it would run another PHP script. But I am not sure if it is possible. I have attached my attempt at this problem. Any ideas? Thanks in advance!
if (
<script type="text/javascript">
function viewplus(){
}
setTimeout(viewplus, 10000);
</script>
)
$query = "SELECT * FROM users WHERE id=" . $rws2['id_user'];
$result2 = mysqli_query($db, $query);
$rws2 = mysqli_fetch_array($result2);
$views_total = $rws2['views_total'] + 1;
$views_week = $rws2['views_week'] + 1;
$views_today = $rws2['views_today'] + 1;
$id = $rws2['id'];
$query = "UPDATE users SET views_total='$views_total',views_week='$views_week',views_today='$views_today' WHERE id='$id'";
mysqli_query($db, $query);
It is possible using jQuery like this:
Put your code in a php file and call it after 10 seconds after page load with
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('index.php');
}, 10000);
});
</script>
Example of updating a table and receiving a status message:
if (isset($_POST['id'])&&
isset($_POST['var'])){
$con = new mysqli("localhost", "my_user", "my_password", "world");
$id = $con->real_escape_string($_POST['id1']); //In our example id is INT
$var = $con->real_escape_string($_POST['var']);
$result = $con->query("UPDATE table SET value = '$var' WHERE id = $id);
(!$result) ? echo "Update failed!" : "Update succeeded";
}
This will load the output of your php file(Update filed or succeeded) in a element (this case one with id some_id).
Another way which I DO NOT recommend is using PHP's sleep() function PHP Documentation
I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.
I want to get the clicked number
and load the data from the database according to this number. The column that the numbers are stored is named as id.
I have this code in order to display the numbers(id)...
$sql = "SELECT id FROM work WHERE username='$username' order by id asc limit 10;";
$result = mysql_query($sql);
if ($result != 0) {
$num_results = mysql_num_rows($result);
for ($i=0;$i<$num_results;$i++) {
$row = mysql_fetch_array($result);
$id = $row['id'];
echo '' .$id. '';
}
}
And then I want to load the data from this number in a form which the code for the form is...
function kotoula() {
$username = $_SESSION["username"];
if($query = mysql_query("SELECT job_title,company,website,start_date,end_date,start_year,end_year,work_history FROM work WHERE id>'$id' AND username='$username' order by id asc limit 10") or die(mysql_error()))
{
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$job_title = $row['job_title'];
$company = $row['company'];
$website = $row['website'];
$start_date = $row['start_date'];
$end_date = $row['end_date'];
$start_year = $row['start_year'];
$end_year = $row['end_year'];
$work_history = $row['work_history'];
}
}
}
}
Just put it in the URL using GET. Something like:
http://yoururl.com/user.php?id=12345
Then, user.php will receive that value on $_GET array. Example:
$_GET['id'];