After browsing google for a few hours, I managed to splice together some code up, and it looks like it's working for the most part. Unfortunately, I'm getting an SQL error when I submit my form.
What I'm trying to do: When someone fills out the form on my website, a specific function is applied based on which radio button is pressed in the form. I want to store the data in a database, but I also want to store the IP address of the individual submitting.
All I request of this wonderful community is an explanation of why this isn't functioning as I thought it should, and a quick lesson on how to prevent this from happening again.
Here is the code for my form:
<html>
<head>
<link rel="stylesheet" type="text/css" href="/style.css">
<title>
Learning Made Easy
</title>
</head>
<body>
<?php include_once 'googleanalytics.php'; ?>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<div class="content">
</br>
</br>
</br>
<form action="../scripts/switch.php" method="post">
Title:
</br><input type="text" name="Title">
</br>
</br>
</br>
Summary of the video (including questions used in the video):
</br><textarea name="Summary" COLS=60 ROWS=10></textarea>
</br>
</br>
</br>
URL of the video (Yes, this means you need to upload it to an external website.):
</br><input type="text" name="URL">
</br>
</br>
Which course does your video pertain to?</br>
<input type="radio" name="course" value="intermediate"> Intermediate and below</br>
<input type="radio" name="course" value="college"> College Algebra</br>
<input type="radio" name="course" value="precalculus"> PreCalculus</br>
<input type="radio" name="course" value="trigonometry"> Trigonometry</br>
<input type="radio" name="course" value="calculus I"> Calculus I</br>
<input type="radio" name="course" value="calculus II"> Calculus II</br>
<input type="radio" name="course" value="calculus III"> Calculus III</br>
<input type="radio" name="course" value="differential equations"> Differential Equations</br>
</br>
The function triggered is used to pick the correct function based on the radio button selected. For the sake of space I won't include it, and will skip right to the code that it redirects to. This is where (I suspect) my error is, and I'm unfortunately not well versed enough to solve this error alone.
Code of the function AFTER switch.php (this is where I define the IP variable):
<?php
// Create connection
$con=mysqli_connect("********","*****","*****","****");
$IP = $_Server['REMOTE_ADDR'];
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Intermediate Algebra ('Title', 'URL', 'IP', 'Summary')
VALUES
('$_POST[Title]','$_POST[URL]','[$IP]','$_POST[Summary]'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Your video has been successfully submitted. Thank you for your contribution to TerryTheTutor.com";
header('Location:http://terrythetutor.com');
?>
</br>
<input type="submit" value="Submit, foo!">
</form>
</br>
</br>
</br>
<p>
Please understand that you will not be able to change the title, summary, or URL of your video after submission.
</p>
</div>
<div class="footer">
<?php include 'footer.php'; ?>
</div>
</body>
</html>
I believe that the error has originated with the $IP variable. I've tried to add quotes, scanned the code countless times and still am unsure of what the error is.
Here is what the error I'm getting when I submit looks like:
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 'Algebra ('Title', 'URL', 'IP', 'Summary') VALUES ('Title Test','Url test','[]',' at line 1
As a courtesy, if someone could show me how to properly "sanitize" this data input, that would be wonderful.
Thank you, guys!
table names and column names are identifiers. they are not string literals so they should not be wrap with single quote. So you need to remove it eg
INSERT INTO `Intermediate Algebra` (Title, URL, IP, Summary) VALUES(....)
If it happens that the names contains spaces or a reserved keyword, it should be wrap with backticks. eg
INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`) VALUES(...)
Additional Info
MySQL Reserved Keywords List
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
You can try this, this will help you to run your script successfully without any error.
$sql="INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`)
VALUES ('".$_POST[Title]."','".$_POST[URL]."','".$IP."','".$_POST[Summary]."')";
You have more than one error here:
PHP variable names are case sensitive. This means you have an error in this line of code:
$IP = $_Server['REMOTE_ADDR'];
Thus, $IP is always empty.
Instead, this should be:
$IP = $_SERVER['REMOTE_ADDR'];
In your SQL statement, table names with spaces need to be backquoted. It's also a very good idea to do the same with your field names, to avoid conflicts with MySQL keywords:
$sql="INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`) VALUES(...)";
Finally, your SQL statement is vulnerable to SQL injection and needs to be completely rewritten and replaced with a prepared statement.
You need to close bracket ),
('$_POST[Title]','$_POST[URL]','$IP','$_POST[Summary]')";
SQL:
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$URL = mysqli_real_escape_string($con, $_POST['URL']);
$IP = $_SERVER['REMOTE_ADDR'];
$IP = mysqli_real_escape_string($con, $IP);
$Summary = mysqli_real_escape_string($con, $_POST['Summary']);
$sql="INSERT INTO Intermediate Algebra ('Title', 'URL', 'IP', 'Summary')
VALUES
('$Title','$URL','$IP','$Summary')";
Related
I am working on a school project and can't get registration page done right. It just doesn't insert the data in table.
Here is a screenshot for database and table
I have added the HTML, and after going through all your answers I think I am using outdated videos and study material to learn (PHP, HTML, CSS, Website Security).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
</head>
<body>
<div class="form">
<h2>Registeration</h2>
<form action="" method="post">
Name<input type="text" name="name" placeholder="First & Last name" required><br><br>
Username<input type="text" name="username" placeholder="Username"required><br><br>
Password<input type="password" name="password" placeholder="Keep it Strong"required><br><br>
Confirm Password<input type="password" name="confirm-pass" placeholder="Re-Enter Password"required><br><br>
Email<input type="email" name="email" placeholder="Email"required><br><br>
Phone No.<input type="text" name="phone-no" placeholder="Phone No"required><br><br>
Gender<input type="text" name="gender" placeholder="Male or Female"required><br><br>
State<input type="text" name="state" placeholder="State"required><br><br>
<button type="submit" name="home">Home</button>
<button type="submit" name="sub">Submit</button>
<button type="submit" name="reset">Reset</button>
</form>
</div>
</body>
</html>
<?php
$con=mysqli_connect('localhost','root','123456789','eedb');
if ($con)
{
if (isset($_POST['sub']))
{
$n= $_POST['name'];
$un=$_POST['username'];
$p=$_POST['password'];
$cp=$_POST['confirm-pass'];
$e=$_POST['email'];
$pn=$_POST['phone-no'];
$g=$_POST['gender'];
$s=$_POST['state'];
mysqli_query($con,"SELECT * FROM `register`");
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`) VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
if ($insert)
{
echo "<center>Data Successfully Submitted</center>";
}
else
{
echo "<center>Data Not Submitted</center>";
}
}
}
else
{
echo "<center>Oh!no there is an error.<br><br>But don't worry we have an army of trained chimpanzies to deal with it.<br><br> <image src='images/chimps.jpg'><br><br>Come Back Soon</center>";
}
if (isset($_POST['home']))
{
header("location:index.php");
}
if (isset($_POST['reset']))
{
header("location:register.php");
}
?>
Since you didn't post your HTML form, I am posting the following answer, which is what your HTML form should (basically) look like, which btw only contains the one example element.
You will need to fill in the rest and follow the same convention.
<form method="post" action="handler.php">
First name:
<input type="text" name="name">
<br>
<input type="submit" name="sub" value="Submit">
</form>
Then escape your values, should there contain any characters that MySQL may complain about, such as apostrophes.
I.e.: Doug's Bar & Grill.
Then:
$n= mysqli_real_escape_string($con, $_POST['name']);
Something you should use or a prepared statement since your code is presently open to an SQL injection.
Ref: How can I prevent SQL injection in PHP?
And do the same for all your other POST arrays.
The name attribute is required for POST arrays when using pure PHP and a post method for the HTML form.
Sidenote: Your entire code is dependant on the following conditional statement
if (isset($_POST['sub'])){...}. So make sure that that form element bears the same name attribute for it.
Check for errors also.
Since this does not help you:
echo "<center>Data Not Submitted</center>";
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
It's unclear as to what you're trying to do with this line:
mysqli_query($con,"SELECT * FROM `register` ");
If the goal is to check if a row exists, then consult one of my answers on Stack:
check if row exists with mysql
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Other links of interest:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PBKDF2 For PHP
HTML stickler:
The <center> tag is deprecated and has been removed from Web standards.
For more information, visit the following:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center
you can try this
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`)VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
you can try to use notepad++ or any other editor (e.g netbeans )that will make the open and closed brackets more obvious .
Well I am pretty much trying to create database with some table, the values in the table and check them in phpMyAdmin. I am able to create the table and database, but not the values
2.) when I add the isset $_post['submit'] variable, when I click the submit button, nothing is getting created. Is there a syntax error I am not seeing?
<html>
<body>
<p> welcome to my Page
Please insert the data below
<br>
<br>
<form action="input.php" method="post">
<p> Name: <input type="text" name="name">
<p> Age: <input type="text" name="age">
<p> Address: <input type="text" name="address">
<p> Email: <input type="text" name="email">
<input type="submit" value="Send!" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
//connects to the sql database
$con = mysql_connect("localhost", "willc86", "tigers330");
if (!$con) {
echo 'can not connect to Database' . "<br>";
}
//creates the database in mySQL
$db = mysql_query("CREATE DATABASE form");
if (!$db) {
echo 'Did not create database';
}
//select the database and connect to it. on where you want to create tables.
mysql_select_db("form", $con);
//create the table once "form database" is selected
$table = "CREATE TABLE users (
Name varchar(30),
Age varchar(30),
Address varchar(30),
Email varchar(30)
)";
mysql_query($table,$con);
//insert the data from the form
$value= "INSERT INTO users (Name, Age, Address, Email)
VALUES ('$_POST[name]','$_POST[age]','$_POST[address]','$_POST[email]')";
mysql_query($value,$con);
mysql_close();
}//end of submit
?>
</body>
</html>
Your form action is input.php, is your file called input.php as well? Otherwise you'd be executing input.php when you're submitting the form instead of executing the PHP on your page.
I think user willc86 don't have access rights for create databases.
In second your script is incorrect, because it run for each "user add" operation and tried create database and table.
You can create it once in phpadmin and use in your script only insert.
No point in highlighting particular errors here as others are unlikely to have the exact same issue. Better to just give you the tools/means to debug the issue for yourself.
Instead of:
mysql_query($table,$con);
Try:
$res = mysql_query($table,$con);
if($res === false){
throw new Exception(mysql_error($conn));
}
Better yet, use PDO.
First of all your code is fine if this file name is input.php. There can be few reasons, one that you have incorrect credentials second that the user does not have a right to create table, for that go to Phpmyadmin and give user all rights.
Secondly and most importantly, use Prepared statements or mysqli otherwise you are vulnerable to SQL Injection
For that do go through this post
How can I prevent SQL injection in PHP?
I'm making a storage log for work, and I've been fighting with this code for the last two hours with no success. For some reason, no matter how many times I check and recheck the code for my INSERT INTO query, it will not work.
Keep in mind that I copied this code, almost verbatim (changed the form names and fields, obviously) from another page that has basically the same functionality and works 100%. Code below:
This is the page containing the form where the transaction is being submitted:
<?php
$script = '<script>
$(document).ready(function(){
$(".datepicker").datepicker();
}); </script>' ;
$title = "View/Edit Storage - " ;
include('inc/header.php');
?>
<table>
<tr>
<form action="transadded.php" name='addnewtransaction' method="POST">
<td><input type="text" name="moveID" size="20" value="<?php echo $results[moveid]; ?>" readonly> </td>
<td><select id="inoutselect" name="inorout">
<option value="Select">Select</option>
<option value="Storage In">Storage In</option>
<option value="Storage Out">Storage Out</option>
</select> </td>
<td><input type="text" name="numberofunits" size="20"></td>
<td><input type="text" name="dateoftransaction" size="20" class="datepicker"></td>
<td><input type="text" name="rrdt" size="20"> </td>
<td><input type="submit" value="Add" id="logsubmit"></td>
</form>
</table>
<br /><br />
<?php };?>
Here's the query itself, aka "transadded.php":
<?php
$title = "Project Added - ";
include('inc/header.php');
$query = "INSERT INTO newtransaction (moveid, inout, units, transdate, refno) VALUES('$_POST[moveID]','$_POST[inorout]','$_POST[numberofunits]','$_POST[dateoftransaction]','$_POST[rrdt]')";
if(!mysqli_query($con,$query))
{
die ('Error: ' . mysqli_error($con));
}
echo '<div class="transstatus">' . '1 record added' . '</div>';
mysqli_close($con);
?>
The header, obviously, contains the function for connecting to the database, and as I said, another query works just fine with it, so I know that that isn't the problem. Upon clicking the submit button, the error I get on the page is as follows:
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 'inout, units, transdate, refno) VALUES ('1234567','Storage In','81','09/11/2013'' at line 1
Here, "1234567", "Storage In", etc are the values I enter into the form.
I hope you can help me out. I'm so stuck!
Also, I know that I'm not protected against injection right now. I plan to work on that later, but I'm trying to get the functionality straightened out first.
INOUT is a MySQL reserved word.
See here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Change the name or put it in quotes.
Use the following:
$query = "INSERT INTO newtransaction (
`moveid`, `inout`, `units`, `transdate`, `refno`
)
VALUES(
'{$_POST[moveID]}', '{$_POST[inorout]}',
'{$_POST[numberofunits]}', '{$_POST[dateoftransaction]}',
'{$_POST[rrdt]}'
)
";
$query = "INSERT INTO newtransaction (moveid, inout, units, transdate, refno)
VALUES
( '".$_POST['moveID']."','".$_POST['inorout']."','".$_POST['numberofunits']."',
'".$_POST['dateoftransaction']."','".$_POST['rrdt']."')";
you post your like ='$_POST[dateoftransaction]'
right procedure is if you using wamp= '".$_POST['dateoftransaction']."'
i hope you got your mistake
Ferrakkem
I'm designing a crud app to store storage data in a database. Using php, mySQL (with the help of XAMPP). I keep running into this problem, though, where I click "Submit" on my form and the function appears to run successfully (I get a the success message on the php page), but when I look at the actual database, the row fills 3 of the fields (the first 1 and the last 2) with just "0" regardless of what's in the form when I click submit. And then the other two columns don't have anything in them at all.
Here's my code for the form:
<div id="newprojform">
<fieldset><legend>Create New Project</legend>
<form action='projectadded.php' name="addnewproject" onsubmit="return(validate());">
<div id="newprojfields"><br />
Project Name:
<div class="field">
<input type="text" name="projname" size="50">
</div>
<br /><br />
Customer:
<div class="field">
<input type="text" name="custname" size="50">
</div>
<br /> <br />
Move ID:
<div class="field">
<input type ="text" name="moveID" size="50">
</div>
<br /><br />
<label for="unit">Unit of Measurement: </label>
<div class="field" id="uomdd">
<select id="unit" name="unit">
<option value="Select">Select</option>
<option value="CWT">CWT</option>
<option value="Vault">Vault</option>
<option value="SqFt">SqFt</option>
<option value="Pallet">Pallet</option>
<option value="Piececount">Piece Count</option>
</select>
</div>
<br /><br />
Cost Per Unit:
<div class="field">
<input type="text" name="cost" size="50">
</div>
<br /> <br />
<input type="submit" value="Add Project" id="submit"><br />
</div>
</form></fieldset>
</div>
And here's the php
<?php
$con=mysqli_connect("localhost","root","", "storagelog");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO newproject (moveid, projectname, customername, UoM, PPU)
VALUES
('$_POST[moveID]','$_POST[projname]','$_POST[custname]','$_POST[unit]','$_POST[cost]')";
if(!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Can anybody please tell me what I'm doing wrong? I've gone over the syntax and names of the forms a million times, but every time I click "submit," I just get a row that either has zeros in it or nothing at all. This is all very new to me, so i'm expecting a lot of stupid or clunky mistakes, but this is the first time I'v ever been so stuck..
any help is appreciated.
The problem is that you aren't specifying POST as the method in your form, but you are trying to read the form variables from the $_POST variable. See this thread: What is the default form HTTP method? for information about the form defaults. To fix it, you just need to change your form to this:
<form action='projectadded.php' name="addnewproject" onsubmit="return(validate());" method="POST">
There are some other things you should change in here, like sanitizing your inputs before putting them into the database, but those aren't the root of your problem.
So first things first. I don't recommend using unfiltered $_POST and $_GET variables when dealing with the database (in a production setting of course).
Second, when using the form element, you have to specify whether you're using a post method, or a get method:
<form action="location_of_file.php" method="POST">
Also, make sure you check that your column names in the table absolutely match the names in your sql insert syntax.
Maybe even try the following to see if it inserts:
$sql="INSERT INTO newproject (`moveid`, `projectname`, `customername`, `UoM`, `PPU`)
VALUES ('" . $_POST["moveID"] . "','" . $_POST["projname"] . "','" . $_POST["custname"] . "','" . $_POST["unit"] . "','" . $_POST["cost"] . "')";
Sometimes, SQL can be touchy.
Lol, dang... seanmk beat me to the punch. If what we suggest works, choose his answer as he was first to post it.
For future reference (aside from the excellent advice in the other answers) you should consider printing out $sql to see what your actual insert statement looks like. You'd see immediately that your values are empty strings and would know to go chase after the $_POST to see why it's arriving empty.
having a bit of trouble adding some data to a database. I have the file new_entry.php which is a form, which posts the data added to insert_new.php.
Every time the fields are filled in and submitted the data does not go to the database with the error message "Could not add the data to table" appearing..any ideas?
NEW_ENTRY.PHP
<body>
<form method="post" action="insert_new.php"><!-- form sent to insert_new.php-->
Section: <input type="text" name="section"/><br />
Food: <input type="text" name="food"/><br />
Description: <input type="text" name="description"/><br />
Price: <input type="text" name="price"/><br />
<br />
<input type="submit" value="submit"/>
</form>
</body>
INSERT_NEW.PHP
<?php
include 'library/connect.php';//connect to databse
$section = $_REQUEST["section"]; // get data from the HTML form on new student form
$food = $_REQUEST["food"];
$description = $_REQUEST["description"];
$price = $_REQUEST["price"];
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', $price)")/* insert the data to the food_menu table*/
or die ("Could not add the data to table");//error message
header('Location:index.php');//auto redirect to view page
include 'library/closedb.php';
?>
It seems that you have a mistake at the end of your MySQL query near price.
Please replace the code below with existing line:
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', '$price')")
Tell me the result please.
First: Don't do this. You really need to research SQL Injection or you will be very sorry.
Secondly, your price has no numeric validation (assuming it's going into a numeric column)... this is also bad... what if someone put in a dollar sign or something?
Next, please post your table definition and connection code (not the connection values).
You can also get more feedback if you do something like:
or die (mysql_error());//error message