Search code examples
phpmysqlshort-url

Can't get PHP code to work


I have this code, mainly it is meant to create shorurls for my site. But I simply cannot get it to work. Do you see something wrong with it? Is it ok to run a while() inside another one?

$urloriginal = $nt['fecha']."/".$nt['titulolower'];
mysql_query("SET NAMES 'utf8'");
$shortcheck = mysql_query("SELECT * FROM shorturls WHERE urloriginal = '".$urloriginal."' LIMIT 1");
while($urlitem = mysql_fetch_array($shortcheck)) {
    if($urlitem['urloriginal'] !=  "0") {
        echo "http://neutronico.com/u/".$urlitem['id'];
    } else {
        mysql_close($shortcheck);
        mysql_query("INSERT into shorturls (urloriginal) VALUES ('$urloriginal')") 
           or die(mysql_error());
        $shortget = mysql_query("SELECT * FROM shorturls WHERE urloriginal = '".$urloriginal."' LIMIT 1");
        while($urlitem2 = mysql_fetch_array($shortget)) {
            echo "http://neutronico.com/u/".$urlitem['id'];
        };
        mysql_close($shortget);
    };
};

Thank you very much.


Solution

  • The first problem I see is that you're calling mysql_close() mid-script on a result set. Remove the call:

    mysql_close($shortcheck);
    

    mysql_close() is intended to be called on a resource link -- the database connection. Not on a query result resource. It is called implicitly when the script exits, so you needn't call it at all unless you have specific memory requirements. I think you are intending to call mysql_free_result(), but again this is called implicitly and you needn't call it unless you need to manage memory.

    Later, remove this call, as it is not closing a MySQL resource link.

    mysql_close($shortget);