dongzi4030 2015-09-26 21:52
浏览 25
已采纳

mysqli中每行的唯一ID

Here is the code that I've used

html:

<form action = 'insert.php' method='POST'>
<input type = "text" name = "name">
<input type = "submit" name = "submit">
</form>

php:

<?php
$servername='localhost';
$username='noob';
$password='password';
    $conn = mysqli_connect($servername, $username, $password);
    if (!$conn) 
        die("Connection failed: " . mysqli_connect_error());
$a=$_POST['name'];
mysqli_query("INSERT INTO table1 (name) VALUES ('$a')");
?>

Right now, the code above inserts a name into a table called table 1. My question now is, say I input many names into the table, but I want each name to have a unique 6 character/digit id. How would I change this code? For example, after 3 inserts, the table should look like this:

[table 1]
name               unique_id
NAME1              994323
NAME2              832344
NAME3              332123

Each value of unique_id must be unique. Is there any efficient way to do this?

  • 写回答

2条回答 默认 最新

  • dtrt2368 2015-09-26 22:11
    关注

    For the random code generation you can use RAND() as To obtain a random integer N in the range a <= N < b, just use the expression FLOOR(a + RAND() * (b – a)) as described in mysql docs

    Your query is vulnerable to SQL Injection, fix it with mysqli_real_escape_string !

    $name = mysqli_real_escape_string($_POST['name']);
    $result = mysqli_query("SELECT FLOOR(100000 + RAND() * 990000) AS random_num
        FROM table1 
        WHERE random_num NOT IN (SELECT table1.code FROM table1)
        LIMIT 1");
    $row = mysqli_fetch_row($result);
    $code = $row[0];
    
    mysqli_query("INSERT INTO table1 (name, code) VALUES ('$name', '$code')");
    

    This is the working query for random digit generation: http://sqlfiddle.com/#!9/2acd3/1

    EDIT:

    Personally I prefer PDO instead of mysqli functions, anyway,

    someone asked my why I suggest the PDO instead of MySQLi function. This is the way that I suggested, You can use whatever you want

    • Database Support

      • PDO has 12 different drivers
      • MySQLi has only Mysql driver
    • API

      • PDO: only OOP (avoiding bad practice)
      • MySQLi OOP or Procedural
    • Named parameters

      • PDO: yes
      • MySQLi no
    • Prepared statements (client side)

      • PDO: yes
      • MySQLi: no
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么