簡體   English   中英

如何生成隨機ID

[英]How to generate random id's

我想知道如何為照片ID為任意數字生成隨機數,為用戶ID為任意數字生成隨機ID,例如:

num =照片ID idr =用戶ID

yourphoto.php?num=60&idr=3

現在我想做的是生成不會告訴用戶照片的ID號或用戶ID是隨機的東西。

像那樣:

yourphoto.php?num=654654654648&idr=34546545621

選中uniqid ,它將滿足您的需求。

Kinda偽代碼(與注釋有關)

  //Insert into DB $new_photo = array( array('id' => 1, 'name' => 'newphoto', 'unique' => uniqid()), array('id' => 2, 'name' => 'newphoto2', 'unique' => uniqid()) ); // select everything from db $photos = $new_photo; //display photos foreach($photos as $photo){ // display Link with $photo['unique'], <a href="link.php?num=$photo['unique']" var_dump($photo); } //GET Num // select where unique = $_GET['num'] 

既然我猜您不太了解,我將成為一個好人,向您展示它的工作原理。 確保記住這只是一個不利於生產的示例。

創建2個PHP文件test.php和test2.php

test.php

運行一次,它將創建一個名為photos_temp的新表,並將插入2張照片。

 // DB information $host = "localhost"; $username = "root"; $password = "password"; $dbname = "database"; // Create our photos_temp table $test_query = "CREATE TABLE IF NOT EXISTS `photos_temp` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `unique` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;"; //Connect to DB $conn = new mysqli($host, $username, $password, $dbname); // Create Table $table = $conn->prepare($test_query); $table->execute(); // Data to insert into the database ( you can insert trough a form ) $new_photos = array( array('name' => 'newphoto', 'unique' => uniqid()), array('name' => 'newphoto2', 'unique' => uniqid()) ); // Insert Query template $addquery = "INSERT INTO `photos_temp` (`name`, `unique`) VALUES (?, ?)"; // foreach our data ( we will insert the 2 photos ) foreach($new_photos as $photo){ if($query = $conn->prepare($addquery)){ $query->bind_param('ss', $photo['name'], $photo['unique']); $query->execute(); } } echo 'finish inserting'; 

test2.php

這將顯示照片並鏈接到您的獨特照片。

 // DB information $host = "localhost"; $username = "root"; $password = "password"; $dbname = "database"; $conn = new mysqli($host, $username, $password, $dbname); $stmt = $conn->stmt_init(); $stmt->prepare('Select * from photos_temp'); $stmt->execute(); $result = $stmt->get_result(); while ($data = $result->fetch_assoc()) { echo '<a href="?num='.$data['unique'].'">'.$data['name'].'</a><br/>'; } if(isset($_GET['num'])){ $num = $_GET['num']; $stmt->prepare("SELECT * FROM `photos_temp` WHERE `unique` = ?"); $stmt->bind_param("s", $num); $stmt->execute(); $result = $stmt->get_result(); $photo = $result->fetch_assoc(); echo '<pre>'; print_r($photo); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM