質問

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.

役に立ちましたか?

解決

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);

他のヒント

Yes, it's OK to nest while statements.

The main problem that I didn't spot at first is that you're closing your connection in the middle of the query, thus remove all mysql_close statements.

However, after you solve this, you'll face another problem, since you're using only one MySQL connection, the second query loses all results of the first query, so probably you stop at the first row, or the first time the else branch gets executed.

To make it work, you' can choose one of the two options:

  • use two MySQL connections, and specify which one to use with the $link_identifier parameter mysql_query ( string $query [, resource $link_identifier ] )
  • run the first query, save all results in an array and then run the other queries, so the queries don't overlap. Use this option only if your table isn't too big.

Michael also suggested to check that your $urloriginal has been sanitized with mysql_real_escape_string(), or you face a risk of SQL injection.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top