user3117337
user3117337

Reputation: 223

Deny insert when column value is empty

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?

Upvotes: 1

Views: 132

Answers (4)

King-of-IT
King-of-IT

Reputation: 578

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.
}

Upvotes: 1

Pinu
Pinu

Reputation: 412

$random = rand(10000,99999);

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

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

Upvotes: 0

Pavel Štěrba
Pavel Štěrba

Reputation: 2912

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);

Upvotes: 3

Jenz
Jenz

Reputation: 8369

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

Upvotes: -1

Related Questions