Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>MySQL:</p> <pre><code>CREATE TABLE song ( song_id INT UNSIGNED NOT NULL AUTO_INCREMENT, vote INT NOT NULL DEFAULT 0, PRIMARY KEY(song_id) ); </code></pre> <p>JavaScript:</p> <pre><code>$(function() { var listContainer = $("#daily-songs"), songs = []; var songSort = function(a, b) { return +b.vote.text() - +a.vote.text(); }; var submitVote = function(song, delta) { $.post("vote.php", { id: song.node.attr("id").match(/\d+$/)[0], delta: delta, }, function(data) { if ( data != 'success' ) { alert(data); } } ); $.each(songs.sort(songSort), function() { listContainer.append(this.node); }); }; listContainer.find("li").each(function() { var $this = $(this); var song = { node: $this, vote: $this.find(".votes") }; $this.find(".vote-up").click(function() { submitVote(song, 1); }); $this.find(".vote-down").click(function() { submitVote(song, -1); }); songs.push(song); }); }); </code></pre> <p>PHP:</p> <pre><code>&lt;?php $song_id = !empty($_POST['id']) ? (int)$_POST['id'] : 0; $delta = !empty($_POST['delta']) ? (int)$_POST['delta'] : 0; if (!$song_id || !$delta || !is_int($song_id) || !is_int($delta)) { die("Invalid parameters"); } // Make sure the voting value is within the valid range. if ($delta != -1 &amp;&amp; $delta != 1) { exit("Invalid delta"); } // Check to see if user has already voted for this song session_start(); if (isset($_SESSION['voted'])) { exit("You already voted!"); } // If they haven't voted yet, connect to the database // YOU NEED TO CHANGE THIS INFOMATION TO WHATEVER APPLYS TO YOU. $dsn = 'mysql:dbname=testdb;host=127.0.0.1'; $user = 'dbuser'; $password = 'dbpass'; try { $dbh = new PDO($dsn, $user, $password); } catch (PDOException $e) { exit('Connection failed: ' . $e-&gt;getMessage()); } // If the database connection is succesful, update song entry // UPDATE daily_song SET votes=votes+$delta WHERE daily_song_id=$songId $sth = $dbh-&gt;prepare('UPDATE song SET votes = votes + :delta WHERE song_id = :song_id'); $sth-&gt;bindParam(':delta', $delta); $sth-&gt;bindParam(':song_id', $song_id); if (!$sth-&gt;execute()) { exit("Unable to update votes"); } exit("success"); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload