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
}
}
Related
( Sorry for my bad english )
I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?
Existing Code :
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Seeing that your code is coming from a POST form, you can use a conditional statement around it.
For example, in your HTML form:
<input type="submit" name="submit" value="Submit" />
then use:
if(isset($_POST['submit'])){
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
}
another thing is to make sure that fields are not left empty, using empty() I.e.:
if(empty($_POST['username'])){
echo "Enter a username.";
exit;
}
also isset(). I.e.:
if(isset($_POST['username'])){
// do something
}
You can also use a header("Location: http://www.example.com/page.php");
but make sure there is nothing else above your PHP, echo, HTML, etc.
In regards to your present code:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.
I have written a PHP page with a form on the submit button I set the action to the PHP form page.
<form id="form1" method="post" action="../control_lbs/lbs_trace.php">
The INSERT INTO is basic sql load information to the database.
The problem i have every time I open the page it sends blank information to the rows. Is there away I can prevent this from happening?
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req,
lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES
('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]'
,'$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
The above is my PHP action code
This is the new code and full code I use
if ($con = mysql_connect($host, $username, $password)) {
if ( !empty($_POST["send"])) {
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES ('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]','$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
On refresh or page entry it still gives me blank info on Database
You need to use isset() to see if the $_POST variables are set. I've use $_POST in the example below, I suggest you give the submitbutton a name (like example) and use isset($_POST['example']):
if( isset($_POST) ){
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES(
'".$_POST['lbs_msisdn']."',
'".$_POST['lbs_req_by']."',
'".$_POST['lbs_date_req']."',
'".$_POST['lbs_reason']."',
'".$_POST['lbs_station']."',
'".$_POST['lbs_cas']."',
'".$_POST['lbs_traced_by']."'
)";
echo $sql; // echo it to see if it has any values
// print_r($_POST); // in case the query is still empty, uncomment this. It will show you the values in the POST array
}
I am trying to authenticate a login for my php/sql webpage.
The first code shows part of the Login.php where I take two text fields, email & password, and pass them to authenticate.php
The second code shows where I take the two values and try to process them.
The problem I have having is that I get directed to index.php everyime, even if I have the correct data entered in the field.
Any help would be appreciated.
Part of Login.php
<td width="70">Email</td>
<td width="6" align="center">:</td>
<form action="authenticate.php" method="post" name="authenticate_form">
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td width="70">Password</td>
<td width="6" align="center">:</td>
<td><input name="password" type="text" id="password"></td>
</tr>
<tr>
<td width="70">Login</td>
<td width="6" align="center">:</td>
<td>
<input type="submit" name="submit" value="Login" />
</form>
</td>
Authenticate.php
// ----------------------
// Retrieve login information
include("db_info.php");
// ----------------------
$conn = oci_connect($db_user, $db_pwd, '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=asuka.cs.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=asuka)))');
if (!$conn) {
$e = oci_error();
print_r($e);
exit();
}
// ----------------------
// Get POST values
if(isset($_POST['email']) && $_POST['email'] && isset($_POST['password']) && $_POST['password']) {
// Get posted form information and strip out unsafe characters
$email = htmlspecialchars(stripslashes($_POST['email']));
$password = htmlspecialchars(stripslashes($_POST['password']));
} else {
// Illegal access.
// Redirect back to index.php
header("location: index3.php");
exit();
}
// ----------------------
// Authenticate User
// Create query
$sql = "SELECT PASSWORD FROM CUSTOMER WHERE EMAIL = '$email'";
// Create database query statement
$statement_id = oci_parse($conn, $sql);
// Execute query statement
$result = oci_execute($statement_id, OCI_COMMIT_ON_SUCCESS);
$queryResult = oci_fetch_row($statement_id);
//var_dump($queryResult);
// Check for successful authentication
if($password == $queryResult[0]) {
if ($email=="admin#hotmail.com") {
$db_login_status = 2;
header("location: admin.php");
} else {
$db_login_status = 1;
header("location: normal.php");
}
} else {
header("location: fail.php");
}
// ----------------------
// Close connections
oci_free_statement($statement_id);
oci_close($conn);
$result is never assigned, therefore it never equals 1. The fix would be:
$result = oci_execute($statement_id, OCI_COMMIT_ON_SUCCESS);
// Check for successful authentication
if ($result) {
$result will be boolean, therefore you don't need to compare it with 1.
When $result returns false there is a function to see what went wrong. This function is oci_error(). Instead of redirecting you should print (or log) the error. This will aid you with debugging.
The problem could be that you don't have quotes around the parameters in you SQL query.
if ($email=="admin#hotmail.com") {
$db_login_status = 2;
header("location: index1.php");
} else {
$db_login_status = 1;
header("location: index.php");
}
If you are being sent to index.php, that must mean you are not logging in with "admin#hotmail.com". Try using that email address. Otherwise, try removing the code above and just leave these two lines:
$db_login_status = 1;
header("location: index.php");
The thing is that you're not getting redirected even though you entered the correct login, you are getting redirected because you did so. If you do not want to be redirected upon logging in, you will have to change your script to do whatever you are intending.
Edit: Based on your comment, it seems $email is empty. That would be because the <input name="email"> in your form is a hidden input which is not filled with anything when you type in your password. I was assuming that you had a javascript which imported the values from the visible text inputs in the other table cells. Do you? Otherwise, there's your problem. Your <form> tag needs to actually include the inputs which the login data gets entered into. You can solve the problem by wrapping the form around the whole login table.
Apart from that, your $result will always be 1 because the query succeeded, and not because it contained a result. After that, you additionally need to do $row = oci_fetch_row($statement_id);. Then check for if($row) rather than if($statement_id). Or simply if(oci_fetch_row($statement_id))
As a side note that turned out to be another problem: Don't forget to commit edits which you make to the database on an external editor. If they're not committed, other queries will not see them. In this case, the record for 'admin#hotmail.com' was added in an external program and not committed - so PHP refused to acknowledge the login.
if ($result==1) {}
$result is never assigned in the code!
Hi I encounter a problem with the foreach function in php... i used the function to input results of an array into the database. Forexample, If the Array (3,5,7), the system should input 3 different entries into the database. However, in my case, it only created 1 entry and totally ignored the other 2. May I know if anyone can spot my mistake?
i have created the a form with checkboxes and trying retrieve the value and give each value a individual array for example:
<form name="appoptions" id="applicationoptions" method="post" action="s_apply_now.php">
<table width="100%" class="apptable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input type="checkbox" name="cat[]" value="1" /> CAT 2PG</td>
<td><input type="checkbox" name="cat[]" value="2" /> CAT 1OR</td>
<td><input type="checkbox" name="cat[]" value="3" /> CAT 2TT</td>
</tr>
<tr>
<td><input type="checkbox" name="cat[]" value="4" /> CAT 3PG </td>
<td><input type="checkbox" name="cat[]" value="5" /> CAT 2OR</td>
<td><input type="checkbox" name="cat[]" value="6" /> CAT 3TT</td>
</tr>
<tr>
<td><input type="checkbox" name="cat[]" value="7" /> CAT 4PG</td>
<td><input type="checkbox" name="cat[]" value="8" /> CAT 3OR</td>
<td> </td>
</tr>
</table>
</form>
After clicking on confirm, it will then proceed to the processor page. In my processor page I tried to extract the value but i realise its in an array:
<?php
session_start();
include'Connections/database.php';
$conn = dbConnect ();
if (! $conn)
die("Couldn't connect to MySQL");
$user = $_SESSION['eid'];
$query = "select MED from emp where EID = '$user'";
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
$med = $row['MED'];
$user =$_SESSION['eid'];
$class=$_POST['class'];
$cat_arr=$_POST['cat'];
$i = 0; /* for illustrative purposes only */
foreach ($cat_arr as $cat)
{
if ($med=='no')
{
if (! $conn)
die("Couldn't connect to My SQL");
$query = "insert into permit (EID, PTYPE, STATUS) values ('$user,$cat, 'medical')";
$result = mysql_query($query,$conn);
header ('Location:medical_question.php');
$i++;
}
else
{
if (! $conn)
die("Couldn't connect to My SQL");
$query = "insert into permit (EID, PTYPE) values ('$user,$cat)";
$result = mysql_query($query,$conn);
$i++;
}
}
dbDisconnect($conn);
?>
I am not everysure if for each is the mistake but I think its around there...
Thanks in advance.
I see a few different things wrong with your PHP code:
You shouldn't connect/disconnect MySQL in your loop. This is unnecessary overhead. Instead, connect before your loop and disconnect afterwards.
You need to sanitize any user input before using it in a query. Your code is vulnerable to SQL injection.
You should also move your header('Location:medical_question.php'); line outside of your loop, and you should change it to die(header('Location:medical_question.php')); in order to stop the rest of your script from executing (assuming that's what you want to happen).
You need to fix the single-quotes in your queries:
insert into permit (EID, PTYPE, STATUS) values ('$user,$cat, 'medical')
should be:
insert into permit (EID, PTYPE, STATUS) values ('$user', '$cat', 'medical')
And the same thing for your other query.
In the end, your script will look more similar to this:
$conn = dbConnect();
if (!$conn)
die("Couldn't connect to MySQL");
$user = mysql_real_escape_string($_SESSION['eid']);
$class = $_POST['class'];
$cat_arr = $_POST['cat'];
foreach ($cat_arr as $cat)
{
$cat = mysql_real_escape_string($cat);
if ($med == 'no')
$query = "INSERT INTO permit (EID, PTYPE, STATUS) VALUES ('{$user}', '{$cat}', 'medical')";
else
$query = "INSERT INTO permit (EID, PTYPE) VALUES ('{$user}', '{$cat}')";
mysql_query($query);
}
dbDisconnect($conn);
if ($med == 'no')
$nextPage = "medical_question.php";
else
$nextPage = "next_page.php";
die(header("Location:{$nextPage}"));
SQL Injection example:
Suppose your query looks like this:
$user = $_GET["user"];
$cat = $_GET["cat"];
$query = "insert into permit (EID, PTYPE, STATUS) values ('$user', '$cat', 'medical')";
What would your query look like if I passed in a value like this for user:
`'); DROP TABLE permit; /*`
That would turn your query into this:
insert into permit (EID, PTYPE, STATUS) values (''); DROP TABLE permit; /*', 'cat', 'medical')
This is definitely not what you wanted to happen. When you sanitize the input using mysql_real_escape_string, it will escape the single-quote character and either the query will fail or the entire string will be inserted instead of being executed.
UPDATE:
The reason you want to move the header outside of the loop will be easier to understand if you know exactly what the function does:
When you call the PHP header function, you are telling PHP (on the server-side) to send a HTTP header to the browser (on the client-side). In the case of header('Location:...'), you are sending a HTTP header that causes the browser to redirect to a different page and disconnect from the current PHP script.
So this is the course of events that happens:
The PHP script sends the HTTP header, and depending on the latency, it can take some time for the browser to receive it.
The browser interprets the header and redirects to the location you specified, which also sends a disconnect message to the currently executing PHP script.
Again, depending on latency, it can take some time for the server to receive the disconnect message from the browser.
Between the time that the PHP script sends the header and then receives the disconnect message, the script is still executing. There is no way to tell how much code the script will execute before receiving the disconnect message, so you cannot rely on this at all. This is why you should die upon sending the header.
Knowing that this is how the PHP header function works, the only reason you would possibly want to put this inside the loop, is if you want the current script to stop execution in the middle of the loop depending on some certain condition. Like this:
foreach ($vars as $var)
{
if ($var == "stop")
die(header("Location:anotherPage.php"));
// do something as long as $var != "stop"
}
This will loop through the $var array until it comes to the value "stop", at which time it will send a redirect header to the client and stop execution.
The difference with your example is that (before you edited it) your loop contained a single if-else statement, and in both the if and in the else, you had the header-redirect call. So no matter what, it would be sent on the first iteration of the loop, which doesn't make sense. If this is truly what you wanted, you wouldn't be using a loop. It would only be executed once, which defeats the purpose of a loop.
Sorry for the long-winded response, but hopefully you now have a better understanding of what's really going on in your code.
It's only inserting once because after doing the first insert, you are redirecting to medical_question.php.
Move this redirect to outside of the foreach:
header ('Location:medical_question.php');
Also, you might as well move the db connect to before the foreach too.
strings are marked by '$string' (apostrophe) into a sql query
$query = "insert into permit (EID, PTYPE) values ('$user','$cat')";
you can initialize just one db object ($db) with proper connection, and use it where you want: see http://php.net/manuel/en/ref.mysql.php
Eg:
$conn = new mysqli('localhost', 'root', 'pass', 'db');
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
$sql = "INSERT INTO `table` (`id`, `val`) VALUES (1, 'peace'), (2, 'love')";
if ($conn->query($sql) === TRUE) {
echo 'Done';
}
else {
echo 'Error: '. $conn->error;
}
$conn->close();
This is just a raw example.
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.