HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.
Related
My issue I believe is fairly simple but after a whole day trying different variations I have resorted to bothering you guys, please excuse me if this has been covered but I could not find a close enough example
I have a php file that is a processing file for a simple html form
Process.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host="1.2.3.4:3306"or die("wrong server"); // Host name
$username="username"or die("wrong Username"); // Mysql username
$password="password"or die("Wrong Password"); // Mysql password
$db_name="db-name"or die("wrong DB"); // Database name
$tbl_name="banned"or die("Wrong table"); // Table name
$member = isset($_REQUEST['member']) ? $_REQUEST['member'] : "";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$find_member = mysql_query("SELECT member FROM banned WHERE member='$member'")or
die(mysql_error());
$ban = mysql_fetch_array($find_member);
if($member == $ban['member']){
echo ("this member is banned");
}
else {
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' style='display:none;' value='<?php echo
htmlspecialchars($member);?'/>'
<button type='submit'>Continue</button>");
}
?>
Form.html:
<form method="post" action="http://example.com/process.php">
<input type="text" name="member">
<input type="submit">
</form>
What im trying to accomplish:
A user would type their member number in the form.html and click submit, process.php will catch POST and either echo the text "this member is banned" or if member number is not on banned sql table, then display a html button with with a hidden input field that will carry the $member variable on to the next page
What is actually happening
no matter what number is entered into the form.html it always displays the html button. there is one number on the blacklist but when entered still displays the button
Error reporting
php and sql error reporting displays no errors
Side note
DB structure
member VARCHAR(20) / id (auto increment) / Time (timestamp - defalt:current time stamp)
The member number is Alphanumeric and is max 15 characters
example: +ayw7394
The initial error of using:
if($member = $ban['member']){
was replaced with:
if($member == $ban['member']){
but produces the opposite effect of echoing the "banned member" message regardless of which number is being inputed
It seems as though the
if statements are being ignored
Can anyone please provide me with some advice?
thank you for your help so far
"no matter what number is entered into the form.html it always displays the html button. there is one number on the blacklist but when entered still displays the button"
The reason being is this:
In this if($member = $ban['member']) you're assigning = instead of comparing == to compare $member against the "member" row.
Change that to if($member == $ban['member'])
I must note that your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Footnotes:
</input> isn't a valid closing tag and can be safely removed.
Edit:
Also this code block:
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' style='display:none;' value='<?php echo
htmlspecialchars($member);?'/>'
<button type='submit'>Continue</button>");
You're already in PHP, so there's no need for the <?php echo and ?>
Change it to:
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' value='".htmlspecialchars($member)."'/>
<button type='submit'>Continue</button>");
Which could explain why it shows "banned" because you're probably re-clicking on it after.
I suggest you just remove it and do a redirection instead.
Example, and by replacing it with the echo'd button:
else{
header("Location: your_form.html");
exit;
}
Your problem is at the line
if($member = $ban['member']){
This is actually always true because you are setting $member to be equal to $ban['member']. Did you mean ?
if($member == $ban['member']){
Echo $member and $ban['member'] to see if they are the same or different value.
Another step, other than guarding against SQL injection like someone else said, would be to run TRIM commands on your input and on your MYSQL fields to ensure spaces aren't an issue.
Every time I try to refresh the page I get a new row. I tried to read many posts regarding to this problem, but I couldn't do anything since I'm new in database programming.
I don't know where the value come from, because the same value is repeated over and over.
My code.
<?php
require('connect.php');
$sql="CREATE TABLE test(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(25),message LONGTEXT)";
if($sql==true){
$res=mysql_query( $sql);
}
?>
<?php
$user=null;
$message=null;
if(isset($_POST['user'])){
$user=$_POST['user'];
}
if(isset($_POST['message'])){
$message=$_POST['message'];
}
if(!empty($_POST)){
if($user&&$message){
$insert=mysql_query("INSERT INTO test(user,message)VALUES('$user','$message')");
}
else{
echo "please fill out the fields";
}
}
?>
<html>
<body>
<form action="database.php" method="post">
<p><label for="user">Name:</label><br/>
<input type="text" name="user" id="user"/></p>
<p><label for="message">Message:</label><br/>
<textarea ="message" name="message"> </textarea></p>
<button type="submit" name="submit" value="send">Send Message:</button>
</form>
<br/><br/><tr><td>The Users Comments:</td><td><br/><br/>
</html>
<?php
$query=mysql_query("SELECT * FROM test ORDER BY id DESC");
while($row=mysql_fetch_ASSOC($query)){
$name=$row["user"];
$message=$row["message"];
echo "username:",$name,'<br/>'," Messages: ",$message,'<br/>','<br/>';
}
?>
Problem is that everytime you refresh the page your browser is re-posting the same data. To workaround it you should consider implementing the Post, Redirect, Get pattern in your page.
Fundamentally this means that upon a successful POST (i.e. row was inserted) you should redirect to another page. This effectively stops the user from having the ability to re-post the same data.
The link above has a good overview of how to implement...
I don't find a problem in your code. Probably when you post data first time and then refresh the page, data is posted again. Most of the browsers like firefox gets confirmation if browser is re-posting data.
Edit:
To avoid this you must use redirect to GET method. see this
try to edit this
Blockquote
if(!isset($_POST)){
if($user && $message){
$insert=mysql_query("INSERT INTO test(user,message)VALUES($user,$message)");
}
and be sure ctrl+f5 then refresh page
Before insert check database if those values are present in database or not
like
if(!empty($_POST)) {
if($user && $message) {
//check if this user and message in present database or not
$query = mysql_query("SELECT * FROM test WHERE user='".$user."' AND message='".$message."'");
$count = mysql_num_rows($query);
if ($count > 0 ){ // if $count is greater than 0 means values exists in database then
echo "Data exists";
}
else {
// insert
$insert=mysql_query("INSERT INTO test(user, message) VALUES ('$user','$message')");
}
}
else {
echo "please fill out the fields";
}
it is just a example you can modified it with your requirement :)
I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5
I am trying to make a VERY simple PHP form that posts a form to MySQL Database, however I am having some issues, and would welcome a simple fix for this if possible:
My PHP:
<?php
$con=mysqli_connect("serveraddress","db","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (email, type, cats)
VALUES
('$_POST[email]','$_POST[type]','$_POST[cats]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
My HTML:
<form action="personuploader.php" method="post">
<table class="#">
<tr>
<th colspan="2">Test</th>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="text" name="email"> </td>
</tr>
<tr>
<td>Type:</td>
<td><input type="text" name="type"> </td>
</tr>
<tr>
<td>Cats:</td>
<td><input type="text" name="cats"> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="upload" name="upload">
</tr>
</table>
</form>
My SQL Configuration:
Even though I have not null set in the DB I am getting empty results, is it possible to stop the form resubmitting on refresh causing null results be entered into the DB. I will enter some form validation to stop null results passing into the post script in the future but refreshing the page still sends over null results.
Edit:
Your column names have mixed-case letters (Cats and cats are not the same)
I edited my answer, where I changed it from:
$sql="INSERT INTO `Persons` (`email`, `type`, `cats`)
to
$sql="INSERT INTO `Persons` (`Email`, `Type`, `Cats`)
I also made a mistake with a missing ) for if(empty($_POST['email'] which has been fixed.
Please make sure also, that your column names are indeed called Email Type Cats and not email type cats Change it to the letter-case that is in your DB.
Your table's original structure: (larger image)
You should have talked to me first, instead of posting a new question with my code
See the rest below in the code.
As I stated in my comments under your original question, have put this together for you.
Don't use this method VALUES ('$_POST[email]','$_POST[type]','$_POST[cats]') you're open to SQL injection
To avoid re-submissions causing an empty entry, you can use a header() to redirect to another page, or use AJAX
However, I am sure there are other ways of doing this in the query itself, I just don't remember how right now.
I.e.: In place of where you have echo "1 record added";
you can do header("Location: added.php"); exit();
You can also use a conditional statement:
if(empty($_POST['variable'])){ die("Fill this in.");}
Try the following. It will check for empty fields, as well as check if the upload submit-type button is set.
Plus, I modified the way your query was done, replacing POST variables with mysqli_real_escape_string()
<?php
$con=mysqli_connect("serveraddress","db","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['upload'])){
// You can replace the || with && if required
// depending on what you want to check for.
if(empty($_POST['email']) || empty($_POST['type']) || empty($_POST['cats']))
{
die("You need to fill in all the fields.");
}
$email = mysqli_real_escape_string($con, $_POST['email']);
$type = mysqli_real_escape_string($con, $_POST['type']);
$cats = mysqli_real_escape_string($con, $_POST['cats']);
$sql="INSERT INTO `Persons` (`Email`, `Type`, `Cats`)
VALUES ('$email','$type','$cats')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
// Uncomment out if you're going to use echo, but not with header.
// echo "1 record added";
header("Location: redirect_to_other_page.php");
exit();
} // end of if(isset($_POST['upload']
// else conditional statement for if(isset($_POST['upload']
else{ echo "You cannot do this operation from here."; }
mysqli_close($con);
?>
Footnotes:
Just saying, the following:
('$_POST[email]','$_POST[type]','$_POST[cats]')
should have been:
('$_POST['email']','$_POST['type']','$_POST['cats']')
However, using this method is highly discouraged, as I already mentioned.
You need to check if a submit actually occured:
if ($_SERVER["REQUEST_METHOD"] == 'POST') {
... submit occured, do DB stuff
}
And note that an empty string is NOT the same as an SQL null. Empty string is just that - a string which happens to be empty/zero-length. An SQL null is quite literally "unknown". Your code cannot insert an actual null - it can only ever insert empty strings.
You should check whether the Upload button has been clicked on the "personuploader.php" file.
// Initializing Variables
$email = '';
$type = '';
$error = false;
if ( isset ( $_POST['upload'] ) ) {
// Then capture the POST Variables
$email = $_POST['email'];
// Do Some Validations
if ($email == '') {
$error = true;
}
// Process the Form if NO Errors
if ($error == false) {
// Insert The Data into DB
}
}
I just start coding in PHP,
i wrote my first php + mysql program for inserting data through web form. it works fine, but whenever i refresh the page, it automatically saves null record to my database.
i know the solution in .NET is ispostback, but not in php?
can somebody give me some idea in PHP.
Code is here:
<body>
<form action="mySQLTest.php" method="post">
First Name :<input type="text" name ="txtFirstName"/> <br/>
Last Name: <input type="text" name ="txtLastName"/> <br/>
Age : <input type="text" name= "txtAge" /> <br/>
<input type="submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not Connect:' .mysql_error());
}
mysql_select_db("test", $con);
if($_REQUEST[])
{
$sql1 = "Insert into info(FirstName, LastName, Age) Values('$_POST[txtFirstName]','$_POST[txtLastName]','$_POST[txtAge]')";
}
if(!mysql_query($sql1, $con))
{
die('Error: '.mysql_error());
}
else
{
echo "1 Record Added";
}
mysql_close($con)
?>
</body>
Have you tried if ($_SERVER['REQUEST_METHOD']=='POST')
updated answer:
if ($_SERVER['REQUEST_METHOD']=='POST') {
[insert...]
header('Location: added_record.php');
}
When you use the POST-method, it's better (imho) to use $_POST rather than $_REQUEST. To check whether you have data, you could use isset($_POST['txtFirstName']);. If you need all data, it's best to do this for all input fields, resulting in
if(isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtAge'])) {
// do stuff
}
If you want to know if there was any field submitted using post, you could use if(!empty($_POST)) {.
On a side note: I know you are just starting PHP, it could be quite dangerous to use user-generated code in queries. When you are building stuff online, for everyone to reach, please read a bit about SQL injection. This will also prevent your code from breaking when someone enters an apostrophe (').