473,320 Members | 2,035 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How can I avoid adding a empty record into database.

Hi guys,

I am trying to build a user registration form using PHP and MYSQL but encountring a problem.

When I click on submit with empty fields it adds records to database also it doesn't matter what information I put it always add records to database when I click on submit. What can I do to make sure user will not be able to add records to database until he enters the right information?

I am posting my code for you guys to have a look and help me with the problem. Any help will be really appreciated.

connect.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $con = mysql_connect("localhost","username","password");
  3. if (!$con)
  4.   {
  5.   die('Could not connect: ' . mysql_error());
  6.  
  7.   }
  8. mysql_query("CREATE DATABASE tbl_login", $con);
  9. mysql_select_db("tbl_login", $con);
  10.  
  11. $sql = "CREATE TABLE login_tbl 
  12. (
  13. loginID int NOT NULL AUTO_INCREMENT, 
  14. PRIMARY KEY(loginID),
  15. Username varchar(35),
  16. Password varchar(35),
  17. Email varchar(35)
  18. )";
  19.  
  20. mysql_query($sql,$con);
  21. ?>
Form-validation.php

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $form_validation_alerts = Array(
  3.     '>'      => "%%Name%% should be more than %%num%%!",
  4.     '<'      => "%%Name%% should be less than %%num%%!",
  5.     '>='     => "%%Name%% should be more or equal to %%num%%!",
  6.     '<='     => "%%Name%% should be less or equal to %%num%%!",
  7.     'ch'     => "%%Name%% contains invalid characters!",
  8.     'chnum_' => "%%Name%% contains invalid characters!",
  9.     'date'   => "Please, enter a valid %%name%%!",
  10.     'email'  => "Please, enter a valid e-mail address!",
  11.     'empty'  => "Please, enter %%name%%!",
  12.     'len >'  => "%%Name%% should contain more than %%num%% characters!",
  13.     'len <'  => "%%Name%% should contain less than %%num%% characters!",
  14.     'len >=' => "%%Name%% should contain at least %%num%% characters!",
  15.     'len <=' => "%%Name%% should contain at most %%num%% characters!",
  16.     'len ==' => "%%Name%% should contain %%num%% characters!",
  17.     'num'    => "%%Name%% is not a valid number!");
  18.  
  19. function form_validation_alert($type, $name, $num)
  20. {
  21.   $name = preg_replace('/^\W*(\w*)\W*$/', "$1", $name);
  22.  
  23.   $msg = $GLOBALS['form_validation_alerts'][$type];
  24.   $msg = str_replace('%%Name%%', strtoupper(substr($name, 0, 1)) . strtolower(substr($name, 1, strlen($name)-1)), $msg);
  25.   $msg = str_replace('%%name%%', strtolower($name), $msg);
  26.   $msg = str_replace('%%num%%', $num, $msg);
  27.  
  28.   return $msg;
  29. }
  30.  
  31. // ***** isNaN *****************************************************************
  32.  
  33. function form_validation_isNaN($value)
  34. {
  35.   return (string)(integer)$value !== (string)$value;
  36. }
  37.  
  38. // ***** Validate **************************************************************
  39.  
  40. function form_validation_validate($data, $rules)
  41. {
  42.   $rules = preg_replace('/^(\s*)(\S.*)/', "$2", $rules);
  43.   $rules = preg_split('/\s*;\s*/', $rules);
  44.  
  45.   foreach ($rules as $i => $rule)
  46.   {
  47.     $rule = preg_split('/\s*:\s*/', $rule);
  48.  
  49.     if (count($rule) < 2) continue;
  50.  
  51.     $rule[0] = preg_split('/\s+/', $rule[0]);
  52.     $rule[1] = preg_split('/\s+/', $rule[1]);
  53.  
  54.     foreach ($rule[0] as $j => $name)
  55.     {
  56.       $name = str_replace("[]", "", $name);
  57.  
  58.       if (!in_array($rule[1][0], Array('cnt', 'radio', 'terms')))
  59.         if (!isset($data[$name])) return 'Invalid form!';
  60.  
  61.       if (!in_array($rule[1][0], Array('cnt')))
  62.         if ( isset($data[$name]) && is_array($data[$name])) return 'Invalid form!';
  63.  
  64.       switch ($rule[1][0])
  65.       {
  66.         // ***** Comparison *****
  67.  
  68.         case '>':
  69.           if (form_validation_isNaN($data[$name]))
  70.             return form_validation_alert('num', $name, 0);
  71.           if ($data[$name] <= $rule[1][1])
  72.             return form_validation_alert('>', $name, $rule[1][1]);
  73.           break;
  74.  
  75.         case '<':
  76.           if (form_validation_isNaN($data[$name]))
  77.             return form_validation_alert('num', $name, 0);
  78.           if ($data[$name] >= $rule[1][1])
  79.             return form_validation_alert('<', $name, $rule[1][1]);
  80.           break;
  81.  
  82.         case '>=':
  83.           if (form_validation_isNaN($data[$name]))
  84.             return form_validation_alert('num', $name, 0);
  85.           if ($data[$name] < $rule[1][1])
  86.             return form_validation_alert('>=', $name, $rule[1][1]);
  87.           break;
  88.  
  89.         case '<=':
  90.           if (form_validation_isNaN($data[$name]))
  91.             return form_validation_alert('num', $name, 0);
  92.           if ($data[$name] > $rule[1][1])
  93.             return form_validation_alert('<=', $name, $rule[1][1]);
  94.           break;
  95.  
  96.         // ***** Ch *****
  97.  
  98.         case 'ch':
  99.           if (!preg_match('/^([A-Za-z]+)$/', $data[$name]))
  100.             return form_validation_alert('ch', $name, 0);
  101.           break;
  102.  
  103.         // ***** Chnum_ *****
  104.  
  105.         case 'chnum_':
  106.           if (!preg_match('/^(\w+)$/', $data[$name]))
  107.             return form_validation_alert('chnum_', $name, 0);
  108.           break;
  109.  
  110.         // ***** Cnt *****
  111.  
  112.         case 'cnt':
  113.           $cnt = isset($data[$name]) ? (is_array($data[$name]) ? count($data[$name]) : 1) : 0;
  114.           if ($rule[1][1] == '>' && $cnt <= $rule[1][2])
  115.             return form_validation_alert('cnt >', $name, $rule[1][2]);
  116.           if ($rule[1][1] == '<' && $cnt >= $rule[1][2])
  117.             return form_validation_alert('cnt <', $name, $rule[1][2]);
  118.           if ($rule[1][1] == '>=' && $cnt < $rule[1][2])
  119.             return form_validation_alert('cnt >=', $name, $rule[1][2]);
  120.           if ($rule[1][1] == '<=' && $cnt > $rule[1][2])
  121.             return form_validation_alert('cnt <=', $name, $rule[1][2]);
  122.           break;
  123.  
  124.         // ***** Email *****
  125.  
  126.         case 'email':
  127.           if (!preg_match('/^(\w+\.)*(\w+)@(\w+\.)+(\w+)$/', $data[$name]))
  128.             return form_validation_alert('email', $name, 0);
  129.           break;
  130.  
  131.         // ***** Empty *****
  132.  
  133.         case 'empty':
  134.           if ($data[$name] == '')
  135.             return form_validation_alert('empty', $name, 0);
  136.           break;
  137.  
  138.         // ***** Len *****
  139.  
  140.         case 'len':
  141.           if ($rule[1][1] == '>' && strlen($data[$name]) <= $rule[1][2])
  142.             return form_validation_alert('len >', $name, $rule[1][2]);
  143.           if ($rule[1][1] == '<' && strlen($data[$name]) >= $rule[1][2])
  144.             return form_validation_alert('len <', $name, $rule[1][2]);
  145.           if ($rule[1][1] == '>=' && strlen($data[$name]) < $rule[1][2])
  146.             return form_validation_alert('len >=', $name, $rule[1][2]);
  147.           if ($rule[1][1] == '<=' && strlen($data[$name]) > $rule[1][2])
  148.             return form_validation_alert('len <=', $name, $rule[1][2]);
  149.           break;
  150.  
  151.         // ***** Num *****
  152.  
  153.         case 'num':
  154.           if (form_validation_isNaN($data[$name]))
  155.             return form_validation_alert('num', $name, 0);
  156.           break;
  157.       }
  158.     }
  159.  
  160.   }
  161.  
  162.   return true;
  163. }
  164.  
  165. ?>
Register.php

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <title>Register</title>
  4. <link rel="stylesheet" href="../css/content.css" type="text/css"/>
  5. <style>
  6. td
  7. {
  8.   padding: 2px 5px;
  9.   text-align: left;
  10. }
  11.  
  12. h4 { margin: 0px; }
  13.  
  14. input.editfield, select.editfield, textarea.editfield { width: 18em; }
  15.  
  16. </style>
  17. </head>
  18. <body>
  19. <center>
  20.  
  21. <form method="post" action="register.php">
  22. <input type="hidden" name="form_validation_rules"      value="" />
  23. <table class="tableborder" bgcolor="#f0f0f2">
  24. <p>&nbsp;</p>
  25.  
  26. <?php
  27.  
  28. if (isset($_POST['submit']))
  29. {
  30.   include 'form-validation.php';
  31.   include 'connect.php';
  32.  
  33.  
  34. $Username=$_POST['Username'];
  35. $Password=$_POST['Password'];
  36. $Email=$_POST['Email'];
  37.  
  38.  
  39. $sql="INSERT INTO login_tbl (Username, Password, Email)VALUES('$Username','$Password','$Email')";
  40.  
  41.   mysql_query($sql);
  42.   $result = form_validation_validate($_POST, "
  43.   Username Password : empty;
  44.   Username Password : len >= 3;
  45.   Username Password : chnum_;
  46.   Email: email;
  47.   ");
  48.  
  49.   ?>
  50.   <tr>
  51.   <td colspan="2">
  52.   <?php
  53.  
  54.   if ($result === true)
  55.   {
  56.     echo '<span style="color: green;">The form is successfully submitted!</span>';
  57.     $_POST = Array();
  58.   }
  59.   else echo '<span style="color: #A71930">' . $result . '</span>';
  60.  
  61.   ?>
  62.   </td>
  63.   </tr>
  64.   <?php
  65. }
  66.  
  67. function __post($name, $val = '')
  68. {
  69.   return isset($_POST[$name]) ? $_POST[$name] : $val;
  70. }
  71. ?>
  72.  
  73. <tr>
  74.   <td style="padding-bottom: 10px;" colspan="2" class="heading1"><b>User Registration</b></td>
  75. </tr>
  76.  
  77. <tr>
  78.   <td>Username:</td>
  79.   <td><input class="editfield" type="text" name="Username" value="<?php echo $_POST['Username']; ?>" /></td>
  80. </tr>
  81.  
  82. <tr>
  83.   <td>Password:</td>
  84.   <td><input class="editfield" type="password" name="Password" value="<?php echo $_POST['Password']; ?>" /></td>
  85. </tr>
  86.  
  87. <tr>
  88.   <td>E-mail:</td>
  89.   <td><input class="editfield" type="text" name="Email" value="<?php echo $_POST['Email']; ?>" /></td>
  90. </tr>
  91. <tr>
  92.   <td></td>
  93.   <td><input type="submit" name="submit" value="Submit" class="submit" /></td>
  94. </tr>
  95. </table>
  96. </form>
  97. </center>
  98. </body>
  99. </html>
Aug 26 '08 #1
9 6081
Guys I am still waiting for my answer. Pl. help me with my query. Thanks
Aug 26 '08 #2
Dormilich
8,658 Expert Mod 8TB
is there any reason why you create a new database each time the form is submitted (see connect.php)?

the very best regards
Aug 26 '08 #3
Ferris
101 100+
I think something wrong in Regist.php,look at line 39 to 47, you shouldn't insert information before being validated..

find line 39

[PHP]
$sql="INSERT INTO login_tbl (Username, Password, Email)VALUES('$Username','$Password','$Email')";
mysql_query($sql);
$result = form_validation_validate($_POST, "
Username Password : empty;
Username Password : len >= 3;
Username Password : chnum_;
Email: email;
");
[/PHP]

change into

[PHP]$result = form_validation_validate($_POST, "
Username Password : empty;
Username Password : len >= 3;
Username Password : chnum_;
Email: email;
");
if ( $result === true )
{
$sql="INSERT INTO login_tbl (Username, Password, Email)VALUES('$Username','$Password','$Email')";
mysql_query($sql);
}[/PHP]

Hope it helps.
Aug 26 '08 #4
Markus
6,050 Expert 4TB
Do not double post threads. I have reported the original thread for double posting.
Aug 26 '08 #5
Banfa
9,065 Expert Mod 8TB
Has has been pointed out please do not double post additionally

Guys I am still waiting for my answer. Pl. help me with my query. Thanks
you waited about 2 hours 40 minutes before following up. Please remember that this is an international forum run by volunteers. The best person to answer your question might have just gone to sleep at the time you posted. You should not be making this sort of re-query post until at least 24 hours has passed.

Please do read our posting guidelines as failure to follow them may ultimately lead to a ban on your account.

Banfa
Administrator
Aug 26 '08 #6
is there any reason why you create a new database each time the form is submitted (see connect.php)?

the very best regards
Hi Dormilich,

Thanks for your reply but sorry mate I am not sure is there any other way to do this as I am new to php. Can you pl. show me how can I avoid creating new database each time the form is submitted.

Thanks
Aug 27 '08 #7
Do not double post threads. I have reported the original thread for double posting.
Sorry markusn00b I am new this community so I didn't realise thats you can't post threads twice. What about my query? You havn't answered my question?? Please help me with the problem.
Aug 27 '08 #8
Has has been pointed out please do not double post additionally

you waited about 2 hours 40 minutes before following up. Please remember that this is an international forum run by volunteers. The best person to answer your question might have just gone to sleep at the time you posted. You should not be making this sort of re-query post until at least 24 hours has passed.

Please do read our posting guidelines as failure to follow them may ultimately lead to a ban on your account.

Banfa
Administrator
Sorry mate.....I won't do it again.
Aug 27 '08 #9
I think something wrong in Regist.php,look at line 39 to 47, you shouldn't insert information before being validated..

find line 39

[PHP]
$sql="INSERT INTO login_tbl (Username, Password, Email)VALUES('$Username','$Password','$Email')";
mysql_query($sql);
$result = form_validation_validate($_POST, "
Username Password : empty;
Username Password : len >= 3;
Username Password : chnum_;
Email: email;
");
[/PHP]

change into

[PHP]$result = form_validation_validate($_POST, "
Username Password : empty;
Username Password : len >= 3;
Username Password : chnum_;
Email: email;
");
if ( $result === true )
{
$sql="INSERT INTO login_tbl (Username, Password, Email)VALUES('$Username','$Password','$Email')";
mysql_query($sql);
}[/PHP]

Hope it helps.
Hi Ferris,

Yes it does work. Thanks heaps for help.

Dhiru
Aug 27 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: Steve Jorgensen | last post by:
Since reading values from calculated controls in Access 2000 and 2002 from code has proven unrliable at best, and since I like to avoid running separate queries to calculate sums of subform records...
1
by: Dalan | last post by:
I can't seem to find a workaround of Query Syntax Error. Actually, the query performs just fine, except when the last record on a related subform is deleted, then it generates a Runtime Error 3075...
8
by: Mark | last post by:
When my form goes to a new record, I have a procedure that copies the last record added to the form's underlying table into the form. The intent is that a series of new records may have the same...
11
by: Johnny M | last post by:
I have several databases where I have one form to add a new record and one form to edit an existing record. I use unbound forms and class modules most of the time. What I would like to do is...
2
by: Jim | last post by:
In my Win App, I have a datagrid that's bound to a dataset. When the form loads, the datagrid fills. How can I add an empty row to the end of the datagrid during a button click (similar to...
3
by: Jim Heavey | last post by:
Trying to figure out the technique which should be used to add rows to a datagrid. I am thinking that I would want an "Add" button on the footer, but I am not quite sure how to do that. Is that...
3
by: Tull Clancey | last post by:
Hi, hope someone can help with the following, I'm a bit stuck! I have a database table (Access) with an AutoNumber field. When I add data to the table I want to use the AutoNumber field, format...
2
by: Rico | last post by:
Hello, I'm formatting a report based on an existing controlled document. The document that I'm duplicating has a number of lines that the user fills our manually, but the database version of...
2
by: basestring | last post by:
Hi I am busy now for many hours without luck I have a database and when I use PHP to add date to it, it works only one time when i want to add the next data, It doesn't work. but i don't get any...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.