Better mysqli table creation

<?php
$mysqli = new mysqli(DB_SERVER,DB_USER,DB_PASS,DB_NAME);

if($mysqli->connect_errno) echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "n";

$query = "CREATE TABLE hwt_tools(
id mediumint(8) NOT NULL AUTO_INCREMENT,
user_id mediumint(8),
category_id mediumint(8),
target_url varchar(255),
favicon_url varchar(255),
desc_text text,
UNIQUE KEY id (id)
);";

//Use this to safely create a table while testing
if(!$mysqli->query($query)) echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

//Use this to drop existing table and start a new
//if(!$mysqli->query("DROP TABLE IF EXISTS hwt_tools") || !$mysqli->query($query)) echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

?>

Query by term and custom field

<?php
$query = "
SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->terms.slug = 'tvlt-notes'
AND $wpdb->term_taxonomy.taxonomy = 'tvlt_category'
AND $wpdb->postmeta.meta_key = 'tvlt_sort'
AND $wpdb->postmeta.meta_value <> '9999'
";

$tvlt_posts = $wpdb->get_results($query, OBJECT);
?>

Count posts in taxonomy

<?php

global $wpdb;
$query = "
SELECT COUNT( DISTINCT cat_posts.ID ) AS post_count
FROM wp_term_taxonomy AS cat_term_taxonomy INNER JOIN wp_terms AS cat_terms ON
cat_term_taxonomy.term_id = cat_terms.term_id
INNER JOIN wp_term_relationships AS cat_term_relationships
ON cat_term_taxonomy.term_taxonomy_id = cat_term_relationships.term_taxonomy_id
INNER JOIN wp_posts AS cat_posts
ON cat_term_relationships.object_id = cat_posts.ID
WHERE cat_posts.post_status = 'publish'
AND cat_posts.post_type = 'post'
AND cat_term_taxonomy.taxonomy = 'my_taxonomy'
AND cat_terms.slug IN ('term_slug','term-slug2')
";
return $wpdb->get_var($query);
?>