How do I store changing data into a database?
-
22-07-2019 - |
Question
I made an application to take the now playing title and artist from an internet radio stream, and I have it displaying in plain text on this page:
http://thelisthq.net/z1035.php
The output is simply a php 'echo $variable' command, but $variable is constantly changing, so how do I store each different value of $variable into a database. The end plan to to keep a list of all the songs that play over a certain period of time.
Solution
You'll have to set up the php script to run every x minutes or so, and instead of echoing the result, check the most recent database entry against the currently playing song, and if it is different, add a new record.
First, some SQL to set up a new table:
CREATE TABLE SongList (
ID int primary key auto_increment not null,
Song char(255) not null,
PlayTime Datetime not null
);
Then, modify your PHP script to insert records in the database instead of echoing to the screen:
<?php
$song = get_song(); //not sure how you're doing that
$sql = "SELECT Song FROM SongList ORDER BY PlayTime DESC LIMIT 1";
list($prevSong) = mysql_fetch_row(mysql_query($sql));
if ($song !== $prevSong) {
$sql = "INSERT INTO SongList (Song, PlayTime) VALUES ('$song', NOW())";
mysql_query($sql);
}
?>
Set up a scheduled task or a cron job to run php -f z1035.php
every minute.
To see the entire list of songs, create a new php file station_history.php
<html>
<body>
<pre>
<?php
$sql = "SELECT Song, PlayTime FROM SongList LIMIT 20"; // Just the last 20 songs
$result = mysql_query($sql);
while(list($song, $playtime) = mysql_fetch_row($result)) {
echo "[$playtime] $song\n";
}
?>
</pre>
</body>
</html>