1

I have my php code that will hold and insert date to mysql:

from an input textbox

$id2 = $_POST['id'];

Random Number Generator How can I generate it always on 5 digit?

$random = rand();

Insert code:

$sql3="Insert into warranty(serial_no,a_id)
values ('$random','$id2')";
$result3=mysql_query($sql3);

How can I deny insert when $id2 doesn't have a value?

user3117337
  • 213
  • 1
  • 5
  • 17
  • 1
    You are vulnerable to SQL injection and are [using a deprecated library](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – George Feb 14 '14 at 11:33

4 Answers4

3

Just use empty() function to determine, if given variable has value or not (manual page). Like this:

if (!empty($id2))
{
   $sql3="Insert into warranty(serial_no,a_id) values ('$random','$id2')";
   $result3=mysql_query($sql3);
}

But passing $_POST value directly to SQL query is huge* security issue (SQL Injection to be clear), os use at least mysql_real_escape_string():

$sql3="Insert into warranty(serial_no,a_id) values ('$random','" . mysql_real_escape_string($id2) . "')";

For more info about this, read How can I prevent SQL injection in PHP?.

EDIT: At first, I miss your second question, so moved from comments - to generate 5 digits random number, use simple:

$fiveDigitsRand = rand(10000, 99999);
Community
  • 1
  • 1
Pavel Štěrba
  • 2,822
  • 2
  • 28
  • 50
1

put below code and remove existing code.You don't have need of $id2 variable if you are getting value using $_POST method. You can do it directly by following code.

$random = rand();

if(isset($_POST['id']))
{   
$sql3="Insert into warranty(serial_no,a_id)
values ('$random','".$_POST['id']."')";
$result3=mysql_query($sql3);
}
else
{
echo "No ID Found"; //you can do any action here.
}
King-of-IT
  • 578
  • 4
  • 18
0

$random = rand(10000,99999);

if(!empty(trim($id2)))

{
  $sql3="Insert into warranty(serial_no,a_id) values ('$random','$id2')";
 $result3=mysql_query($sql3);
}
Pinu
  • 382
  • 3
  • 4
-1
if(isset($id2))
{
$sql3="Insert into warranty(serial_no,a_id)
values ('$random','$id2')";
$result3=mysql_query($sql3);
}
Jenz
  • 8,280
  • 7
  • 44
  • 77