Jump to content

i am trying to build a form to post to a mysql DB


baxt01

Recommended Posts

Hi I am trying to build a form that when submitted the results are posted to a database,

I an less than a novice coder I am trying to learn I think I understand the basic syntax but for some reason my form data is not reaching my DB I do not know if the problem is in my table structure or my coding,

 

before I go on to show my code I know there are security issues with my codes you would be lucky number 100th person to state this I know It looks lazy and bad but the codes I am using and showing here are NOT in a working public page these are my private test pages!!!

 

this is my index.php page

<html><head><title>test page</title><script type="text/javascript">function validateForm(){var a=document.forms["reg"]["fname"].value;var b=document.forms["reg"]["lname"].value;var c=document.forms["reg"]["mname"].value;var d=document.forms["reg"]["address"].value;var e=document.forms["reg"]["contact"].value;var f=document.forms["reg"]["pic"].value;var g=document.forms["reg"]["pic"].value;var h=document.forms["reg"]["pic"].value;if ((a==null || a=="") && (b==null || b=="") && (c==null || c=="") && (d==null || d=="") && (e==null || e=="") && (f==null || f==""))  {  alert("All Field must be filled out");  return false;  }if (a==null || a=="")  {  alert("First name must be filled out");  return false;  }if (b==null || b=="")  {  alert("Last name must be filled out");  return false;  }if (c==null || c=="")  {  alert("Gender name must be filled out");  return false;  }if (d==null || d=="")  {  alert("address must be filled out");  return false;  }if (e==null || e=="")  {  alert("contact must be filled out");  return false;  }if (f==null || f=="")  {  alert("picture must be filled out");  return false;  }if (g==null || g=="")  {  alert("username must be filled out");  return false;  }if (h==null || h=="")  {  alert("password must be filled out");  return false;  }}</script></head><body><form name="reg" action="code_exec.php" onsubmit="return validateForm()" method="post"><table width="274" border="0" align="center" cellpadding="2" cellspacing="0">  <tr>    <td colspan="2">		<div align="center">		  <?php 		$remarks=$_GET['remarks'];		if ($remarks==null and $remarks=="")		{		echo 'Register Here';		}		if ($remarks=='success')		{		echo 'Registration Success';		}		?>		    </div></td>  </tr>  <tr>    <td width="95"><div align="right">First Name:</div></td>    <td width="171"><input type="text" name="fname" /></td>  </tr>  <tr>    <td><div align="right">Last Name:</div></td>    <td><input type="text" name="lname" /></td>  </tr>  <tr>    <td><div align="right">Gender:</div></td>    <td><input type="text" name="mname" /></td>  </tr>  <tr>    <td><div align="right">Address:</div></td>    <td><input type="text" name="address" /></td>  </tr>  <tr>    <td><div align="right">Contact No.:</div></td>    <td><input type="text" name="contact" /></td>  </tr>  <tr>    <td><div align="right">Picture:</div></td>    <td><input type="text" name="pic" /></td>  </tr> <tr>    <td><div align="right">Username:</div></td>    <td><input type="text" name="username" /></td>  </tr> <tr>    <td><div align="right">Password:</div></td>    <td><input type="text" name="password" /></td>  </tr>  <tr>    <td><div align="right"></div></td>    <td><input name="submit" type="submit" value="Submit" /></td>  </tr></table></form></body></html>

this is my code_exec.php page

<?phpsession_start();include('connection.php');$fname=$_POST['fname'];$lname=$_POST['lname'];$mname=$_POST['mname'];$address=$_POST['address'];$contact=$_POST['contact'];$pic=$_POST['pic'];$username=$_POST['username'];$password=$_POST['password'];mysql_query("INSERT INTO member(fname, lname, gender, address, contact, picture, username, password)VALUES('$fname', '$lname', '$mname', '$address', '$contact', '$pic', '$username', '$password')");header("location: index.php?remarks=success");mysql_close($con);?>

this is my conection.php page

<?php$mysql_hostname = "localhost";$mysql_user = "***************";$mysql_password = "*********";$mysql_database = "********_simple_login";$prefix = "";$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");mysql_select_db($mysql_database, $bd) or die("Could not select database");?>

the structure of my database is:

# Name Type collation Null Default

 

1 mem_id varchar(30) no none

2 username varchar(30) latin1_swedish_ci no none

3 password varchar(30) latin1_swedish_ci no none

4 fname varchar(30) latin1_swedish_ci no none

5 lname varchar(30) latin1_swedish_ci no none

6 address varchar(100) latin1_swedish_ci no none

7 contact varchar(30) latin1_swedish_ci no none

8 picture varchar(100) latin1_swedish_ci no none

9 gender varchar(10) latin1_swedish_ci no none

 

trying to get this code to simply insert the form from index.php into this table is frustrating me so much so please someone help me figure out why the data is not reaching my table as I am not getting no error message returned when I submit it I get my success message returned

Link to comment
Share on other sites

before I go on to show my code I know there are security issues with my codes you would be lucky number 100th person to state this I know It looks lazy and bad but the codes I am using and showing here are NOT in a working public page these are my private test pages!!!

Does that mean you would rather spend your time learning the bad way to do it, instead of just learning the right way to start with? It seems like you're making double the work for yourself. Why spend any valuable time at all to learn the bad way?First, add this to the top of your PHP code, before any other PHP code:
ini_set('display_errors', 1);error_reporting(E_ALL);
Second, if you insist on using the deprecated mysql extension, then at least add error checking:
mysql_query("INSERT INTO member(fname, lname, gender, address, contact, picture, username, password)VALUES('$fname', '$lname', '$mname', '$address', '$contact', '$pic', '$username', '$password')") or exit(mysql_error());
The mysql extension does not automatically show errors from MySQL, you need to check for them. Other more modern database extensions for PHP are better about error checking, but if you want to use the mysql extension then you have to do it yourself.

mysql_close($con);

What is $con?
Link to comment
Share on other sites

I am going to try to answer // justify myself here you mistake my frustrations for laziness this is not laziness not in the slightest,

I want to learn the right way to do this I really do I just really struggling to get past this issue that no matter how many online tutorials I sit endlessly reading and typing out the same resolve is waiting for me at the end

as for this "deprecated mysql extension " wow I learned only today that is the case when I was reading on http://php.net

and yes I hit my head hard,

as for $con this is a variable defined by me its reference to the database connection

 

ok that's odd I just read back in my codes and I could not find the variable myself :(

so this is not really working out so well right now I need some major help to do what should be real simple

I only want to post my form into my table in MySQL I know I need to learn to do this the correct way and the safe way at the same time and i have been through so many online tutorials I can afford collage to learn I can barely afford my domain and server right now

 

 

Does that mean you would rather spend your time learning the bad way to do it, instead of just learning the right way to start with? It seems like you're making double the work for yourself. Why spend any valuable time at all to learn the bad way?First, add this to the top of your PHP code, before any other PHP code:

ini_set('display_errors', 1);error_reporting(E_ALL);
Second, if you insist on using the deprecated mysql extension, then at least add error checking:
mysql_query("INSERT INTO member(fname, lname, gender, address, contact, picture, username, password)VALUES('$fname', '$lname', '$mname', '$address', '$contact', '$pic', '$username', '$password')") or exit(mysql_error());
The mysql extension does not automatically show errors from MySQL, you need to check for them. Other more modern database extensions for PHP are better about error checking, but if you want to use the mysql extension then you have to do it yourself.What is $con?

 

Link to comment
Share on other sites

I have implemented your wonderful help into my codes and not really shocking it did return me an error value

but I am not sure what it means as this part of the coding that it refers to came from someone else online and its java scripting error

The returned error is: Notice: Undefined index: remarks in /home/mnvbcou1/public_html/index2.php on line 141

the line this refers to is $remarks=$_GET['remarks'];

Link to comment
Share on other sites

as for $con this is a variable defined by me its reference to the database connection

No it's not, check your connection file. You don't define a variable called $con. Your connection is called $bd.The undefined index error means that you are trying to access an array index that doesn't exist. $_GET is an array. You're trying to access $_GET['remarks'], so the message means that $_GET does not contain an index called remarks. You can use isset to check if something exists before trying to access it, e.g.:
$remarks = '';if (isset($_GET['remarks'])) {  $remarks = $_GET['remarks'];}
This line is also incorrect:
if ($remarks==null and $remarks=="")
$remarks will never be both values, it won't be both null and also an empty string. It can be one or the other, but not both at the same time. With the code above you can remove the check for null and just check for an empty string.This is what your code looks like using PDO with prepared statements instead of mysql. The part at the top can go in an include file if you want it to. With PDO you create the PDO object first to connect to the database. Then, with prepared statements you call PDO::prepare and give it the SQL, but instead of adding in the data supplied by the user you just put question mark placeholders (you can also use named placeholders instead of question marks). The prepare method returns a PDOStatement object. Then you can call the execute method on the PDOStatement object and send it the actual data you want to use in the query. The database server will take care of substituting that data into the query in a way that won't cause any problems. With your original code, for example, if someone enters an apostrophe into any field then it breaks your SQL query. If they knew how your code worked then they could type in a bunch of SQL code into your form fields to have the query insert multiple values. That's what SQL injection is. On an insert form SQL injection is pretty benign, but if you were doing the same thing when logging in a user then someone could exploit your code to log in as any user without needing to know a password, and that's a problem. Using prepared statements solves that problem.Lastly, all of the PDO code is surrounded in try/catch blocks to catch any exceptions that get thrown because of a database error. The setAttribute line right after creating the PDO object tells PDO to use exceptions as the way to handle database errors, there are other options you could use there also. I've also added some debugging output so that you can see what the code is doing, but adding that output means the redirect header won't work so I commented that line out. If you uncomment the header line you'll just see an error that the header couldn't be sent because of the other output on the page, so with the debug output I commented out the header.
<?phpini_set('display_errors', 1);error_reporting(E_ALL); $db_name = 'testdb';$dsn = 'mysql:dbname=' . $db_name . ';host=localhost';$user = 'dbuser';$password = 'dbpass';try {  $pdo = new PDO($dsn, $user, $password);  // set PDO to throw exceptions if an error happens  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch (PDOException $e) {  exit('Database Connection failed: ' . $e->getMessage());}echo 'Connected to database<br>';echo 'Values received from $_POST: <textarea style="width: 90%; height: 200px;">' . print_r($_POST, true) . '</textarea><br>';$fname=$_POST['fname'];$lname=$_POST['lname'];$mname=$_POST['mname'];$address=$_POST['address'];$contact=$_POST['contact'];$pic=$_POST['pic'];$username=$_POST['username'];$password=$_POST['password'];try {    $stmt = $pdo->prepare('INSERT INTO member(fname, lname, gender, address, contact, picture, username, password) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');    $stmt->execute(array(    $fname,    $lname,    $mname,    $address,    $contact,    $pic,    $username,    $password  ));  echo 'Inserted record into database.<br>';} catch (PDOException $e) {  exit('Database error: ' . $e->getMessage());}  echo 'Send redirect header.<br>';//header("location: index.php?remarks=success");
Start with that code and see where it takes you. Maybe you'll get other errors, and you can also check the output in the text area to see what is in $_POST. There are some more resources about PDO here, and there are plenty of articles about using PDO that you can find online. If you're looking for database tutorials then I would stick with tutorials that use PDO.http://php.net/manual/en/intro.pdo.phphttp://php.net/manual/en/pdo.connections.phphttp://php.net/manual/en/pdo.prepared-statements.phphttp://php.net/manual/en/pdo.error-handling.phphttp://php.net/manual/en/class.pdo.phphttp://php.net/manual/en/pdo.construct.phphttp://php.net/manual/en/pdo.prepare.phphttp://php.net/manual/en/pdostatement.execute.php
  • Like 1
Link to comment
Share on other sites

More Human Than Human WOW WOW oh boy WOW if i was not such a dumb ###### i would be leathal in this game of coding your PDO coding is a must learn for me but in the mean time my original code works

wooooooooooooooohooooooooooooooooooooooooo

finally

HAHAHA that was so exciting

so now i have that working i can explain it was not my bad coding stopping it working it was actually something more stupid when i created my DB i simply forgot to grant myself / user acc the correct access rights over it *DOH* so now it is 202AM here and my wife & children are already asleep so i better join them but tomorrow with a fresh brain i am gong to set about looking at your PDO coding as this to me sounds much more affective

thank you so much More Human Than Human your the absolute best

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...