Hi everyone, I have been trying to update a mysql database with the shortend url I get from bit.ly

I have the shortend url displayed on the page, but everytime I try and update mysql with the variable
$bitlylink.. instead of http://bit.ly/123abc the database is updated with

How can I update the database with the correct url I get back from bit.ly

$link = "$bitlyslug";
$bitlylink = "$link"; 
$suiid = "$suiid";

print getSmallLink($link); 

function getSmallLink($longurl){  
// Bit.ly  
$url = "http://api.bit.ly/shorten?version=2.0.1";  

$s = curl_init();  
curl_setopt($s,CURLOPT_URL, $url);  
$result = curl_exec($s);  
curl_close( $s );  

$obj = json_decode($result, true);  
return $obj["results"]["$longurl"]["shortUrl"];  


// update shorturl 
        // add short url to db -                    
        mysql_query ("UPDATE table SET bitly='$bitlylink' WHERE var='$var_val'")
        or die(mysql_error());
        // end short url update

If someone good show me why I am getting the wrong url added to my databse that would be great...

Recommended Answers

All 3 Replies

Can you dump the curl result, and paste it here.

Member Avatar

does this work? I thought you had to login to get bitly to work. Do a print_r on the $obj in your function.

commented: that's the problem +0

As diafol pointed, you are not doing the login in your curl request. Anyway I use this function, that make use of file_get_contents() and works pretty well:


function getlink($url)
    $version = '2.0.1';
    $format = 'xml';
    $login = 'username';
    $appkey = 'API_KEY';
    $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;

    $response = file_get_contents($bitly, TRUE);

    if($response !== FALSE)
        $xml = simplexml_load_string($response);
        $link = 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
        return $link;
    } else {
        return FALSE;

echo getlink('http://www.website.tld');


which is based on http://davidwalsh.name/bitly-php

commented: nice +14
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.