Taking mySQL database input from HTML form with PHP - php

I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>

You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.

Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.

Related

Random Number Resets

My random number generates on page load, but seems to reset when the user clicks the "Guess" button. I still have a lot of building to go with this, but at the end I want the user to be able to make multiple guesses to guess the random number. I want it to generate when the page first comes up and stay the same until correctly guessed. I'm not sure what I'm doing wrong and just starting this program. If you answer, please also explain, as I'm trying to learn what I'm doing. Thank you!
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>PHP Homework 2</title>
<link rel="stylesheet" href="styles/styles.css">
</head>
<body>
<section id="main">
<h1>Play the Guessing Game!</h1>
<section id="left">
<h2>Take a Guess!</h2>
<form action="mine.php" method="post">
<div id="guessBox">
<label id="guessLB">Your Guess:</label>
<input id="guessTB" class="num" type="number" name="guessTB" max="1000" min="1">
</input>
</div>
<input type="submit" id="guessButton" name="guessBTN" value="Guess" />
</form>
</section>
<section id="right">
<h2>Game Stats</h2>
<?php
if(isset($_POST['guessTB']))
{
$randomNum = $_POST['guessTB'];
}
else
{
$randomNum = rand(1,100);
}
echo "<p>Random Number: $randomNum</p>";
?>
</section>
</section>
</body>
</html>
UPDATE: My HTML has remained the same, and I'm posting my new PHP code. But I used a session and wrote some more. However, I've come across two problems:
1) If I refresh the page, I get an error that says that the first instance of $randomNum below the session_start(); is unidentified.
2) It seems that it remembers my very last guess in the game. If I close out the page and reopen it, I immediately get one of the messages that my guess was too high or too low, even before making a guess. Any advice is appreciated!
<?php
session_start();
$randomNum = $_SESSION['randomNum'];
$guess = $_POST['guessTB'];
if(!isset($_SESSION['randomNum']))
{
$_SESSION['randomNum'] = rand(1,1000);
}
else
{
if($guess < $randomNum)
{
echo "<p>Your Guess is Too Low! Try Again!</p>";
}
else if($guess > $randomNum)
{
echo "<p>Your Guess is Too High! Try Again!</p>";
}
else
{
echo "<p>You Won!</p>";
$_SESSION = array();
session_destroy();
}
}
echo "<p>Guess: $guess</p>";
echo "<p>Random Number: $randomNum</p>";
?>
What you can do is use sessions. On every load check if you set it in the session and if it's not set, generate new number and set it, then check what the user input and compare the two numbers. This could also be done with cookies. Another thing you can do is use js. On load store the generated number in some js variable and don't use a form. On button click get the value of the input field and compare with the one you store in the variable.

Php code symbols escaped after execution (Sublime editor)

I am aware that this might be a question with an obvious answer but I for a php-newbie it is SO not!
I am writing php code with Sublime inside a file together with html and after I execute the files my code changes. The <and > is written with its escaping characters. Help..please..
<?php
$username= trim($_POST['username']);
$pass= trim($_POST['pass']);
$userExist= trim($_POST['userExist']);
$passExist= trim($_POST['passExist']);
// print_r($username);
// print_r($pass);
$conn= mysqli_connect('localhost','neli','','yogies');
// if(!$conn){
// echo "No database";
// exit;
// }else {
// // echo "Done";
// // }
if(isset($username) && isset($pass)){
$usernameCheck = mysqli_query($conn, 'SELECT username FROM users WHERE username="'.$username.'"');
// print_r('SELECT username FROM users WHERE username="'.$username.'"');
if( $usernameCheck && $usernameCheck->num_rows ){
$check= 1;
} else {
$check=0;
}
}
if($check==0){
$userToEnter =$username;
$userToEnter = mysqli_real_escape_string($conn, $userToEnter);
$passToEnter = $pass;
$passToEnter = mysqli_real_escape_string($conn, $passToEnter);
$sql = 'INSERT INTO users (username,password) VALUES ("'.$userToEnter.'","'.$passToEnter.'")';
// print_r($sql);
if(mysqli_query($conn, $sql)){
session_start();
// print_r('here');
// print_r($_POST['url']);
$doc = new DOMDocument();
// html5 problems with tags
// libxml_use_internal_errors(true);
$doc->loadHTMLFile('header_nav.php');
// html5 problems with tags
// libxml_clear_errors();
$doc->getElementById('sign')->setAttribute('display','none');
$doc->getElementById('logout')->setAttribute('display','block');
$doc->saveHTMLFile('header_nav.php');
// header('Location: '.$_POST['url']);
}
}else{
print_r('Nope');
}
?>
<!DOCTYPE html>
<html class="wallpaper">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./styles/css.css">
<title><?php echo $pageTitile ?></title>
</head>
<body>
<header><div class="top">
<img src="./pictures/logo.png" height="80px" width="80px">
Log in
Log out
<nav><ul><li>Yoga Poses</li>
<li class="subList">
<span id="levels">Yoga Levels <img id="arrow" src="./pictures/arrow.png"></span>
<ul class="dropdown"><li>All levels</li>
<li>Level 1</li>
<li>Level 2</li>
<li>Level 3</li>
<li>Level 4</li>
</ul></li>
<li>Healthy and Delicious</li>
</ul></nav></div>
<div id="overlay">
<div id="background"></div>
<form id="loginForm" name="login" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!-- <input type="hidden" name="url" value="<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>"> -->
<fieldset id="bordered"><legend>Register:</legend>
<p>Username:<input type="text" name="username"></p>
<p>Password:<input type="password" name="pass"></p>
<p>Repeat pass:<input type="password" name="pass2"></p>
</fieldset><fieldset><legend>Log in:</legend>
<p>Username:<input type="text" name="userExist"></p>
<p>Password:<input type="password" name="passExist"></p>
</fieldset><div class="btns">
<button id="btnSubmit" class="btn" type="button" value="Submit">Submit</button>
<button class="btn" type="button" value="Cancel">Cancel</button>
</div>
</form>
</div>
</header>
</body>
</html>
It looks like this script is modifying itself, and using DOMDocument to do it. PHP scripts aren't valid HTML/XML, so DOMDocument mangles the code up - it's not Sublime's fault :)
The way to make the code do what you expect here is put the header HTML into a separate file (like header_nav.html), manipulate that instead, and then make your script output it to the user rather than save it.
But modifying a file with DOMDocument is probably way over the top for what you need, and there are other problems with that approach too. That file gets given to everyone, so as soon as one person logs in, everyone gets that header_nav. It also writes to disk when you only really need to change the code in memory and pass it to just that user.
Something much more simple would be to have two header html files (like header_logged_in.php and header_logged_out.php) and then make your header_nav.php just include('header_logged_in.php') if the user is logged in, or include('header_logged_out.php') if they're not.
Some other notes:
Never take something from $_POST and put it straight into an SQL query - you trim it, but that’s no safety at all. The safe way to do it is by using prepared statements. Have a look at PHP The Right Way on how to do that (the examples use PDO which is what I’m more familiar with, but mysqli is okay too if you prefer it).
If either $username or $pass are empty, then $check is never set, so you’d get a PHP strict error telling you that $check is undeclared. You could just add $check = 0 before the if ($check == 0)… line to solve that. Also, use true and false instead of 1 and 0, and === instead of == - though it's a matter of taste in this instance, if you do it elsewhere too then it'll bite you eventually.
It’s commented out, but a later line does header(“Location: “.$_POST[‘url’]) which is also kinda bad - anyone could put any URL into that and redirect your users to their site. It’d be better to build the URL yourself or use an array of valid URLs and point to the right key in the array or something.
You start the session, but you don’t put anything in it (like… whether the user is logged in, and what their username is).
Make sure the doc type is .php and not HTML.
Click the syntax highlighting menu and choose PHP, the language chosen is HTML, make sure PHP is checkmarked.
Otherwise:
To edit the preferences:
1) - Preferences ==> Browse Packages...
2) - Go to the HTML folder & Open "HTML.tmLanguage" with a text editor
3) - Find :
firstLineMatch
<string><!(?i:DOCTYPE)|<(?i:html)|<\?(?i:php)</string>
And replace it with :
firstLineMatch
<string><!(?i:DOCTYPE)|<(?i:html)</string>
4) - Restart Sublime Text.

How to prevent a php script form changing to another page

I used a sample I found here with a HTML page calling a PHP script, both are listed below.
It all works well - BUT, I end up with the PHP scrip page and I want to avoid it - I want to stay on the HTML page and NOT move anywhere. I read in some places that I will need JS or AJAX but can't see any actual example.
I am working on my PC under Windows 7 with IIS version 7.5 installed, PHP 5.3.28.
and executing the HTML file inside c:\inetpub.wwwroot
HTML
<div id="contact">
<h2>Enter your First and Last Name</h2>
<form action="frm_script.php" method="post" target="_parent">
<p><strong>First Name:</strong><br /> <input type="text" name="firstName" /></p>
<p><strong>Last Name:</strong><br /> <input type="text" name="lastName"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</div>
PHP Script
<?php
if(isset($_POST['submit']))
{
//get the name and comment entered by user
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
//connect to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'mdpdata') or die('Error connecting to
MySQL server');
$check=mysqli_query($dbc,"select * from clients where firstname='$firstname' and
lastname='$lastname'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0)
{
print "customer exists";
}
else
{
//insert results from the form input
$query = "INSERT INTO clients(firstName, lastName) VALUES('$firstName', '$lastName')";
$result = mysqli_query($dbc, $query) or die("Sorry, Duplicate Record.'$php_errormsg'");
mysqli_close($dbc);
}
print '<script type="text/javascript">';
print 'alert("The Customer is NOW registered")';
print '</script>';
};
?>
A html document containing a form with an action="" statement results to change to the assigned page. Like yours, to frm_script.php
If you don´t want this to occure, you need an AJAX-request, as you mentioned above, or you can add a
header(location: 'FPRM.HTML');
to the bottom of the php script. So after processing, which should be very fast, the original page is loaded again.
Or you don´t use two pages at all. Just put the html code from FPRM.HTML to the bottom, after the php code, so the page just will be reloaded once the form values are saved. In this case, call the concatenated document simply FPRM.php, and the form action must be set to action="FPRM.php" or is simply not needed, as the form without action statement loads the same page anyway.

How do I change the value of textarea by option selected?

I am trying to change the contents of depending on the current option selected.
The getData(page) comes back correctly (onChange) but it just doesn't go over to the variable I get "Fatal error: Call to undefined function getData() in C:\xampp\htdocs\pdimi\admin\editpages.php on line 42"
EDIT: This is how I finished it!
Javascript:
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
Select form:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<select name="page" onChange="getData(this)">
<?php
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_POST['page']);
else
$page = '';
$query = "SELECT pageid FROM pages;";
?>
<option value="select">Select Page</option>
<option value="indexpage">Index Page</option>
<option value="starthere">Start Here</option>
</select>
Textarea:
<textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data">
<?php
if (isset($_GET['page'])) {
$sql1 = #mysql_query("SELECT * FROM pages WHERE pageid='".$_GET['page']."'") or die(mysql_error());
$sql2 = #mysql_fetch_array($sql1) or die(mysql_error());
if ($sql1) {
echo $sql2['content'];
}
}
?>
</textarea>
And that is that!
You cannot execute a Javascript function (client side) from PHP (which runs server side).
Also, you need to connect to a database server with user and password, and select a database. Do not use #, it will only prevent you from seeing errors -- but the errors will be there.
In the PHP file you need to check whether you receive a $_POST['page'], and if so, use that as the ID for the SELECT. You have set up a combo named 'page', so on submit the PHP script will receive the selected value into a variable called $_POST['page'].
Usual warnings apply:
mysql_* functions are discouraged, use mysqli or PDO
if you still use mysql_*, sanitize the input (e.g. $id = (int)$_POST['page'] if it is numeric, or mysql_real_escape_string if it is not, as in your case)
If you want to change the content of textarea when the user changes the combo box, that is a work for AJAX (e.g. jQuery):
bind a function to the change event of the combo box
issue a call to a PHP script server side passing the new ID
the PHP script will output only the content, no other HTML
receive the content in the change-function of the combo and verify success
set $('#textarea')'s value to the content
This way you won't have to reload the page at each combo change. Which reminds me of another thing, when you reload the page now, you have to properly set the combo value: and you can exploit this to dynamically generate the combo, also.
Working example
This file expects to be called 'editpages.php'. PHP elaboration is done (almost) separately from data presentation.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>PDIMI - The Personal Development and Internet Marketing Institution</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css' />
<link href="../style/default.css" rel="stylesheet" type="text/css" media="all" />
<!--[if IE 6]>
<link href="default_ie6.css" rel="stylesheet" type="text/css" />
<![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
</head>
<?php include 'aheader.php';?>
<?php
error_reporting(E_ALL);
if (!mysql_ping())
die ("The MySQL connection is not active.");
mysql_set_charset('utf8');
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_REQUEST['page']);
else
$page = False;
$query = "SELECT pageid, pagename FROM pages;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec)
trigger_error("Cannot fetch data from pages table: " . mysql_error(), E_USER_ERROR);
if (0 == mysql_num_rows($exec))
trigger_error("There are no pages in the 'pages' table. Cannot continue: it would not work. Insert some pageids and retry.",
E_USER_ERROR);
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['pageid'] === $page)
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $page)
$page = $row['pageid'];
$sel = '';
}
$options .= "<option value=\"{$row['pageid']}\" $sel>{$row['pagename']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['page_data']))
{
$page_data = mysql_real_escape_string($_POST['page_data']);
$query = "INSERT INTO pages ( pageid, content ) VALUES ( '{$page}', '{$page_data}' ) ON DUPLICATE KEY UPDATE content=VALUES(content);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
// Anyway, recover its contents (maybe updated)
$query = "SELECT content FROM pages WHERE pageid='{$page}';";
$exec = mysql_query($query);
// who says we found anything? Maybe this id does not even exist.
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textarea = $row['content'];
}
else
$textarea = '';
mysql_free_result($exec);
?>
<body>
<div id="page-wrapper">
<div id="page">
<div id="content2">
<h2>Edit Your Pages Here</h2>
<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>
<form name="editpage" method="POST" action="">
<table border="1" width="100%">
<tr>
<td>Please Select The Page You Wish To Edit:</td>
<td>
<select name="page" onChange="getData(this)"><?php print $options; ?></select>
</td>
</tr>
<tr>
<td><textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data"><?php print $textarea; ?></textarea></td>
</tr>
<tr>
<td><input type="Submit" value="Save the page"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
The biggest issue that you have here, is that you need to learn the difference between client side and server side.
Server Side: As the page is loading... We run various code to determine what is going to be displayed and printed into the source code.
Client side: Once the page has loaded... We can then use DOM elements to interact, modify, or enhance the user experience (im making this up as i go along).
In your code, you have a PHP mysql command:
$thisdata = #mysql_query("SELECT * FROM pages WHERE pageid=".getData('value'));
1, Don't use mysql. Use mysqli or PDO
2, You have called a javascript function from your PHP.
There is absolutely no way that you can call a javascript function from PHP. The client side script does not exist and will not run until after the page has stopped loading.
In your case:
You need to server up the HTML and javascript code that you will be using. Once, and only when, the page has loaded, you need to use javascript (client side scripting), to set an event listener to listen for your select change event. Once this event is triggered, then you can determine what you want to do (ie change a textbox value, etc).

PHP: Using POST on a dynamic page redirects me to index.php and does not post the values

I am trying to get a guest book to work using PHP. I have managed to make it function, the thing is that I don't want the guest book to be in my index.php. I want it to be on a dynamic page, index.php?=guestbook for instance.
The problem is that when I put the code on another page rather than index.php the thing that happends when I fill out the fields and press the submit button, I get redirected to index.php and nothing is submited to my database. This all works fine as long as the code is in the index.php.
My first question is: What is causing this?
Second question: How do I get the code to function properly eventhough I have it in index.php?=guestbook?
Thanks in advance!
I am using xampp btw.
See below for the code:
<html>
<head>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Guestbook</h1><hr>
<?php
mysql_select_db ("guestbookdatabase") or die ("Couldn't find database!");
$queryget = mysql_query ("SELECT * FROM guestbook ORDER BY id ASC") or die("Error witch query.");
$querygetrownum = mysql_num_rows ($queryget);
if ($querygetrownum == 0)
echo "No posts have been made yet. Be the first!";
while ($row = mysql_fetch_assoc ($queryget))
{
$id = $row ['id'];
$name = $row ['name'];
$email = $row ['email'];
$message = $row ['message'];
$date = $row ['date'];
$time = $row ['time'];
if ($id%2)
$guestbookcomment = "guestbookcomment";
else
$guestbookcomment = "guestbookcommentdark";
echo "
<div class='$guestbookcomment'>
<div class='postheader'>
<b>Posted by $name ($email) on $date at $time</b>
</div>
<div class='message'>
".nl2br(strip_tags($message))."
</div>
</div>
";}
echo "<hr>";
if($_POST['submit'])
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$date = date("Y-m-d");
$time = date("H:i:s");
if ($name&&$email&&$message)
{
$querypost = mysql_query ("INSERT INTO guestbook VALUES ('','$name','$email','$message','$date','$time')");
echo "Please wait... <meta http-equiv='refresh' content='2'>";
}
else
echo "Please fill out all fields.";
}
echo "
<form action='index.php' method='POST'>
Your name: <input type='text' name='name' class='name' maxlength='25' ><br> <br>
Your email: <input type='text' name='email' class='email' maxlength='35'><br><br>
<div class='your_message'>
Your message:<input type='textarea' name='message' class='messagetextarea' maxlength='250'><br><br>
</div>
<input type='submit' name='submit' value='Post'>
</form>
";
?>
</body>
</html>
1) The action property of your form should be the same as the name of the file where the code is in. :) You create a guestbook.php, for example, but the action still is 'index.php'. Hence the problem. You send the POST data to index.php but there's no code to process it.
2) The query string doesn't affect the form. Only the filename.
I hope I understood your problem correctly.
Have you tried updating your form's action parameter to:
index.php?=guestbook
instead of just index.php?
If the problem resides on the server end than the victim to your problem is .htaccess (mod rewrite);
Otherwise, what do you really mean by this line of code?
echo "Please wait... <meta http-equiv='refresh' content='2'>";
< meta > refresh tag requires location to be mentioned where the redirect otherwise according to you refreshes the current page..
<meta http-equiv="refresh" content="2;url=http://stackoverflow.com/">
First, I'm assuming the file you're showing is index.php
Second, don't use index.php?=guestbook. URL parameters work within a key => value structure. In you're case you've only defined the value and no key.
Try using index.php?page=guestbook. this way, in your index.php file you can do something like:
if($_GET['page'] == 'guestbook') {
// ... your guestbook php code.
}
Then try setting your forms action attribute like this: action="index.php?page=guestbook".
Third, I'm going to assume that you have mysql connection code that isn't shown here. If not, take a look at mysql_connect().
Fourth, NEVER use unescaped data in a SQL query. You MUST escape your data to protect your database from being destroyed. Take a look at this wikipedia article which describes SQL Injection in greater detail: http://en.wikipedia.org/wiki/SQL_injection
Then take a look at mysql_real_escape_string() to learn how to prevent it with PHP and MySQL.
Fifth, don't use <meta http-equiv='refresh' content='2'> for redirect. Use PHP's header() function to redirect users, like this:
header('location: index.php');
exit(); // be sure to call exit() after you call header()
Also, just so you know, you CAN close PHP tags for large HTML blocks rather than using echo to print large static chunks of HTML:
<?php
// ... a bunch of PHP
?>
<form action="index.php" method="POST">
Your name: <input type="text" name="name" class="name" maxlength="25" ><br> <br>
Your email: <input type="text" name="email" class="email" maxlength="35"><br><br>
<div class="your_message">
Your message:<input type="textarea" name="message" class="messagetextarea" maxlength="250"><br><br>
</div>
<input type="submit" name="submit" value="Post">
</form>
<?php
// ... some more PHP
?>

Categories