gpt4 book ai didi

php - 在 php/mysql 中生成随机字符串

转载 作者:行者123 更新时间:2023-11-29 01:56:44 25 4
gpt4 key购买 nike

当我在我的 mysql 中插入数据时,我需要生成一个随机字符串。我确实读过有关 uuid 或 cast(rand) 的内容,但我找不到任何看起来可以使用的内容。

我的数据来自应用。

我创建了一个名为 code 的新行并将其设置为 unik。

我希望你能帮助我:)

我如何告诉我的插入为我的行代码生成一个随机字符串?

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {

$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

mysql_set_charset("utf8");

// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato) VALUES('$name', '$nummer', '$description', '$dato')");

好的,这就是我到目前为止所得到的

if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {

$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];
// $code = $_POST['code'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}


// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$randomString')");

但是我的代码行中没有任何内容?

    return $randomString;

$random_str = generate_random_string(10);

}


// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$random_str')");

最佳答案

您可以使用 PHP 的函数 rand 生成一个随机数:

// code = rand($min , $max); for example
code = rand(100000, 999999); // will generate a number between 100000 and 999999
// then add the column to your insert if it belongs to the same table or
// make another query to insert the code if it belongs to a different table

请注意,您可以使用当前时间和 md5 函数来生成更强大的唯一代码。

此外,如果您想将此逻辑应用到您的数据库中,请尝试创建一个将在每次插入后运行的触发器。

祝你好运。

关于php - 在 php/mysql 中生成随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26869391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com