Computers and Technology
Bit.ly API and adding URLs to your MySQL database
In my last tutorial, I’ve touched on how to use the to.ly API and how to make automatic “Tweet it” buttons with a relevant message.
Well, this can get problematic if with every page refresh, your server sends out a request to the to.ly server for a short link. Pretty soon, you’ll be getting “Too Many Connections” and you’re screwed. Just like I was, so here’s an idea. How about we store those links in a database….automatically?
You see, it’s much easier to create a script that will request a shortlink, adds the link to the database, and then just call it up whenever you need it. It works perfectly well on my quote site. Basically, whenever you create a website with get-requests, tons of pages, and all that. You can use the following script to make it all work, automatically (again).
Bit.ly
Let’s get some bit.ly action going here. First, you need to create an account. Then you need to get the bit.ly API key
Next, let’s look at a neat script I found and made a few changes to so you could simply use include() and have a ready function with all the right variables:
// Variables
$bitlylogin = 'loginname';
$apikey = 'long series of numbers that make up your API key';
/* make a URL small */
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
//get the url
//could also use cURL here
$response = file_get_contents($bitly);
//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
return $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
I like to set my function up like this so that I can always interchange values, and so that I will automatically have the right values stored in those two variables above ($bitlylogin and $apikey). You don’t need to do that. You could simply change the function definition like to include defaults:
function make_bitly_url($url,$login = 'loginusername',$appkey = 'long api key',$format = 'xml',$version = '2.0.1')
Now as far as implementation of the script goes, it’s pretty simple:
$url = "Http://www.davepcguy.com"; $shorturl = make_bitly_url($url, $bitlylogin, $apikey); echo $shorturl;
And you’ll get the short url echoed out. If you use the default value version you can simply do this:
$url = "http://www.davepcguy.com"; $shorturl = make_ibtly_url($url); echo $shorturl;
You’re done. Easy enough, eh?
MySQL Database
Believe it, or not. It’s actually rather tricky to add a URL into a database. You have to select the correct format in the table, decode and encode stuff. It’s pretty messy and I have not found a good tutorial online on how to do this.
So here goes, let’s assume you use the method above to create short links. It’ll make life much easier, trust me.
First, let’s create a table in your database:
//login variables
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'sample database';
//connect
$connection = mysql_connect($host, $user, $pass) or die ('Unable to connect!');
//database select
mysql_select_db($db) or die ('Unable to select database!');
//the right query
$query = "CREATE TABLE sample_table
(
id int NOT NULL auto_increment primary key,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL ,
message text NOT NULL,
url varchar(255) NOT NULL
)";
//executing query
$result = mysql_query($query) or die ('Error in Query');
Notice that I used a varchar(255) for the datatype. You could use varchar(55) or any other number. Every shortlink by bit.ly is 20 characters…max. The problem is when you add the information in your database so I recommend a good 255 characters.
Next, you have to make sure you know what you want out of the script. I made a script so that every time my website asked for a row of information, it would automatically add the URL (since I was a bit late with this idea, I had to find a way to add the information without having to recreate the whole database). Also, it’s a good practice to check if the data is present and in case it’s not, add it. Here’s what I did:
//connect
$name = 'sample name';
//query for a particular row with the name
$query = 'SELECT * FROM sample_table WHERE name = $name'';
// execute query
$result = mysql_query($query) or die ("Error in query: $query.".mysql_error());
//check if the url column has anything in it
if (empty($row[4])) {
//if it IS empty, let's make a shortlink
$url = make_bitly_url($permalink,$bitlylogin,$apikey,'xml');
//we have to encode the url. I'll explain that
$url = urlencode($url);
//make a query to update (don't forget the quotation marks!)
$query = 'UPDATE quotes SET url = "'.$url.'" WHERE name = '.$name.'';
//execute query
$urlresult = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
//decode url for later use in the script
$url = urldecode($url);
}
//let's make an else statement in case the information IS present
else {
//let's decode that encoded url
$url = urldecode($row[4]);
}
Now you have the $url variable down! w00t. You can do a bunch of stuff with that. Like implement it in that twitter button I keep talking about. Check out my new site too to see it in action.
Oh about that encoding and decoding. If you try to submit the $url without encoding it, you’ll get an error because the characters “/” and “:” and some of the other ones have a special meaning in SQL. Here’s what the encoded and decoded versions look like:
normal: http://bit.ly/8oQBvB
encoded: http%3A%2F%2Fbit.ly%2F8oQBvB
decoded: http://bit.ly/8oQBvB
As you can see, the encoded version uses the “%” characters (ascii) for the coding.
Don’t forget to encode and decode then!
I hope you enjoyed my tutorial ![]()
| Print article | This entry was posted by Admin on December 21, 2009 at 17:16, and is filed under PHP and Scripting, Tutorials. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |


about 2 years ago
I think this website screwed your code. It says & and ". Think it should be & and ” but okay, I hope people understand that. Otherwise they can read it in this comment! Nice tut though.
about 2 years ago
yeah, it’s pretty damn annoying. I’ve already had to fix it about five different times but it keeps reverting back. Ever since I upgraded to the 2.9 WordPress.
urgh
about 2 years ago
the comments even return “&” instead of “&”. That’s just not cool. I Typed “&”
about 2 years ago
damned, & amp; <— Without Space!
about 2 years ago
i’m john!
Nice to meet all of you!
about 2 years ago
winsome answers i like it