HTML form to mySQL database

They have: 16 posts

Joined: May 2009

I am trying to make a form in html which submits a name and e-mail address to a mySQL database and asks a user if they wish to subscribe or unsubscribe to a mailing list.

The form can be viewed here: www.davidframpton.co.uk/contact.html.

This is the php script i have to post the data:

<?php
$con
= mysql_connect("(davidfra_mail).ns1.siteground215.com","DB_NAME","PASSWORD"); //Replace with your actual MySQL DB Username and Password
if (!$con)
{
die(
'Could not connect: ' . mysql_error());
}
mysql_select_db("davidfra_mail", $con);
$name=mysql_real_escape_string($_POST['name']);
$email=mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO form_data (name,email) VALUES ('$name','$email')";
if (!
mysql_query($sql,$con)) {
die(
'Error: ' . mysql_error());
}
echo
"The form data was successfully added to your database.";
mysql_close($con);
?>

When I click submit nothing happens at all, it just gives me a blank look.

Can anyone spot the problem? The form validator works and i have removed the DB name and password from the php.

Thanks

P.S. Also any advice on how to delete an entry when the user selects unsubscribe ?!? I am extremely new to this and it took me ages just to do what you see above.

Dave

They have: 16 posts

Joined: May 2009

Any tutorials would be appreciated also Smiling

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Any error log? Usually the first place to look. Is anything actually been written to the DB?

Does it output the "The form data was successfully..."?
If it doesn't output that, and doesn't output any mysql errors from the "die" you have (so as you say a blank screen), then I guess it's a straight forward PHP error which halts the entire script.

Again, check the error log. I had a look and couldn't see any syntax issues, but I'm "guessing" that's what it is. Post the error log results here if you wish, it will likely give you a line number but it is sometimes not the line it gives you.

I have never used "IF" to check if a mysql query was ok. It may well be ok, but I have always used affected_rows:

<?php
$query_num_rows
= 0;
mysql_query("INSERT INTO form_data (name, email)
VALUES ('
$name', '$email')");
$query_num_rows = mysql_affected_rows();
if (
$query_num_rows !=1){
was error
}else{
was fine
}
?>

Your way may well be fine, and don't change it unless someone states that affected_rows is better.
I have only ever really seen affected_rows in any forum advice - possibly it's faster, anyone know?

They have: 16 posts

Joined: May 2009

Hey again Greg, my you are a helpful chap. Thanks for the reply.

Ok firstly nothing is being written to the database.

Secondly maybe my poor attempt at humor in the original post was mis-interpreted :

"When I click submit nothing happens at all, it just gives me a blank look"

What I meant was no new screen opens, when i click submit nothing happens it stays on the same page and does nothing! There is no output what so ever!!

And i know this sounds a real noob question but where do I find the 'error log'? I was thinking maybe it may have something to do with this part :

$con = mysql_connect("(davidfra_mail).ns1.siteground215.com","DB_NAME","PASSWORD"); //Replace with your actual MySQL DB Username and Password

mainly the .ns1.sitegrounds215.com bit. But I am not sure what is supposed to go here.

Thanks again Greg

Dave

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Error logs can be in a few places depending on your server setup.

- In the directory where the file you ran has the error
- In your control panel (Plesk, Cpanel etc) there will be "logs" link and "error logs" link.
- Somewhere else in your directory structure (this is less likely and is 99% sure to be in one or both of the above two possibilities)

I was going to check your form page, but it gives me a 404!
www.davidframpton.co.uk/contact.html

If it's doing nothing when you click submit, then my next guess would be the form "ACTION" is not set to do anything.

<form method="post" action="youfilenamehere.php">

They have: 16 posts

Joined: May 2009

I have checked my error log and it shows nothing.

I'm not sure why you get a 404. But here is a working link

http://www.davidframpton.co.uk/Contact.html

I have checked my form against others and I am quite sure it is correct. However i thought that earlier with another problem and spend 3 hours looking for a missing bracket.

Sorry to take up your time, but please know i appreciate the help.

Dave

greg's picture

He has: 1,581 posts

Joined: Nov 2005

The first link you gave in your first post has a lower case "C", the page actually has an upper case C.

You're right, the form doesn't do anything when I submit it, although even if it did, there is an error in your "sendingdata.php" file:

Could not connect: Unknown MySQL server host '(davidfra_mail).ns1.siteground215.com' (0)

The host you state in your mysql connection is incorrect!

EDIT:
I managed to get the form to submit by removing the Javascript you have in the form:
This from your <form> code onsubmit="return formValidator();"
And this from your submit button onclick="javascript:return formValidator();"

When I removed that JS the form submitted.
I don't know Javascript so cannot help you with that unfortunately, although another note, the Javascript checks that stops me entering an invalid email and ensures the form data is as it should be can be bypassed easily.
You should really use PHP to check the user input as that cannot be bypassed if done correctly.

They have: 16 posts

Joined: May 2009

Ah ok I thought it might be that, as i said before, but I am not sure what to put in there ?!?!? However I will scan the siteground website looking for a clue.

How did you view the error?

Thanks very much Greg I owe you like a beer or something.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

I viewed the error by finding the page the form submits to from the form code "sendingdata.php". And just accessed that directly.

But if you see my last post I added something else regarding the form not submitting^^

They have: 16 posts

Joined: May 2009

Hey again, Ok I have followed your advice and I have found some PHP for form validation. However I still can't figure out what I am supposed to put in here :

Could not connect: Unknown MySQL server host '(davidfra_mail).ns1.siteground215.com' (0)

I have tried localhost, which my PHP admin on cpanel says it is. Is there a special way I am supposed to write it in there?

They have: 16 posts

Joined: May 2009

Fixed it, heres the working code incase anyone else has the same problem:

<?php
$host
= "localhost";
$user = "davidfra_Dave";
$db_name= "davidfra_mail";
$pass= "PASSWORD";

$con = mysql_connect($host, $user, $pass);

if (!
$con)
{
die(
'Could not connect: ' . mysql_error());
}
mysql_select_db("davidfra_mail", $con); //Replace with your MySQL DB Name
$name=mysql_real_escape_string($_POST['name']); //This value has to be the same as in the HTML form file
$email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file
$sql="INSERT INTO Mailing_list (name,email) VALUES ('$name','$email')"; /*form_data is the name of the MySQL table where the form data will be saved.
name and email are the respective table fields*/
if (!mysql_query($sql,$con)) {
die(
'Error: ' . mysql_error());
}
echo
"The form data was successfully added to your database.";
mysql_close($con);
?>

Thanks for your help greg and i hope someone else gets help from this.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Try something like these (try them in order as below):

mysql_connect('localhost', 'mysql_user', 'mysql_password');

Or
mysql_connect('localhost:3306', 'mysql_user', 'mysql_password');

Or
mysql_connect('', 'mysql_user', 'mysql_password');

If you go into phpmyadmin, right at the very top it will tell you what DB Server is:
I.E.

Server: localhost:3306 - Database: davidfra_mail

EDIT:
we posted at the same time Laughing out loud
Glad you got it sorted. If you need any other help, just ask!
I've also took the liberty to edit your post and change the password to "PASSWORD". It's not likely anyone will do anything with it, but you shouldn't make public the password Wink

They have: 16 posts

Joined: May 2009

ha ha i did the same, i realised after i posted it. But thanks again Greg. Now I have a new mission....to find why none of the data that is input is showing up in the table after it is submitted ?!?!?!

PHP is the next thing on my list to learn, it's seriously driving me nuts Sad

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Dave0585 wrote:
to find why none of the data that is input is showing up in the table after it is submitted ?!?!?!
That one is easy!

Your code is this:

<input id="name" type="text"/>
<input id="email" type="text"/>

You need a "name" so when the form gets to the next page PHP knows how to recognise each input. Such as this:

<input id="name" name="name" type="text"/>
<input id="email" name="email" type="text"/>

Then on your PHP page, the $_POST['name'] and $_POST['email'] will now get the NAMES from the form.

Another bit of advice. You can, and most certainly should, use PHP to check for user input.
For your particular circumstance, you should check a few things. For example, if the user enters no name or email. sure the Javascript on the form page will stop that, but there are very easy ways around that, so you should use PHP to check them.

EG:

<?php
$name
= $_POST['name'];//sets "$name" var to be the posted name data
$email = $_POST['email'];//sets "$email" var to be the posted email data

if (empty($name)){
do
something because the name is empty
}
if (empty(
$email)){
do
something because the email is empty
}
?>

Dave0585 wrote:
PHP is the next thing on my list to learn, it's seriously driving me nuts :(
Well, as with anything, it comes with practice and this form is the ideal thing to pick up things from. Although, I really suggest while you are making this form, especially as you are still learning, that it's not publicly accessible.

There are many ways an unscrupulous visitor can access, edit, delete and insert into your mysql database using an insecure script.

Checking what they have input is good for three things at the same time.
It stops them entering data into your database you don't want them to be, and it helps them to ensure what they have entered stands a good chance of being accurate.
The third is making them enter precise things before they can continue "helps" to stop the automated scripts. That is bots that go around the internet trying to use forms automatically to spam and get data.
It wont fool the intelligent ones, but it will stop the majority as they wont be programmed to cope with your site saying "username cannot be more than xx chars" etc.
(this isn't fool proof or a great spam prevention, but every little helps.)

The mysql_real_escape_string "should" make it safe regardless of what they enter, and you should ALWAYS use it before inserting or selecting data from a DB where you use a variable (even if it is one you set yourself within a script) EG have a "where something = '$something'".

But that doesn't help you when someone is typing nonsense into your form trying to hack or even just being a nuisance.
So checks like my above if (empty) are required in my opinion.

Other things you can do:
strlen() gets the number of characters in any given string or variable.
So if in your form I enter "greg" as my name, and you only allow 3 characters, the following will stop me doing this:

<?php
if (strlen($name) > 3){
echo
"your name can only be 3 characters or less"
}
?>

This is a bit useless, you would more likely have something like:
if (strlen($name) < 1) so if the name is less than one char it is empty.
if (strlen($fname) > 10) the name has more than 10 chars you don't allow it.

These are really needed as in your database you need to assign a set length. So for name I'm presuming you use "VARCHAR" and you need to assign a length you allow for that.
If the VARCHAR for name in your DB is say 10 chars, and I enter my name with 12 chars, without the above check it will be inserted into the DB, but the last two letters of my name wont be stored. So you possibly get inaccurate and potentially useless data

So it's not only about security, it's about maintaining continuity between data going into the DB and what users enter.

Other things I often do are make sure the user has only entered chars they need. Such as the "name" only needs to be letters, arguably numbers so for the sake of it allow it, but nothing else.
So:

<?php
if (ereg('[^A-Za-z09]', $name)){
name was not a-Z or 0-9
?>

that may look daunting, but you don't even have to understand it at the moment, just understand what it's doing and implement it into your scripts.

That will catch their input if they entered anything other than numbers or upper or lower case letters.

What to do with it if what they entered goes wrong?
I tend to run through all the checking of their posted data, then send them back to the form with a message IF ANYTHING was wrong.

For this I use $_SESSION, but that may be a little ahead of your current abilities and you would have to learn about sessions.

For the time being, I advise you stop working on code that is publicly available, and just work on the one page outputting errors and NOT running a mysql insert if anything they entered was bad.

You could do something like the following:

<?php
$errors
= "no";
$name = $_POST['name'];//sets "$name" var to be the posted name data
$email = $_POST['email'];//sets "$email" var to be the posted email data

if (empty($name)){
$errors = "yes";
}
if (empty(
$email)){
$errors = "yes";
}
if (
strlen($name) > 10){
$errors = "yes";
}
if (
strlen($email) > 64){
$errors = "yes";
}
if (
$errors == "no"){
<
DB INSERT>
}else{
echo
"you had errors in your form";
}
?>

So it runs through all the checks, and if any of the checks return true, $error is set to "yes" and therefore something went wrong.
As we only do the DB insert if $error is equal to "no", it will only insert into the DB IF everything was ok!

Of course instead of just echoing "you have errors", you could get clever and set vars for each error.
EG:

<?php
if (empty($name)){
$errors = "yes";
$nameerror = "empty";
}
if (empty(
$email)){
$errors = "yes";
$emailerror = "empty";
}

//if are errors dont insert into DB and show what went wrong
if ($errors == "yes"){
if (
$nameerror == "empty"){
echo
"you did not type in a name";
}
if (
$emailerror == "empty"){
echo
"you did not type in an email";
}
//end if are errors
}else{
//else $errors does NOT = "yes" so we insert
<DB INSERT>
}
?>

that's basic, but it gives you the structure of how you should be working.

Check all user inputs, if is all satisfactory to what you want/allow, insert into db, else tell them what they entered was bad in some way.
Again, playing with all of this code and doing the form that you are working on is practice and you will soon know how to do it all.

But you should be practising away from public access.

They have: 16 posts

Joined: May 2009

Once again you have the answer, i agree i shouldn't be doing it in reach of the public. But I needed to work out how it works and it was the only way i could think to link the form with my DB. However there is no data on the server fot the bots to take just my test data (made up addresses etc.

Ok, so now i have the validation on there and it works (the validation part, anyhow), however here is the script i have below (I downloaded it) and i want to adjust it to return to the form if it is incorrectly filled out and proceed with sending the data to the DB if it is correct!

<?php
require_once "formvalidator.php";
$validator = new FormValidator();
$validator->addValidation("name","req","Please fill in Name");
$validator->addValidation("email","email","The input for Email should be a valid email value");
$validator->addValidation("email","req","Please fill in Email");
if(!
$validator->ValidateForm())
{
    echo
"<B>Validation Errors:</B>";

   
$error_hash = $validator->GetErrors();
    foreach(
$error_hash as $inpname => $inp_err)
    {
        echo
"<p>$inpname : $inp_err</p>\n";
    }      
}

$host = "localhost";
$user = "davidfra_Dave";
$db_name= "davidfra_mail";
$pass= "PASSWORD";

$con = mysql_connect($host, $user, $pass);

if (!
$con)
{
die(
'Could not connect: ' . mysql_error());
}
mysql_select_db("davidfra_mail", $con); //Replace with your MySQL DB Name
$name=mysql_real_escape_string($_POST['name']); //This value has to be the same as in the HTML form file
$email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file
$sql="INSERT INTO Mailing_list (name,email) VALUES ('$name','$email')"; /*form_data is the name of the MySQL table where the form data will be saved.
name and email are the respective table fields*/
if (!mysql_query($sql,$con)) {
die(
'Error: ' . mysql_error());
}
echo
"The form data was successfully added to your database.";
mysql_close($con);
?>

Can you help in anyway ?

Thanks

greg's picture

He has: 1,581 posts

Joined: Nov 2005

The exit(header('Location = contact.html')); sends them to whatever page you put in there. But it will return a PHP error if you have already sent headers on the page. That is outputted ANYTHING, such as echoing something.
So only use it if you haven't echoed anything out.

So you could redirect the user upon a certain clause

<?php
if (something = whatever){
exit(
header('Location = contact.html'));
}
?>

Perhaps INSTEAD of echo "<B>Validation Errors:</B>"; use the redirect to send them to the contact form.

Another note: You shouldn't use "or die" when the code is public. It's ok for development, but you don't want visitors to see your errors such as database xy was incorrect, or db_table xy could not be accessed.
Apart from being a "potential" security risk, it's ugly to visitors.

Dave0585 wrote:
i agree i shouldn't be doing it in reach of the public.
....there is no data on the server fot the bots to take just my test data (made up addresses etc.
It wasn't bots that concerned me, humans could hack into your DB.
Of course, if there's nothing of use there nothing is lost, and the chances are highly unlikely. I just don't like the idea.

It's easy enough to make a testing area. Make a new folder and use your control panel to password protect it.
Then anything you do in there is 99% secure from bots and humans.

Or there is the option of LAMP on your home PC. You can install linux, apache, php and mysql and get phpmyadmin with it.
Is great for developing and learning as there is not FTPing files all the time. Just save them and refresh the browser each time you try something.

They have: 16 posts

Joined: May 2009

Hey Greg, sorry I went to bed after one million hours of PHP fun. I agree totally that I should no being trying all of this online. But I think it is now protected. I just put an exit at the end of the validation code to stop it running the POST script stuff unless it is valid input.

Thanks for all of your help greg, it is greatly appreciated indeed.

Here is the code I have now for anyone who might have the same problem:

<?php
require_once "formvalidator.php";
$validator = new FormValidator();
$validator->addValidation("Name","req","Please fill in Name");
$validator->addValidation("Email","email","The input for Email should be a valid email value");
$validator->addValidation("email","req","Please fill in Email");
if(!
$validator->ValidateForm())
{
    echo
"<B>Validation Errors:</B>";

   
$error_hash = $validator->GetErrors();
    foreach(
$error_hash as $inpname => $inp_err)
    {
        echo
"<p>$inpname : $inp_err</p>\n";
    }      
exit;}
?>

They have: 5 posts

Joined: May 2009

Hello Dave0585, I saw your forum post a few days ago when I was looking for a script to send form data to a database. The script I used was similar to the one you're using and it just wouldn't work...anyway, I found something else that adds form data to a txt/csv file - easy to access and (and I'm new to all this so I could be wrong) it isn't likely to suffer sql exploits (because it isn't an sql database) although the created text file will be readable by browsers who know where to look for it (I hope someone here could offer advice to protect it).

Here's the code I'm using:

<?php

// Give your form's <input> tags name attributes equal to
// the variables set here e.g name="fieldone" or name="fieldtwo"
// Change fieldone, fieldtwo...to suit you.
// If you change these, remember to also
// change their corresponding parts below
// eg change every occurrence of $fieldone and fieldone
// to whatever you change them.
// Likewise, these can be increased or decreased
// just remove or add below as needed.

if(isset($_POST['Submit'])){
   
$fieldone = $_POST['fieldone'];
   
$fieldtwo = $_POST['fieldtwo'];
   
$fieldthree = $_POST['fieldthree'];
   
$fieldfour = $_POST['threefour'];
   
$fieldfive = $_POST['fieldfive'];
   
$fieldsix = $_POST['fieldsix'];
   
$fieldseven = $_POST['fieldseven'];
  
$err = '';
  
//This bit checks the fields have been filled.
//Remove for non-essential fields (from "if.." to "}"

  
if(trim($fieldone)==''){
     
$err .= '-Please enter whatever goes into fieldone<br />';
   }
   if(empty(
$fieldtwo)){
     
$err .= '-Please enter whatever goes into fieldtwo<br />';
   }
   if(empty(
$fieldthree)){
     
$err .= '-Please enter whatever goes into fieldthree<br />';
   }
   if(empty(
$fieldfour)){
     
$err .= '-Please enter whatever goes into fieldfour<br />';
   }
   if(empty(
$fieldfive)){
     
$err .= '-Please enter whatever goes into fieldfive<br />';
   }
   if(
strlen($fieldsix)==0){
     
$err .= '-Please enter whatever goes into fieldsix<br>';
   }
   if(
strlen($fieldseven)==0){
     
$err .= '-Please enter whatever goes into fieldseven<br>';
   }
  
   if(
$err!=''){
      echo
$err;
   }

// This bit writes data to "datafile.csv". You can call it whatever
// you want; even change it to a .txt if preferred.
// Whatever you put between ',' (in this case a coma) will also be
// written to the file. I use it to format data ready for use.

  
else{
     
$filename = 'linksubmissions.csv';
     
$somecontent = $fieldone . ',' . $fieldtwo . ',' . $fieldthree . ',' . $fieldfour . ',' . $fieldfive . ',' . $fieldsix . ',' . $fieldseven . "\n";
     
     
$checkfile = 'datafile.csv'; //Changethstothe name of the file you want written

      // Let's make sure the main file exists and is writable.
     
if (is_writable($filename)) {
     
        
// In our example we're opening $filename in append mode.
         // The file pointer is at the bottom of the file hence
         // that's where $somecontent will go when we fwrite() it.
        
if (!$handle = fopen($filename, 'a')) {
             echo
"Cannot open file ($filename)";
             exit;
         }
     
        
// Write $somecontent to our opened file.
        
if (fwrite($handle, $somecontent) === FALSE) {
            echo
"Cannot write to file ($filename)";
            exit;
         }
        

         echo
"You detailshve been successfully recorded, thank you.   Details sent were,<br /><br />$somecontent.";
        
        
fclose($handle);
     
      } else {
         echo
"Either the file $filename or $checkfile is not writable";
      }
   }
}
?>

I've annotated the script, I got the main part of it from another website (forgotten which). If you need to write separate field data to different files then I can help you do that.

Hope this has proved helpful to you 'cause it's taken me two days to re-find this forum to post this script for you Smiling

Now I need to add to it to ensure people fill out the form fields with correct data e.g their email in my email field, and URL in my URL field. I'm going to try the code written by Greg.

He has: 53 posts

Joined: Jun 2010

I'll give you a basic example to you, firstly you try that, here i create a simple lo-gin form as well as registration form that help you for understanding the Database concept completely

index_dir.php

<?php
if(isset($_POST['posted']))
                {
                  
$name=$_POST['dir_username'];
                  
$pass=$_POST['dir_password'];
                  
$connect=mysql_connect('localhost','root','');
               
$db=mysql_select_db('dir_db',$connect);
               
$query=mysql_query('SELECT * FROM dir_login',$connect);
                while(
$row=mysql_fetch_array($query))
                {
                   
$column1=$row['username'];
                   
$column2=$row['password'];
                    if(
$column1 == $name && $column2 == $pass)
                    {
                       
header('location:registration_dir.php');
                    }
                    else
                    {
                        echo(
'Sorry Username and password is mismatch');
                        exit();
                    }
                }
                }
            
?>

USERNAME

PASSWORD

">

*************************************************
registration_dir.php
**********************************************************

<?php
if(isset($_POST['posted'])=='true')
{
$connect=mysql_connect('localhost','root','');
$db=mysql_select_db('dir_db',$connect);

$name=$_POST['dir_name'];
$title=$_POST['dir_title'];
$company=$_POST['dir_company'];
$email=$_POST['dir_email'];
$phone=$_POST['dir_phone'];
$address=$_POST['dir_address'];
$website=$_POST['dir_website'];
$notes=$_POST['dir_notes'];
$search_conent=$_POST['dir_search_content'];
           
// Now, We Perform Saving Operation.
               
if(isset($_POST['dir_save']) == 'Save')
                  {
                   
$query=mysql_query("INSERT INTO dir_registration(name,title,company,email,phone,address,website,notes)                           VALUES('$name','$title','$company','$email','$phone','$address','$website','$notes')",$connect);
                  }
                 
//Now We Perform Cancel operation.
              
if(isset($_POST['dir_cancel']) == 'Cancel')
                {
                    exit();
                }
// Now We Perform Reset operation.
               
if(isset($_POST['dir_reset']) == 'Reset')
                {
                   
$name       = '' ;
                   
$title      = '' ;
                   
$company    = '' ;
                   
$email      = '' ;
                   
$phone      = '' ;
                   
$address    = '' ;
                   
$website    = '' ;
                   
$notes      = '' ;
                    echo
'Sai Ram, Sucessfully record Reset';
                }
// Now We Perform Search Operation.       
              
               
if(isset($_POST['dir_search'])=='Search')
                {
                   
$query=mysql_query("SELECT * FROM dir_registration WHERE name LIKE '%$search_conent%'",$connect);
                    while(
$row = mysql_fetch_array($query))
                    {
                       
$column1=$row['name'];
                       
$column2=$row['title'];
                       
$column3=$row['company'];
                       
$column4=$row['email'];
                       
$column5=$row['phone'];
                       
$column6=$row['address'];
                       
$column7=$row['website'];
                       
$column8=$row['notes'];
                    }
                   
                }
//Now We Perform Deletion Operation
               
               
if(isset($_POST['dir_delete']) == 'Delete')
                {
                    echo
"Hiii";
                   
$query = mysql_query("DELETE FROM dir_registration WHERE name= '$name' ",$connect);
}
}
?>

 
 
 
 

Name :

Title :   
Company :

Email

   

Phone

   

Address

<?php
echo $column6;
?>

   

Website

   

Birthday
 

Notes

<?php
echo $column8;
?>

They have: 2 posts

Joined: Nov 2010

Hi
When i tried to create a database it is throwing a error like "Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'Bala'@'localhost' (using password: YES) in C:\xampp\htdocs\Database.php on line 7
Could not connect: Access denied for user 'Bala'@'localhost' (using password: YES)"

Can anyone help me?

- Bala

They have: 2 posts

Joined: Nov 2010

Hi
When i tried to create a database it is throwing a error like "Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'Bala'@'localhost' (using password: YES) in C:\xampp\htdocs\Database.php on line 7
Could not connect: Access denied for user 'Bala'@'localhost' (using password: YES)"

I am using the code

<?php
$host
= "localhost";
$user = "Bala";
$db_name= "Bala_db";
$pass= "PASSWORD";
   
$con = mysql_connect($host, $user, $pass);
   if (!
$con)
{
die(
'Could not connect: ' . mysql_error());
}
mysql_select_db("Bala_db", $con); //Replace with your MySQL DB Name
$name=mysql_real_escape_string($_POST['name']); //This value has to be the same as in the HTML form file
$email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file
$sql="INSERT INTO Mailing_list (name,email) VALUES ('$name','$email')"; /*form_data is the name of the MySQL table where the form data will be saved.
name and email are the respective table fields*/
if (!mysql_query($sql,$con)) {
die(
'Error: ' . mysql_error());
}
echo
"The form data was successfully added to your database.";
mysql_close($con);
?>

Can anyone help me?

- Bala

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

That error message usually happens when the SQL password is incorrect.

They have: 1 posts

Joined: Jan 2012

Hi
I cant make The php code ....
i got site with a form like this
(checkblox)action
(checkblox)science
(checkblox)drama
(checkblox)thriler.....
I have 4 tables in database and in action table is action movies ,in thriler table is thriler movies etc
if u can help me with php code to show each time the rigth table ....
i' ve make the form with Post ....thank you and sorry for my english

They have: 13 posts

Joined: Jan 2012

These are really needed as in your database you need to assign a set length. So for name I'm presuming you use "VARCHAR" and you need to assign a length you allow for that.
If the VARCHAR for name in your DB is say 10 chars, and I enter my name with 12 chars, without the above check it will be inserted into the DB, but the last two letters of my name wont be stored.

They have: 1 posts

Joined: Mar 2015

Hello
I have already displayed my sql table in my HTML form. I want to update the same sql table with the same html form after every submit. How do I go about this.The attached is a screenshot of what I want to update

AttachmentSize
t.png 134.09 KB

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.