I found a script that uses php long polling.
It uses the following code to see if the text file is changed and returns the content.
This is received by the browser.
How can i change this to read a table and see if there are new events ?
$filename= dirname(__FILE__)."/data.txt";
$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
}
$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);
I have a table where there are 'posts'. post_id,content,user_id,posted_time
How can i know if theres a new post ?
You basically just have to fetch a new result, thats it, if you want to check if there are new results since the last execution of the script you have to save the output somewhere (is that what you want to do?)
See the following code, for a regular MySQL query:
<?php
// Connect to your MySQL DB
#$db = mysqli_connect("localhost", "root", "", "database");
// Check connection and echo if an error occurs
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
// Execute SQL Query, replace this with your Query (maybe the one I put in fits for your needs)
$query = mysqli_query($db, "SELECT * FROM posts");
// Transform the result into an array if your you got new elements in the MySQL DB.
$resultat = mysqli_fetch_assoc($befehl);
// Close connection
mysqli_close($db);
?>
Related
I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!
I'm building a mobile application that requires push notifications to be sent whenever a new post is added.
Here's the PHP notification script: (it should be added inside the loop so it will be used again for each result.
$to = (should get DEVICEID from the database).
$title = "A new request"
sendPush($to,$title,$message);
function sendPush($to,$title,$message){
//Sends noti.
}
So How do I place the above code in a while loop, and get the DEVICEID from the database and place it into $to ?
I suppose that you have an mysql connection set up and that you are using mysqli.
After you have created the connection to the database, you should have a variable holding your connection:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
So right now you are able to execute a SQL statement to your database. Your SQL statement should look similarily to this:
$sql = "SELECT DeviceID FROM Devices";
Now we can execute the statement we created to the database:
$result = mysqli_execute($con, $sql);
Now we get a result object. We can use this to get a while loop:
while ($row = mysqli_fetch_assoc($result)) {
$to = $row["DeviceID"];
// Rest of your code, this will be executed for every DeviceID in the database.
}
If you are using PDO you can read more about it here: http://php.net/manual/en/ref.pdo-mysql.php
But in general, the steps are the same.
I am using a PHP script to pull comments from my database to populate an app. How the database is set up is any secondary comments, ie replies to comments, will have a reply_id. The issue im seeing is all comments, regarless of replies, are seeing the same replies as the one comment that has it. I tried deleting the array with the secondary comments in it, but to no avail. Could someone point out where I failed to seperate the values?
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
$memory_id=$_POST['memory_id'];
$query ="Select * FROM comment WHERE memory_id= '$memory_id' and reply_id=''";
$dbquery = mysqli_query($conn,$query);
$query2= "Select * FROM comment WHERE memory_id='$memory_id' and reply_id='$comment_id'";
if($dbquery){
$result = array();
while($row = mysqli_fetch_array($dbquery))
{
$temp_array= array();
unset($temp_array['replys']);
$temp_array['user_id']=$row['user_id'];
$temp_array['comment_id']=$row['comment_id'];
$temp_array['text']=$row['comment'];
$comment_id= $row['comment_id'];
$temp_array['replys']=array();
$dbquery2 = mysqli_query($conn,$query2);
if($dbquery2){
while ($row2 = mysqli_fetch_array($dbquery2)){
$temp_array['replys'][]=array(
'user_id'=>$row2['user_id'],
'comment_id'=>$row2['comment_id'],
'text'=>$row2['comment']);
}//Feeds comments
array_push($result, $temp_array);
}
}//pulls initial command
echo json_encode($result);
}
else
{
$response["error"] = TRUE;
$response["error_msg"] = "No memory FOund";
echo json_encode($response);
}
?>
The second query is being executed with $memory_id having the value of $_POST['memory_id']. An easy solution is to move the $query2 line below $memory_id = $row['memory_id'], that way the second query will be executed with the correct memory_id value.
EDIT
A better solution is to prepare your queries instead. Check the mysqli_prepare function.
Can anyone see what the problem with my code is / where im going wrong?
I know i have the correct host,database,user and password.
This is the code in the php file, it should get all the details available on the players from my sql database, however if i go on the page it just gives me a white page. Im using go daddy as a host and my database is also on there.
Any ideas? thanks
<?php
$host = "abc12345"; //Your database host server
$db = "abc12345"; //Your database name
$user = "abc12345"; //Your database user
$pass = "abc12345"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
} else {
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$query = "SELECT * FROM Player";
$resultset = mysql_query($query);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The script is all right, I checked it with a different query.
Assuming that the table Player is not empty, the error can be either with your raw sql query (as pointed by #Sharikov in comments), otherwise the error is with the way you have configured your godaddy server.
For debugging that, I would suggest inserting dummy print_r or echo statements before you execute the query, and going through your apache logs at /var/log/apache2/access.log.
Also make sure that you don't have any core php package missing on your server (like php5-mysql if you use mysql).
I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.