I am having trouble with a form. I am to have 1 script that will do the following: Two form fields : Name, Email 1 Submit Button On submit it should write the Name and Email to an SQL database and it should return all the data in the database tables below the form. When I load my script it shows all the data in the database tables, it is not waiting for me to hit submit. here is my code: Please note I am just learning php. Instructors notes: Your form will be identical to the original form, it will have one submit button. your script will do two actions (actually three) 1) get the POST data and put it in the DB -- if no data (because this isn't the result of a 'submit'), then skip this step. 2) display the form with the proper name and e-mail inserted 3) get the elements from the DB and display them below the form. Yes, you will be able to do all this with one script. <?php /* your logic to process the POST data including connecting to MySQL and putting it into the database */ // Receiving variables @$ip= $_SERVER['REMOTE_ADDR']; @$name = addslashes($_POST['name']); @$email = addslashes($_POST['email']); // Validation //saving record to MySQL database @$strQuery = "INSERT INTO `email`(`Name`,`email`)VALUES (\"$name\",\"$email\")" ; @$host = "localhost"; @$user = "root"; @$pw = ""; @$db = "week3"; $link = mysql_connect($host, $user, $pw); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db($db, $link); if (!$db_selected) { die ('Can not use $db : ' . mysql_error()); } //insert new record $result = mysql_query($strQuery); if (!$result) { die('Invalid query: ' . mysql_error()); } mysql_close($link); $sql = "SELECT * FROM `email` WHERE 1 LIMIT 0, 30 "; mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("week3") or die(mysql_error()); // Retrieve all the data from the "email" table $result = mysql_query("SELECT * FROM email") or die(mysql_error()); // store the record of the "email" table into $row $row = mysql_fetch_array( $result ); ?> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>myform</title> </head> <body> <div id="apDiv1"> <form id="form1" name="form1" method="post" action="working.php"> <p>Name <input type="text" name="name" id="name" /> </p> <p> </p> <p>Email <input type="text" name="email" id="email" /> <input type="submit" name="submit" id="submit" value="Submit" /> </p> </form> </div> </body> </html> <?php echo "<table border='1'>"; echo "<tr> <th>Name</th> <th>Email</th> </tr>"; // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table echo "<tr><td>"; echo $row['Name']; echo "</td><td>"; echo $row['email']; echo "</td></tr>"; } echo "</table>"; ?>
// your database configuration will be here $host="localhost"; $user="root"; $pass=""; $db="dbname"; mysql_connect($host,$user,$pass) or die ("Couldn't connect" . mysql_error()); mysql_select_db($db) or die ("Couldn't select database" . mysql_error()); // when submit button is clicked if ($_REQUEST['type']) { $name=$_POST['name']; $email=$_POST['email']; mysql_query("insert into table_name (name,email) values ('$name','$email')") or die (mysql_error()); } PHP: <body> <div> <form id="form1" name="form1" method="post" action="working.php?type=send"> <p>Name <input type="text" name="name" id="name" /> </p> <p> </p> <p>Email <input type="text" name="email" id="email" /> <input type="submit" name="submit" id="submit" value="Submit" /> </p> </form> </div> <!-------Get the data from the db---------> <table> <tr> <td>Name</td> <td>Email</td> </tr> <?php // fetch the data from the db $result=mysql_query("select * from table_name order by id") or die (mysql_error()); while ($row=mysql_fetch_array($result)) { $name=$row['name']; $email=$row['email']; ?> <tr> <td><?php echo $name;?></td> <td><?php echo $email;?></td> </tr> </table> </div> </body> HTML:
This code that you posted did not work for me. I have redone my script but now I am only returning what I just submitted and I need it to return all the data in that table. Here is my new code. </html> <head> <title>myform</title> </head> <body> <form method="post" action="test.php"> Name: <br /> <input type="text" name="name" size="30" /><br /> Email: <br /> <input type="text" name="email" size="30" /><br /> <input type="submit" value="Submit" /> </form> </body> </html> <?php $databasename='week3'; // Name of the database $tablename='email'; // Name of the table $mysqladd='localhost'; // Address to the MySQL Server - Usually localhost or an IP address $mysqluser='root'; // Your MySQL UserName $mysqlpass=''; // Your MySQL Password @$name = addslashes($_POST['name']); @$email = addslashes($_POST['email']); ///CONNECT TO MYSQL working $link=mysql_connect($mysqladd,$mysqluser,$mysqlpass) or die('Database Error: ' . mysql_error()); //CONNECT TO DATABASE working mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error()); //Get data from Text, Post data to database working $strQuery = "INSERT INTO `email`(`name`,`email`)VALUES (\"$name\",\"$email\")" ; $result = mysql_query($strQuery); if (!$result) { die('Invalid query: ' . mysql_error()); } // print data table from database $result = mysql_query("SELECT * FROM email"); if($row = mysql_fetch_array($result)) { echo $row['name']; echo $row['email']; echo "<br />"; } // this doesn't return all the data in the table. It is only returning what I just entered. ?>
The reason you're not receiving all the information from the database is because you're using an "if" statement where you should be using a "while" statement (or for the masochists, you could essentially do the same thing with a "for" statement but it would make your code messier) Change this: (Last statement) if($row = mysql_fetch_array($result)) { echo $row['name']; echo $row['email']; echo "<br />"; } PHP: to this: while($row = mysql_fetch_array($result)) { // Let's keep the code clean with 1 echo statement :) The "."'s have a construction/additive property :D echo $row['name']." ".$row['email']."<br />"; } PHP: Regards, Dennis M.
If I change the if statement to a while statement it then returns the data when the scripts loads. It does not want for me to enter in the data and hit the submit button. If I use the if statement it waits for me to hit the submit button before it returns the display data.
Ah normally I separate the pages with switch($_GET['page']){ case default: echo "blah"; break; case '1': echo "?page=1 is displayed here"; break; } to get around that try this: leave the if statement and add the while E.g.: // In terms of security it would be best to separate pages but this should work if($row = mysql_fetch_array($result)){ while($row = mysql_fetch_array($result)) { // Let's keep the code clean with 1 echo statement :) The "."'s have a construction/additive property :D echo $row['name']." ".$row['email']."<br />"; } } PHP: Regards, Dennis M.
ok I tried using the code you posted and it returns this error Parse error: parse error in C:\wamp\www\index\sat\test.php on line 62 $result = mysql_query("SELECT * FROM email"); while($row = mysql_fetch_array($result)) { echo $row['name']." ".$row['email']."<br />"; } If I remove the if(!empty($row)){ I get all the data when I run this script. I need to get this to print the database content to the screen when I hit the submit button. It must first enter the data the user submitted to the database then display it.
I did not post empty($row). If you read the post (I had to edit it I accidentally put that in there combining another script I was working on) I took that out and kept the if statement like so: if($row = mysql_fetch_array($result)){ while($row = mysql_fetch_array($result)){ echo $row['name']." ".$row['email']."<br />"; } } Regards, Dennis M.
This is how my code was to look like. I know I did something wrong there is no if statement. So I don't know how to fix it. HTML start Declare Variables: Connect to SQL- Connect to database - If (data exists) then Get data from Text, Post data to database HTML form with submitted data Print data table from database /HTML
I don't understand the question then? if(){ while(){ } } should be the format of what you're looking for or where exactly are you having the problem? I apologize, but the question at the moment remains unclear to me. Regards, Dennis M.
I am confused as well. Here is what he said about my code. 1. Note the blank entry in the table and the gap in the entries below the form. This is because your routine writes empty data into the DB when there is no POST array -- on the initial activation of your PHP script when you put the url into you browser. This first activation is done with an HTTP GET, not an HTTP POST (form submission). However your script does not detect that and writes an empty row into the database. 2. Also, your script does not put the values (sixth, in this case) back into the form after the submit. Check out the code I posted as last weeks example script for how that can be done. Other than those two problems, you are A-OK.
If you post your whole script (working.php included) as well as the DB structure I could do it for you instead of trouble shooting But, to avoid the entry of empty set information put this around the additive statement: if(!empty($_POST) OR !empty($_GET)){ // code - not sure if you're using $_POST or $_GET as I'm not really sure of your whole code // sorry about that } PHP: Regards, Dennis M.
Database name is week3 table is called email table columns are name, email thank you so much for your help. </html> <head> <title>myform</title> </head> <body> <form method="POST"action="myform.php" > Name: <input type="text" name="name" size="30" /><br /> Email:<input type="text" name="email" size="30" /><br /> <input type="submit" value="Submit" /> </form> </body> </html> <?php $databasename='week3'; // Name of the database $tablename='email'; // Name of the table $mysqladd='localhost'; // Address to the MySQL Server - Usually localhost or an IP address $mysqluser='root'; // Your MySQL UserName $mysqlpass=''; // Your MySQL Password @$name = addslashes($_POST['name']); @$email = addslashes($_POST['email']); ///CONNECT TO MYSQL working $link=mysql_connect($mysqladd,$mysqluser,$mysqlpass) or die('Database Error: ' . mysql_error()); //CONNECT TO DATABASE working mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error()); //Get data from Text, Post data to database working $strQuery = "INSERT INTO `email`(`name`,`email`)VALUES (\"$name\",\"$email\")" ; $result = mysql_query($strQuery); if (!$result) { die('Invalid query: ' . mysql_error()); } // print data table from database $query = ("SELECT * FROM email"); $data = mysql_query($query); echo '<table>'; while( $row = mysql_fetch_assoc($data) ) { echo $row['name']." ".$row['email']."<br />"; } ?> Code (markup):
After reviewing and making changes the empty() statement seems to be the solution. I tested and works fine. Here is what happens: 1.) Page loads and shows current data below form. 2.) As long as user has not submitted information prior (meaning has $_POST information stored prior) refresh does not do anything 3.) User submits information and instantly joins information below Here is the solution. Change the while statement to look like this: echo '<table>'; if(!empty($_POST)){ while( $row = mysql_fetch_assoc($data) ) { echo $row['name']." ".$row['email']."<br />"; } } PHP: Now like I mentioned earlier in step 2, there is a bug. Major if this was a production script. Normally there is some sort of var in the DB to check against and then you would run a check against the DB and it wouldn't accept the duplicate data. The error is when someone inputs information and they refresh, the $_POST data is still stored and it just resends to the form like the user just hit submit. But if the user leaves the page and comes back, this would not be the case. Again, not a major flaw if this is a non-production script but it's still there! Cheers Regards, Dennis M.
I am so excited it fixed the printing the data on startup. Thank you so much. Now there is one more issue. How do I stop the script from posting a blank entry into the database when it first runs it is not waiting to me to hit submit.
My teacher said I should use (isset($_POST['submit'])) to fix the issues, but every where I use this I get an error.
I was able to get if (isset($_POST['submit'])) to work in my code. I was missing a } at the bottom of my code and I didn't have my button named. So I add those two things and got it. Thank you for your help with this. I have learned more from you than I have my instructor.