Nothing happens after I submit the form - php

So I am building a simple question form that allows a user to submit a question and once the question is submitted it is sent to the database. I can't figure out why it isn't working. Here is my code, first one is the ask.html and the second is the ask.php.
<form action="ask.php" method="POST">
Name: (not your real name)<br/>
<input type="text" name="name" id="name"/>
<br/>
<br/>
Question: <br/>
<textarea name="question" cols="60" rows="10" id="question">
</textarea>
<br/>
<input type="submit" />
</form>
<?php
include('config.php');
include('open_connection.php');
if ((!$_POST[name]) || (!$_POST[question]))
{
header ("Location: ask.html");
exit;
}
//Select database and table
$db_name = "questionme";
$table_name = "questions";
//Insert data into database
$sql = "INSERT INTO $table_name
(name, question) VALUES
('$_POST[name]', '$_POST[question]')";
$result = #mysql_query($sql, $connection) or die(mysql_error());
?>
<html>
<head>
<title>Ask</title>
<head>
<body>
<h1>Question Submitted</h1>
<p><strong>Name:</strong>
<?php echo "$_POST[name]"; ?></p>
<p><strong>Question:</strong>
<?php echo "$_POST[question]"; ?></p>
</body>
</html>

The following is certainly generating warnings:
if ((!$_POST[name]) || (!$_POST[question]))
replace with
if (!isset($_POST[name]) || !isset($_POST[question]))
then absolutely take into consideration what the other dudes answered. On your INSERT:
('$_POST[name]', '$_POST[question]')";
would be better off as (they're also triggering warnings):
('{$_POST['name']}', '{$_POST['question']}')";
And on these
<?php echo "$_POST[name]"; ?></p>
...
<?php echo "$_POST[question]"; ?></p>
have them as
<?php echo $_POST['name']; ?></p>
...
<?php echo $_POST['question']; ?></p>

Check your post variables with isset() and use quotes for the hashes you're checking:
if (!isset($_POST['name']) || !isset($_POST['question']))
Also, never insert the values of your $_POST variables directly - do something like this instead:
$name = mysql_real_escape_string($_POST['name']);
$question = mysql_real_escape_string($_POST['question']);

Have you show_errors PHP configuration enabled?
Try placing some lines like
echo "[1]";
echo "[2]";
etc to discover where your script terminates (debug a bit);
AND NEVER, NEVER USE _POST and _GET variables in SQL queries directly (use mysql_real_escape_string to escape their values)... or your script will be vulnerable to SQL injection attacks!!!

if you are using tables like $_POST['name'] in a string you have to wrap them with a {}
$sql = "INSERT INTO $table_name
(name, question) VALUES
('{$_POST[name]}', '{$_POST[question]}')";
<?php echo "{$_POST[name]}"; ?>
also

Related

PHP form submission with refreshing

first time posting on here so I apologise for any bad habits.
I recently started an online youtube tutorial on php and how to create a blog.
I ended up getting occupied with other things and have come back to try an finish what I started and 2 things have happened. 1: my tutorials have been deleted off youtube(must of been a copyrright issue) and second I've completely forgot the method used. I assume if I was a seasoned coder this would be easy to decipher but I'm having no luck after trying for days now.
This code is for the submission form for my blog. The blog is working in the sense of if I manually input my HTML into the SQL database but all I seem to get if I use this form is a refresh of the submission page with all the information gone. No information is added to the database.
Anybody have an idea?I had a good search around the site but I ran into a dead end due to my lack of knowledge on what I was actually searching for (lots of solutions regarding javascript)
All help will be appreciated.
Sincerely
SGT Noob
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit']))
if ($_POST['submit']) {
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
include_once("../admin/connection.php");
$sql = "INSERT INTO `posts` (Post_Title, Post_Content, Post_Date)
VALUES ('$title','$content','$date')";
mysqli_query($dbcon,$sql);
echo "Post has been added to the database";
}
else {
header('Location: index.php');
die();
}
?>
<html>
<div>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<title> Insert Post </title>
</head>
<div>
<body>
<div id= 'cmssubmissionform'>
<form action="" method="post">
<p>
<h1> Post Title</h1>
<input type="text" name= "Post_Title"/>
</p>
<h1> Post Date</h1>
<input type="text" name= "Post_Date"/>
</p>
<p>
<h1>Post Content </h1>
<textarea name="Post_Content"></textarea>
<script>
CKEDITOR.replace( 'Post_Content' );
</script>
</p>
<p>
<input type = "submit" value="submit" />
</p>
</form>
</div>
</div>
</div>
</body>
try this
in your from change to
<input type = "submit" value="submit" name="submit"/>
You forgot to put the name attribute
The php
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
include_once("../admin/connection.php");
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit'])){
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
$sql = "INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date')";
if(mysqli_query($dbcon,$sql)){
echo "Post has been added to the database";
}else{
header('Location: index.php');
die();
}
}
?>
Note I also changed your SQL statement to
INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date
Notice the back ticks for the table fields
Replace
if (isset($_POST['submit']))
if ($_POST['submit']) {
with
if (isset($_POST['submit'])) {
and then replace
<input type = "submit" value="submit" />
with
<input type ="submit" name="submit" value="submit" />
However, at this stage I would highly suggest starting over with a different tutorial.
Also, as has been mentioned in the comments, whenever you take arguments from a user and put them into a database query, you must absolutely make sure that the strings do not manipulate the query (imagine someone wrote 0'; DROP TABLE `blog`; -- in the date field (and "blog" were the name of your blog post table). That would be quite catastrophic, wouldn't it?
So when you handle input data, either use the prepare and bind methods of the mysqli package, or pass the strings through the mysqli_real_escape_string() function first.

Submit returning a blank page

A blank page is returned when I try to add a new note. My code is in php and the DB is mysql
This is the php code:
if (isset($_POST['Submit'])) {
$candidate_id = $_POST['candidate_id'];
$Notes = $_POST['notes'];
if ($Notes != "") {
$sql3 = "INSERT INTO notes (notes_id, candidate_id, notes) VALUES(DEFAULT,'$candidate_id','$Notes')";
$result3=mysql_query($sql3);
if (!$result3) {
die('Error: ' . mysql_error());
}
echo "</br>1 note added"
}
}
mysql_close();
The code for the form
<div id="tab3">
<h2> Notes </h2>
<dl>
<dt>Notes</dt>
<dd>
<textarea id="notes" style="width: 80%; height: 150px;" name="notes"></textarea>
</dd>
</dl>
<?php
echo "";
?>
</div>
try
if($_SERVER['REQUEST_METHOD']=="POST"){
or
if(isset($_POST['update'])){
instead of
if (isset($_POST['Submit'])) {
the name of the submit button is update not Submit on your form
also stop using mysql_* functions. If you have to use them for now, at least escape the inputs properly before inserting them to database.
To sum this up:
use error reporting in the beginning of your script
error_reporting(E_ALL);
Echo out the SQL query (after you created it) to see what weird, unescaped stuff you want to send to the server:
echo $sql3;
exit; // to prevent execution
Try the echoed SQL with phpmyadmin to see if the problem is your query or the missing database connection.
There are a lot more bad things in your script, but for first error-tracing those tips might be okay... In general, i recommend you to completely rewrite this after you read into SQL injection, modern database query methods, proper php coding etc. ! To finish your project, you should consider using a micro framework to get quick and secure results.
in your submit button you have no form
try this
<div id ="tab3">
<h2> Notes </h2>
<dl><dt>Notes</dt><dd><form action="" method="post" name="myform"><textarea id="notes" style="width: 80%; height: 150px;" name="notes"></textarea></dd></dl>
<?php echo "</form>";
?> </div>
and please avoid using inner css , please use classes in other css file.
Try This
<?php
if(isset($_POST['submit'])){
// Code
<?php
}
else
{
echo "form not submited properly";
}
?>
<?php
include 'header.php';
include 'nav.php';
include 'config.php';
?>
Except
<?php
include 'header.php';
include 'nav.php';
include 'config.php';
?>
<?php
if(isset($_POST['submit'])){
// Code
<?php
}
else
{
echo "form not submited properly";
}
?>

Getting "You have an error in your SQL syntax" error when submit php form

I'm creating a very simple php forum system to integrate with my portal system (I tried to integrate some existent ones, but all I've found have lots of features I don't want, so I decided to create my own).
The page bellow is just a start point from the board creation page, but when I click on submit, I just get the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc='Testing special characters á é ó ç ã ñ'' at line 1
<?php
function renderForm($nome, $desc, $error)
{
$nome = htmlspecialchars($_POST['nome']);
$desc = htmlspecialchars($_POST['desc']);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Nome: *</strong> <input type="text" name="nome" /><br/>
<strong>Desc: *</strong> <input type="text" name="desc" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
include("../../config.php");
if (isset($_POST['submit']))
{
$nome = htmlspecialchars($_POST['nome']);
$desc = htmlspecialchars($_POST['desc']);
if ($nome == '' || $desc== '')
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($nome, $desc, $error);
}
else
{
mysql_query("INSERT forum_boards SET nome='$nome', desc='$desc'")
or die(mysql_error());
}
}
else
{
renderForm('','','');
}
?>
What could be this?
Improper insert syntax. The proper form is:
INSERT INTO forum_boards (`nome`, `desc`) VALUES ('$nome', '$desc')
Also you need to escape your inputs to prevent SQL injection:
$nome = mysql_real_escape_string(htmlspecialchars($_POST['nome']));
$desc = mysql_real_escape_string(htmlspecialchars($_POST['desc']));
ALSO someone will complain that mysql_* functions are depreciated. I feel like a compiler!
Insert works like this:
INSERT forum_boards (colum_name1,column_name2,column_name3) VALUES($value1, $value2, $value3); etc.
Also take care your code is vulnerable to SQL-Injection http://en.wikipedia.org/wiki/SQL_injection
Also take care the mysql_* functions are officially deprecated!
Try to use single quotes in place of double quotes.
Execution speed of single quotes is more than double quotes.
Try to save query in variable, it is more readable
$query='INSERT INTO forum_boards (nome,desc) VALUES("'.$nome.'","'.$desc.'")';
//try to use mysqli,It is much advanced and always use prepared statement
mysqli_query($query);

HTML Form is not sending variables to PHP/MySQL

My problem is that when I enter data into my html form and click submit, it calls my php file but it doesn't send the parameters.
I have even tried using working code to test it, and even the working code is not passing through variables. I am unsure as to why this is doing this, bad php install? No idea.
Here it is, if you want to see if it works at least for you. But I am not getting anything passed into my variables on my php file. Thanks for the help.
<html>
<head>
<title>Home</title>
</head>
<body>
<form method="get" action="reg.php">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>
</body>
</html>
And here is the php file:
<?php
echo $_SERVER['REQUEST_METHOD'];
if(isset($_GET['firstname'])){
$firstname = $_GET['firstname'];
}
else{
$firstname = 'null';
}
if(isset($_GET['lastname'])){
$lastname = $_GET['lastname'];
}
else{
$lastname = 'null';
}
if(isset($_GET['age'])){
$age = $_GET['age'];
}
else{
$age = 'null';
}
$con = mysqli_connect("127.0.0.1","root","", "my_db");
$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES
('$firstname','$lastname','$age')";
$result = mysqli_query($con, $sql);
if ($result)
{
echo "1 record added";
}
else{
echo "Did not work";
}
error_reporting(E_ALL);
mysqli_close($con);
?>
When I look at the error report, it says Undefined Index every time, for each piece of working code I tested. I tested 4 files of working code and neither worked but was proven they did. I am starting to think I have a bad php install or something deeper is the problem. Thanks again.
Three things:
I would recommend you to use POST instead of GET.
Give your input fields an id and it should work.
You need to sanitize your data before writing them into the database.

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