Jump to content
xisto Community
Sign in to follow this  
rapco

How Can I Make A Php Form To Save Info In Mysql

Recommended Posts

I need to write the php script to creat a form where visitor are able to wirte their name, telephone, adress... etc...And that info has to be saved in a simple table on a MySQL databes that i also have to create (i know how to creat it)Anyone?

Share this post


Link to post
Share on other sites

Here's a short tip. You'll need to setup 3 things:

1. The MySQL DB that your form data is getting written to. For our example lets just take two fields in a table, Name and Email in table Guests in a database named guestdb.

2. A html page with the form

3. A php file to process the form and write out the data to the MySQL db.

 

Step 1 - Create the form

File: index.html

<html>

...

<body>

<form action="./processform.php" method="post">

Name:<input type="text" name="name">

Email:<input type="text" name="email">

<input type="submit" value ="Submit">

</form>

....

</html>


This code just sets up a form with 2 fields to enter your name and email. The form post is redirected to your php code when you press submit.

 

 

Step 2 - Create the form processor php file

File: processform.php

<?php

 

    // Create the query string - be careful about all those single(') and double(")

    // quotes

    $query = "INSERT INTO guestdb.Guests ( Name, Email ) VALUES ( "

    $query .= " '$_POST['Name']' , '$_POST ['Email']'  )";

 

    mysql_query ($query, $conn_id);

 

    echo "Your details have been saved.\n";

 

?>


This shouldn't be hard to understand - it uses the environmental variable $_POST to fetch the form fields and constructs your query accordingly. It's a very basic piece of code...Just make sure both files are in the same directory.

 

That's it. Try and let me know if it works. All the best :P

 

-----------------------------------------------------------

This topic deals with both scripting language and database - but is more script oriented. So I'm moving it to the Programming > Scripting section - and leaving a link in here too.

m^e

Share this post


Link to post
Share on other sites

Ok, i have created this html page:

 

<h1>COMUNIDAD</h1><br /><br />

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

Nombre:<input type="text" name="nombre" />

<br />Documento de IdentificaciĂłn:<input type="text" name="documento" />

<br />Email:<input type="text" name="email" />

<br />Telefono:<input type="text" name="telefono" /><br />

<input type="submit" value="Enviar" />

</form>


With this php proccesor:

 

<?php

 

 

    $query = "INSERT INTO cursoweb.alumno ( documento, nombre, email, telefono ) VALUES ( "

    $query .= " '$_POST['documento']' , '$_POST ['nombre']' , '$_POST ['email']' , '$_POST ['telefono']'  )";

 

    mysql_query ($query, $conn_id);

 

    echo "Sus datos han sido guardados.\n";

 

?>


and this database and table:

 

Posted Image

And i'm getting this error:

 

Parse error: parse error, unexpected T_VARIABLE in W:\www\v2\activmysql.php on line 5

WHAT0S WRONG????

 

Thanks!!!!

 

PS: great post microscopic^earthling, thanks a lot!

Share this post


Link to post
Share on other sites

I believe your problem is you are using the single quotes (') within single quotes to enter the values into the database. This is why it is parsing and error, this is not allowed.

So your code would become:

$query .= " '$_POST[documento]' , '$_POST [nombre]' , '$_POST [email]' , '$_POST [telefono]'  )";

you can see that i have removed the single quotes from within all of the values you want to enter into the database.

instead of $_POST['fieldname'] you would have $_POST[fieldname].

I think that is the answer to your problem. If it is not then i am sure someone will have the answer for you. if you have any more errors feel free to post them here.

good luck

overture.

Share this post


Link to post
Share on other sites

Ok, thanks everybopdy for helping me aout!!!!

Finally i had to use another code.. the following:

note: in the line
$connection = mysql_connect ("localhost", "rapco_sena", "virtual");
localhost =server
rapco_sena = database username
virtual= password



ACTIVIDADMYSQL.PHP

<?php if ($submit == "click"){  // The submit button was clicked!  // Get the input for fullname and email then store it in the database.  $connection = mysql_connect ("localhost", "rapco_sena", "virtual");  if ($connection == false){    echo mysql_errno().": ".mysql_error()."<BR>";    exit;  }     $query = "insert into alumno values ('$documento', '$nombre', '$email', '$telefono')";  $result = mysql_db_query ("rapco_cursoweb", $query);  if ($result){    echo "Success!";  }  else{    echo mysql_errno().": ".mysql_error()."<BR>";  }   mysql_close ();} else{  echo "    <html><body>     <DISABLED-FORM method=\"post\" action=\"activmysql.php\">     Escriba su documento de identidad:    <DISABLED-INPUT type=\"text\" name=\"documento\"></DISABLED-INPUT><br>    Escriba su Nombres y apellidos completos:    <DISABLED-INPUT type=\"text\" name=\"nombre\"></DISABLED-INPUT><br>    Escriba su direccion de e-mail:    <DISABLED-INPUT type=\"text\" name=\"email\"></DISABLED-INPUT><br>    Escriba su telefono con indicativo de ciudad en Colombia:    <DISABLED-INPUT type=\"text\" name=\"telefono\"></DISABLED-INPUT><br>     <DISABLED-INPUT type=\"submit\" name=\"submit\" value=\"click\"></DISABLED-INPUT>            </DISABLED-FORM>     </body></html>  ";} ?>


MOSTRAR.PHP


<?php $connection = mysql_connect ("localhost", "rapco_sena", "virtual");if ($connection == false){  echo mysql_errno().": ".mysql_error()."<BR>";  exit;}   $query = "select * from alumno";$result = mysql_db_query ("rapco_cursoweb", $query); if ($result){  echo "<table border=1>";  echo "<tr><td><b>Documento de ID</b></td><td><b>Nombre completo</b></td><td> <b>Email</b></td><td><b>Telefono</b></td></tr>";   $numOfRows = mysql_num_rows ($result);  for ($i = 0; $i < $numOfRows; $i++){    $doc = mysql_result ($result, $i, "documento");    $name = mysql_result ($result, $i, "nombre");    $emaila = mysql_result ($result, $i, "email");    $tel = mysql_result ($result, $i, "telefono");      echo "<tr><td>$doc</td><td>$name</td><td>$emaila</td><td>$tel</td></tr>";  }   echo "</table>";}else{  echo mysql_errno().": ".mysql_error()."<BR>";} mysql_close (); ?>

This script works perfectly!!!!!!!!!!!!

Share this post


Link to post
Share on other sites

tnx micro for unlockingall i wanted to say is that there is a good reason php introduced the functions addslashes and stripslashes (more info: http://php.net/addslashes/)let's watch this simple query:$query='instert into users(name) values("'.$_POST["name"].'")';and let's say some evil user ( :P) inserted something like d'diddy, or d"any or d\ego, or any other strange signthe query would become: instert into users(name) values("d"any")which would give you errors.replace $_POST["name"]with addslashes($_POST["name"].this will add slashes when necessary, so all your queries work fine.when getting data out of the database, do stripslashes($data), and you get your nice username.it's a matter of security actually. if you don't do it, one could inject sql and obtain info they shouldnt be able to get.that would be all :P

 

Share this post


Link to post
Share on other sites

below you learn how to create a table,form,and display page!
first create a database and table:

CREATE DATABASE form;
USE DATABASE form;

Now create a table like the following on the MySQL command line ( if you use phpMyAdmin,

you can copy and past it.)

CREATE TABLE `form` (`id` MEDIUMINT( 10 ) DEFAULT '0' NOT NULL AUTO_INCREMENT ,`name` VARCHAR( 80 ) ,`lastname` VARCHAR( 80 ) ,`email` VARCHAR( 80 ) ,`url` VARCHAR( 80 ) ,`submitted` DATE,PRIMARY KEY ( `id` ) );

Ok i will now create a form for you to enter information , the info we want to submit is name ,

last name , url and email . Here is the form .

name it "form.php".

<form action ="send.php" method = "post"><table><tr><td>Name:</td><td><input type ="text" name = "name" size="20"></td></tr><tr><td>Last name:</td><td><input type ="text" name = "lastname" size="20"></td></tr><tr><td>Email:</td><td><input type ="text" name = "email" size="20"></td></tr><tr><td>Url:</td><td><input type ="text" name = "url" size="20"></td></tr><tr><td><input type="submit"></td><td><input type = "reset"></td></tr></table></form>

Now you should create a script page and name "send.php".

<?php//connect using your host , username and password info
$connection = mysql_connect("localhost" , "username" , "password");
//select the form database
$db = mysql_select_db("form" , $connection);
//create or query inserting the appropriate values into the mysql
//table
$query = "INSERT INTO form(name , lastname ,email ,url, submitted )
VALUES('$name','$lastname','$email','$url', now())";
//execute query and store result as variable
$result = mysql_query($query);
//displays a message , you could redirect back to the form
//instead , if you wished
echo ("Thanks, your data entered.");
?>


and finally your display page, name it "display.php".


<?mysql_pconnect("localhost","username","password");
mysql_select_db("form");
  if(!isset($start)) $start = 0;
    $query = "SELECT * FROM form LIMIT " . $start . ", 10";
  //do database connection
  $result = mysql_query($query); //you should do error checking
$result = mysql_query($query);
//start creating our table
echo ("<table cellspacing='5' bgcolor='#006699'  cellpadding='5' style='border-collapse:

collapse' width='20'>");
//loop through rows in the database
while ($rows = mysql_fetch_row($result))
{
echo ("<table cellspacing='5'  cellpadding='5' style='border-collapse: collapse' 

width='50%'>");
//in the next row we display the description which is $rows[2]
echo ("<tr><td colspan ='2'  bgcolor='#fbfbfb'><font color='#006699' size='2'

face='Tahoma'>Name: $rows[1]</font></td></tr>");
echo ("<tr><td colspan ='2'  bgcolor='#fbfbfb'><font color='#006699' size='2'

face='Tahoma'>Last Name: $rows[2]</font></td></tr>");
echo ("<tr><td colspan ='2'  bgcolor='#fbfbfb'><font color='#006699' size='2'

face='Tahoma'>Email: $rows[3]</font></td></tr>");
echo ("<tr><td colspan ='2'  bgcolor='#fbfbfb'><font color='#006699' size='2'

face='Tahoma'>Url: $rows[4]</font></td></tr>");
echo "</table>";
}
//finish or table
echo "</table>";
  //this code was wrong, I did not have the second query.
  // need another query to get the total amount of rows in our table
  $query = "SELECT count(*) as count FROM form";
  $result = mysql_query($query);
  $row = mysql_fetch_array($result);
  $numrows = $row['count'];
  if($start > 0)

  echo "<div align='center'><< <a href=\"" . $PHP_SELF . "?start=" . ($start
  - 10) .
  "\">Previous Page</a>";
  echo "    ";
    echo "    ";
  if($numrows > ($start + 10))
  echo "<div align='center'> <a href=\"" . $PHP_SELF . "?start=" . ($start
  + 10) .
  "\">Next Page</a> >></div></div>";

  ?>


-------------------------
Be Successful !

Soleimanian,

Share this post


Link to post
Share on other sites

Can you please explain the php code to me?

I don't understand the

$query = "INSERT INTO guestdb.Guests ( Name, Email ) VALUES ( "    $query .= " '$_POST['Name']' , '$_POST ['Email']'  )";

I understand what it does, but I don't really understand what variable is what.

I also don't understand some of the commands.

Sorry to be a bother, but I'm stupid.

Share this post


Link to post
Share on other sites

$query = "INSERT INTO guestdb.Guests ( Name, Email ) VALUES ( "    $query .= " '$_POST['Name']' , '$_POST ['Email']'  )";

$query is the variable that you request when you want to perform the INSERT command.

guestdb.Guest is the database name and table name for the data to be inserted into.

(Name, Email) are the field names in the table that will be written to.

$_POST['Name'] is the value of the forms text input field named "Name".

<input type="text" name="Name">

$_POST['Email'] is the value of the forms text input field named "Email".

<input type="text" name="Email">

 

Hope this helps, :)

vujsa

Share this post


Link to post
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
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.