-1

I want to generate a 5 digit random number which is not in table and apply to registration. I have below code.. Its is generating a random number,but it showing

" Notice: Undefined variable: id in F:\wamp\www\hello\hello.php on line 8"

please do help me

<?php


error_reporting(E_ALL ^ E_DEPRECATED);
// function to generate random ID number
function createID() {
 for ($i = 1; $i <= 5; $i++) {
  $id .= rand(0,9);
 }
 return $id;
}

// MySQL connect info
mysql_connect("localhost", "root", "");
mysql_select_db("college");
$query = mysql_query("SELECT id FROM college");

// puts all known ID numbers into $ids array
while ($result = mysql_fetch_array($query)) {
 $ids[] = $result["id"];
}

// generates random ID number
$id = createID();

// while the new ID number is found in the $ids array, generate a new $id number
while (in_array($id,$ids)) {
 $id = createID();
}

// output ID number
echo $id;

?>
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Durai Sankar
  • 47
  • 1
  • 11
  • 1
    If you're writing new code, **_please_ don't use the `mysql_*` functions**. They are old and broken, were deprecated in PHP 5.5 (which is so old it no longer even receives security updates), and completely removed in PHP 7. Use [`PDO`](https://secure.php.net/manual/en/book.pdo.php) or [`mysqli_*`](https://secure.php.net/manual/en/book.mysqli.php) with _prepared statements_ and _parameter binding_ instead. See http://stackoverflow.com/q/12859942/354577 for details. – ChrisGPT was on strike Dec 24 '16 at 13:14
  • 3
    you have to initial the $id to avoid the warning – LF00 Dec 24 '16 at 13:14
  • it showing more errors now! – Durai Sankar Dec 24 '16 at 13:16
  • how to intialize $id ? i m new to php – Durai Sankar Dec 24 '16 at 13:17
  • @Durai Sankar I've explained how to do this in my answer below. – EDD Dec 24 '16 at 13:19

3 Answers3

2

The problem is that you need to initialise id before you append to it.

For example this function should do the trick:

function createID() {
    $id = '';
    for ($i = 1; $i <= 5; $i++) {
         $id .= rand(0,9);
    }
    return $id;
}
EDD
  • 2,070
  • 1
  • 10
  • 23
2

You're appending to $id before defining it. Just initialize it with an empty string, and you should be OK:

function createID() {
    $id = '';
    for ($i = 1; $i <= 5; $i++) {
        $id .= rand(0,9);
    }
    return $id;
}

But, frankly, I think you're reinventing the wheel here. You could just randomize a number between 0 and 99999 and zero-fill any missing digits:

function createID() {
    return std_pad(random(0, 99999), 5, '0', STD_PAD_LEFT);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You need to define variable before using it.

<?php
function createID() {
    $id = ''; // define $id variable
    for ($i = 1; $i <= 5; $i++) {
        $id .= rand(0,9);
    }
    return $id;
}
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Đào Minh Hạt
  • 2,742
  • 16
  • 20