1

我有这段代码,但是当我尝试执行它时,它给出了以下错误:
Fatal error: Cannot redeclare genereerLiveCodeP() (previously declared in livestream.php:33) in livestream.php on line 32.

session_start();

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

//header("location: index.php");
if($_SESSION['***'] == '***'){
$fp = fopen("test.html", 'w');
fwrite($fp, "");
fwrite($fp, '<p class="green">*** is online</p>');



$result = mysql_query("select count(1) FROM ***");
$row = mysql_fetch_array($result);

$rows = $row[0]+1000;

echo "Rows: ".$rows."\n";

for ($id = 1000; $id < $rows; $id++) {

echo "ID: ".$id."\n";

function genereerLiveCodeP () {
        $lengthCode = 6;
        $characters = '1234567890abcdefghijklmnopqrstuvwxyz';
        $liveCodeFunction = '';

        for ($p = 0; $p < $lengthCode; $p++) {
        $liveCodeFunction .= $characters[mt_rand(0, strlen($characters))];
    }

    return $liveCodeFunction;
}

$livecode = genereerLiveCodeP ();

echo "Livecode: ".$livecode."\n";

$x = mysql_query("UPDATE *** SET livecode='".$livecode."' WHERE *** = '".$***."'");

echo $x."\n";

}



}

我该怎么办?

4

3 回答 3

1

for声明function. 您的代码应如下所示:

...
for ($id = 1000; $id < $rows; $id++) {
echo "ID: ".$id."\n";
}

function genereerLiveCodeP () {
...
于 2013-02-09T22:13:36.217 回答
1

首先,您使用的是已弃用的扩展名 ( ext/mysql)。

您需要将函数移到for循环之外。PHP 不能那样工作(重新声明函数是不可能的,因此会出现错误)

如果您使用准备好的查询,您可以获得更大的性能提升,并且拥有更多面向未来的代码(当这些函数开始抛出错误时,您的代码将在 PHP 5.5 中中断)

session_start();
$db = new mysqli($host, $username, $password, $db_name);
function generate_live_code($length = 6) {
    $characters = '1234567890abcdefghijklmnopqrstuvwxyz';
    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= $characters[mt_rand(0, strlen($characters))];
    }

    return $str;
}

//header("location: index.php");
if($_SESSION['id'] == 'debug') {
    $fp = fopen("test.html", 'w');
    fwrite($fp, "");
    fwrite($fp, '<p class="green">*** is online</p>');
    // writing html to a file? consider using a database...
    $result = $db->query("select count(1) FROM x");
    $row = $result->fetch_assoc($result);
    $rows = $row[0]+1000;

    echo "Rows: $rows\n"; // no need to concat with double quotes.
    if ($query = $db->prepare("UPDATE x SET livecode = ? WHERE id = ?")) {
        for ($id = 1000; $id < $rows; $id++) {
            echo "ID: ".$id."\n";
            $livecode = generate_live_code();
            echo "Livecode: $livecode\n";
            $query->bind_param("si", $livecode, $id);
            $query->execute();
        }
    }
}
于 2013-02-09T22:42:04.827 回答
0

genereerLiveCodeP()在循环中声明函数,尝试将其放在文件的开头。

于 2013-02-09T22:14:51.627 回答