This is a sample of the Vote it Up plugin:
//Run this to create an entry for a post in the voting system. Will check if the post exists. If it doesn't, it will create an entry.
function SetPost($post_ID) {
global $wpdb;
//prevents SQL injection
$p_ID = $wpdb->escape($post_ID);
//Check if entry exists
$id_raw = $wpdb->get_var("SELECT ID FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'");
if ($id_raw != '') {
//entry exists, do nothing
} else {
//entry does not exist
$wpdb->query("INSERT INTO ".$wpdb->prefix."votes (post, votes, guests, usersinks, guestsinks) VALUES(".$p_ID.", '', '', '', '') ") or die(mysql_error());
}
}
//Run this to create an entry for a user in the voting system. Will check if the user exists. If it doesn't, it will create an entry.
function SetUser($user_ID) {
global $wpdb;
//prevents SQL injection
$u_ID = $wpdb->escape($user_ID);
//Check if entry exists
$id_raw = $wpdb->get_var("SELECT ID FROM ".$wpdb->prefix."votes_users WHERE user='".$u_ID."'");
if ($id_raw != '') {
//entry exists, do nothing
} else {
//entry does not exist
$wpdb->query("INSERT INTO ".$wpdb->prefix."votes_users (user, votes, sinks) VALUES(".$u_ID.", '', '') ") or die(mysql_error());
}
}
//Returns the vote count
function GetVotes($post_ID, $percent = false) {
global $wpdb;
//prevents SQL injection
$p_ID = $wpdb->escape($post_ID);
//Create entries if not existant
SetPost($p_ID);
//Gets the votes
$votes_raw = $wpdb->get_var("SELECT votes FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'");
$sinks_raw = $wpdb->get_var("SELECT usersinks FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'");
$guestvotes_raw = $wpdb->get_var("SELECT guests FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'");
$guestsinks_raw = $wpdb->get_var("SELECT guestsinks FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'");
/* Deprecated
$uservotes_raw = $wpdb->get_var("SELECT votes FROM ".$wpdb->prefix."votes_users WHERE user='".$u_ID."'");
$usersinks_raw = $wpdb->get_var("SELECT sinks FROM ".$wpdb->prefix."votes_users WHERE user='".$u_ID."'");
*/
//Put it in array form
$votes = explode(",", $votes_raw);
$sinks = explode(",", $sinks_raw);
$guestvotes = explode(",", $guestvotes_raw);
$guestsinks = explode(",", $guestsinks_raw);
/* Deprecated
$uservotes = explode(",", $uservotes_raw);
$usersinks = explode(",", $usersinks_raw);
*/
$uservotes = 0;
$usersinks = 0;
$initial = 0; //Initial no. of votes [will be placed at -1 when all posts receive votes]
(and so on...)
I've heard from many people that it is a bad practice to go directly to the mysql database. That the code can break up in future versions of Wordpress.
Or it is necessary in some plugins like Vote it Up?
$wpdbor directmysql_querycalls when you're dealing with non-core tables. The biggest issue with that plugin(as i outlined in your other question), in my mind, is how the plugin db tables are structured. – t31os Mar 28 '11 at 12:55