通过PHP和MySQL查询将一批密钥提交到数据库

时间:2014-01-27 04:09:54

标签: php mysql

我正在生成一批密钥,然后将它们提交到一个数据库,该数据库有一个名为“keycode”的列,如下所示:

$connect=mysqli_connect("localhost","myusername","mypassword","mydatabase");

     if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
          exit;
     }

$keycount=0 ;

while ($keycount < 10) {

        $generatedkey = (bin2hex(openssl_random_pseudo_bytes(6)));

        echo $generatedkey . "<br>";

        mysqli_query($connect,"INSERT INTO mydatabase (keycode) VALUES ('$generatedkey')");

        sleep(0.5);

        $keycount++;

        }

echo "Done. Added " . $keycount . " new keys.";

mysqli_close($con);

虽然脚本本身会打印所有十个键,但只有第一个生成的键出现在数据库的“keycode”列中。如何让它提交所有十个,以及在此推荐每个提交的密钥(如果有的话)之间有什么延迟?

2 个答案:

答案 0 :(得分:3)

实际上你的最后一个密钥存储了......!,所以尝试存储在数组中,而不是通过数组存储到数据库的索引。

while ($keycount < 10) {

        $generatedkey[$keycount] = (bin2hex(openssl_random_pseudo_bytes(6)));

        echo $generatedkey[$keycount] . "<br>";

        mysqli_query($connect,"INSERT INTO mydatabase (keycode) 
        VALUES ('$generatedkey[$keycount]')");

        sleep(0.5);

        $keycount++;

        }

答案 1 :(得分:1)


对我来说,这很好用:

$keycount=0 ;

while ($keycount < 10) {

        $generatedkey = null;

        $generatedkey = (bin2hex(openssl_random_pseudo_bytes(6)));

        echo $generatedkey . "<br>";

        mysqli_query($connect,"INSERT INTO mydatabase (keycode) VALUES ('$generatedkey')") or die(mysqli_error($connect));

        //sleep(0.5);

        $keycount++;

        }

echo "Done. Added " . $keycount . " new keys.";

mysqli_close($connect);
  • 确保keycode字段为varchar。