duanshan188866 2019-06-30 08:43
浏览 74
已采纳

如果我在自身内部重新运行一个函数,PDO就无法运行

I'm trying to create a system, where my website generates an unique code (current date + 5 random characters) and that code is transferred to a table in my database.

Before function generateNumber() can insert the unique code into the database, it has to check if the code already exist in the database.

If the code doesn't exist, my function works flawlessly. But the problem is when the code can already be found on the database, my website just doesn't do anything (it should just re-run the function).

function generateNumber()
{
    global $conn;

    $rand = strtoupper(substr(uniqid(sha1(time())),0,5));
    $result = date("Ydm") . $rand;

    $SQL = $conn->query("SELECT code FROM test WHERE code='$result'");
    $c = $SQL->fetch(PDO::FETCH_ASSOC);

    if ($c['code'] > 0) { // test if $result is already in the database
        generateNumber();
    } else {
        $sql2 = "INSERT INTO test (code) VALUES (?)";
        $stmt2 = $conn->prepare($sql2);
        $stmt2->execute([$result]);
        return $result;
    }
}

try {
    $conn = new PDO("sqlite:db"/*, $username, $password*/);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo generateNumber();
}

catch(PDOException $e) {
    echo "Error:" . $e->getMessage();
}

$conn = null;
?>

There are no error messages in the console, but I suspect the problem is this part of the code:

if ($c['code'] > 0) { // test if $result is already in the database
    generateNumber();
} 

Any idea how I can write this function in a better way?

  • 写回答

1条回答 默认 最新

  • duanchuiwen6694 2019-06-30 08:49
    关注

    Solution :

    if ($c['code'] > 0) { // test if $result is already in the database
    // if the code exists in db the function return nothing 
    // because you are missing a return :
        return generateNumber();
    
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测