【问题标题】:PHP (Grocery CRUD) | Mysql Generate an unique and random number between two numbersPHP(杂货CRUD)| Mysql在两个数字之间生成一个唯一且随机的数字
【发布时间】:2017-09-30 09:59:21
【问题描述】:

我在 Mysql 中用这个列创建了一个表

  • secretNumber(主键和 AI)
  • 姓名
  • 日期
  • 等等……

我的想法是当我要向这个表中添加一个新项目时,自动生成一个“秘密号码”但必须有3个要求:

  • 唯一编号
  • 我每次添加新项目时的随机数
  • 0-1000000之间

尝试使用像 uniqid(); 这样的函数和 mt_rand();但没有成功。

【问题讨论】:

  • 你的 PHP 版本是多少?
  • 关于这个话题已经回答了很多问题。快速搜索 php 唯一 ID 会返回数百个结果。每个都可以轻松适应您的要求。
  • PHP 版本:7.0.22 是的,我试过了,但它不是字母数字,我真正需要它的唯一数字。
  • 您至少应该尝试调整针对您的问题给出的答案。另外,您没有提供任何详细信息,而且您的问题非常笼统。无论如何,我在下面给您一个答案。

标签: php mysql codeigniter grocery-crud


【解决方案1】:

您可以为 0-1000000 之间创建 tmptable 当您插入表时,使用 from tmptable,之后您必须从该表中删除该行。 或转发查询,但这很慢,因为每次创建临时表。如果你创建一次 temptable,那么它可能是一个快速的过程。

CREATE TEMPORARY TABLE IF NOT EXISTS listtable(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, tmp INT NOT NULL); SET @s = CONCAT('INSERT INTO listtable (tmp) VALUES ',REPEAT('(1),',1000000),'(1)'); 从@s准备stmt1; 执行 stmt1; SELECT id FROM listtable WHERE id NOT IN(select id from your table) order by rand() limit 1; DROP TABLE 列表表;

【讨论】:

    【解决方案2】:

    首先是逻辑:为了实现这一点,您必须在杂货店控制器的方法中添加一个 callback_before_insert() 函数。在此回调函数中,您将创建所需的随机数,然后将其添加到 $post_array 变量中,然后将 $post_array 返回到控制器的方法(在杂货店的官方页面上已经有示例)。 所以,在你的控制器的某个地方添加这个:

    function _create_unique_secret_number()
    {
        /*Create a random secret_Number between 0 and 1000000
         * and assign it to a variable
         */
        $random_unique_secret_number = mt_rand( 0, 1000000 );
    
        /* Now make sure that your random secret number is not already "in use"
         * which means that the generated id is already stored in your table.
         */
        $query = $this->db->where( 'secretNumber', $random_unique_secret_number )
                          ->get_where( 'your_table_name_goes_here' );
    
        if( $query->num_rows() > 0 )
        {
            $query->free_result();
    
            // Try again in case the randomly generated number above is in use
            return $this->create_unique_secret_number();
        }
    
        $post_array['secretNumber'] = $random_unique_int;
        return $post_array;
    
    }
    
    /* And finally call the function inside your controllers' method.
     * I mean inside the method that is handling your table.
     */
    $crud->callback_before_insert( array ($this, '_create_unique_secret_number')  );
    

    然后您可以通过访问enter code here $post_array['secretNumber'] 值来访问杂货杂货控制器中生成的数字..

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 2011-05-16
      • 1970-01-01
      • 2013-05-20
      • 2014-12-19
      • 2012-06-05
      • 2014-10-02
      相关资源
      最近更新 更多