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?

1

4 Answers 4

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

how can I generate random numbers always on 5 digits sir?
Simply with rand(10000, 99999);
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. } 

Comments

0

$random = rand(10000,99999);

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

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

Comments

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

1 Comment

iseet() tells him only if given variable is set, not if has some value. Empty is better here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.