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 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM