PHP生成多个字符串并插入数据库

时间:2018-02-14 16:41:09

标签: php mysql pdo

所以我现在用PHP制作这个小小的网上商店。

目前正在构建一个允许生成优惠券代码的功能。 这本身就完美无缺。虽然我不确定如何生成多个代码并将其插入数据库。

试图教育自己。 所以当然,伸出援助之手会很棒!

我的代码在这里:

<?php

    $page = "Gift Cards";
    require_once 'header.php'; 

    if(isset($_POST['createnewCard']))
    {
        $plan = $_POST['plan'];

        if(empty($plan))
        {
            $notify = error('Plan input was empty!');
        }

        if(empty($notify))
        {
             /// Generate Gift Code
            $code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10);

             /// Input to database
            $SQLinsert = $odb -> prepare("INSERT INTO `giftcards` VALUES(NULL, :code, :planID, 0, 0, UNIX_TIMESTAMP())");
            $SQLinsert -> execute(array(':code' => $code, ':planID' => $plan)); 

            $notify = success('New Giftcard has been generated. New code is: '.$code.'');
        }   
    }
?>

3 个答案:

答案 0 :(得分:0)

你可以使用for循环:

for ($x=0; $x<5; $x++) {
     /// Generate Gift Code
     $code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10);

     /// Input to database
     $SQLinsert = $odb -> prepare("INSERT INTO `giftcards` VALUES(NULL, :code, :planID, 0, 0, UNIX_TIMESTAMP())");
     $SQLinsert -> execute(array(':code' => $code, ':planID' => $plan)); 

     $notify = success('New Giftcard has been generated. New code is: '.$code.'');
}

循环执行5次($x<5)并且每次都在for循环中运行代码。这将每次生成一个新的礼品代码并将其添加到数据库中。

希望这有帮助

答案 1 :(得分:0)

起初我认为你的范围存在问题。请参阅变量$ notify。

if(empty($notify))
{
    /// Generate Gift Code
    $code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10);

    ...
}   

我同意亚伦,我会以同样的方式做到这一点。

答案 2 :(得分:0)

这是一个抽象出来的例子。您将需要为您的情况清理它,但它应该生成5个代码。

<?php

    $page = "Gift Cards";
    require_once 'header.php'; 

    function generateCode() {
        if(isset($_POST['createnewCard']))
        {
            $plan = $_POST['plan'];

            if(empty($plan))
            {
                $notify = error('Plan input was empty!');
            }

            if(empty($notify))
            {
                 /// Generate Gift Code
                $code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10);

                 /// Input to database
                $SQLinsert = $odb -> prepare("INSERT INTO `giftcards` VALUES(NULL, :code, :planID, 0, 0, UNIX_TIMESTAMP())");
                $SQLinsert -> execute(array(':code' => $code, ':planID' => $plan)); 

                $notify = success('New Giftcard has been generated. New code is: '.$code.'');
            }   
        }
    }


    $numOfCodes = 5;

    for($i = 0; $i < $numOfCodes; ++$i) {
        generateCode();
    }
?>