PHP/html email form no longer submitting to mysql database - php

I created this form:
<form method="post" action="process-form.php" id="emailForm" name="emailForm" target="_self">
<h4>Sign up to be notified when we go live!</h4>
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
<input type="submit" name="submit" id="submit" value="Submit" onclick="return alert('Thanks! Your email has been added.');">
<p>emails will not be shared with third parties</p>
</form>
With this php code
<?php
//open database connect
$username = "username";
$password = "password";
$hostname = "server";
$conn = mysql_connect($hostname, $username, $password);
if (!$conn) die('Could not connect: ' . mysql_error());
//emaillist is the name of the database
mysql_select_db('emaillist');
//Clean data
function clean_data($string){
if (get_magic_quotes_gpc()){
$string = stripslashes($string);
}
$string = strip_tags($string);
return mysql_real_escape_string($string);
}
//Mail Header removal
function remove_headers($string){
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i",
);
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}
//Pick up cleaned data
$email = clean_data($_POST['email']);
//Insert data
//emails is the name of the table
$query ="INSERT INTO emails (email)
VALUES ('$email')";
mysql_query($query);
//close Connection
mysql_close($conn);
//redirect to page
header('Location: defaultUpCyc.html');
?>
Everything was working fine and dandy in my testing environment and for a couple of days when I put it live. However, I went to my database to see if any emails were submitted and its totally empty. I have put test emails into the form and checked the db and there is nothing. I haven't changed a thing since I put it live so I'm at a loss. Here is the test site: http://upcycledonline.com/test/Site/defaultUpCyc.html
Thanks for the help!

you should check to see if your connection works by adding:
if (!$conn) { die('Could not connect: ' . mysql_error()); }
also check firebug to make sure the form posts with the data. you could also echo out your query to check the format. everything looks good otherwise, so my assumption is the db connection is bad.
just a guess though :)

The form tag on your test site doesn't have its action defined which means it's sending the data to itself and HTML can't work with databases.

i dont know how to add code here so i made a paste:
http://pastebin.com/baPUPhbt
you may use this

i think your problem is at that onclick javascript, try to remove it, it may work

Related

PHP/MYSQL Insert is doing nothing

I have a simple form set up in HTML to pass values to PHP and put them in a MYSQL database. I just can't fathom why nothing is happening when I click the submit button. Previously it was saying 'failed' but now nothing. I have checked the values from the form - fine. I've checked the database connection - fine. I've checked the SQL statement - well, I can't see any errors.
This is my main HTML page
<p class="subtitle">Let me know what you think</p>
<form action="db_insert.php">
<input name="username" placeholder="Name">
<br>
<textarea name="comments" placeholder="Please type your comments here"
cols=120 rows=5></textarea>
<br>
<input type="button" name="submit" value="submit">
<br>
<p id="commTitle">Comments</p>
<br>
<p id="comment"></p>
This is the PHP
<?php
include 'db_connection.php';
//create database connection
$conn = OpenCon();
$username = htmlspecialchars($_POST['username']);
$comment = htmlspecialchars($_POST['comment']);
$sql = 'INSERT INTO sitecomments(username, comment) VALUES(:username,:comment)';
$stmt = $conn -> prepare($sql);
$stmt -> bindValue(':username', $username);
$stmt -> bindValue(':comment', $comment);
$q_result = $stmt -> execute();
if($q_result){
echo 'Comment Inserted Successfully';
}
else{
echo 'Failed';
}
db_connection.php looks like this (with credentials removed.
<?php
function OpenCon(){
//pass the database details to variables
$host = "localhost";
$dbuser = "*****";
$dbpass = "*****";
$dbname = "*****";
// combine host and db name in to single variable
$dbhost = "mysql:host=$host;dbname=$dbname";
//create PDO from database information
$dbconn = new PDO($dbhost, $dbuser, $dbpass);
return $dbconn;
}
?>
As I said, I've checked the database connection and all is fine so where on earth am I going wrong? My database has 3 fields but one is autoincremented so I haven't included it in the query. I tried the query in MyPHPAdmin and it passed ok.
The first thing I notice is that the input has name of "comments" rather than the $_POST variable you're accessing called comment:
<textarea name="comments" placeholder="Please type your comments here" cols=120 rows=5></textarea>
$comment = htmlspecialchars($_POST['comment']);
Try changing that and see if it fixes the issue.
It would be helpful to handle errors within your code. In your current example if something goes wrong you will have a hard time finding out where the problem is.
You can try all of the following examples from the PHP Docs on PDO error handling and PDO::errorInfo:
Assert your connection is valid:
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
Assert your SQL is valid
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
As usual the error is a pebcak error, and you need to utilize proper debugging tools to find out where your mistakes are. Good luck!

Validating using JQuery and processing by PHP

I want to validate my form using JQuery and use php to send it to my database.
This is what I've tried:
<body>
<form id="first_form" method="post" action="">
<div>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"></input>
</div>
<div>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name"></input>
</div>
<div>
<label for="handphone">Handphone:</label>
<input type="text" id="handphone" name="handphone"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
<script>
$(document).ready(function() {
$('#first_form').submit(function(e) {
e.preventDefault();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var handphone = $('#handphone').val();
$(".error").remove();
if (first_name.length < 1) {
$('#first_name').after('<span class="error">This field is required</span>');
return false;
}
if (last_name.length < 1) {
$('#last_name').after('<span class="error">This field is required</span>');
return false;
}
if (handphone.length < 1) {
$('#handphone').after('<span class="error">This field is required</span>');
return false;
}
});
});
</script>
<?php
$first_name = "<script>var first_name = $('#first_name').val();</script>";
$last_name = "<script>var first_name = $('#last_name').val();</script>";
$handphone = "<script>var first_name = $('#handphone').val();</script>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO vali (first_name, last_name, handphone)
VALUES (first_name, last_name, handphone)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
So as you can see, the first part is just the html and form.
The second part is where I used Jquery to validate (which works).
Now the issue is at the php part, where it sends the data to my database as empty.
The logic behind my php code is that, I take the values of the variables I set in Jquery and just update it to the database. But its updating empty values.
I tried to return false in Jquery, but its not working for me. May I know what am I doing wrong here?
Firsty, you have to understand JavaScript in this case is a client-scripting language and PHP is a server-scripting language. Variables can't be pass from JavaScript to PHP is the <script> tag.
Secondly, we have different types of requests; GET, POST, PUT, DELETE and so on. This we can check via PHP. A form can only send two types of request as at the time of me typing this answer, GET and POST request, this is the method value you set in your form. Every value set in a form can be accessed in the request global array and the name of the value being the key/indetifier. $_GET[] if you sent a get request and $_POST[] if you sent a post request.
In your form above, your method is set to POST, meaning all the values would be available in the global $_POST[].
When ever a page loads, the server script gets loaded first before the Client Side / HTML / CSS and other resources used by your document.
PHP has a function called isset() which is used to check if a variable available regardless it's value which is very useful for form validation.
If you ever have PHP codes in file performing logic/operations, it is advisable you placed them topmost of you file since it isn't used in rendering your document/view.
From your code, you should edit as
<?php
if(isset($_POST['submit'])){
// This block will only be executed when a submit button is triggered
//Make your connection here, it is not a must but good practice to always make connection first in order to make it available everywhere. Ensure to check if connection was successful or not.
$first_name = $_POST['first_name']; // this gives you the exact value you passed in the form.
...
// All you variables should be assigned using the above method
//in the above assignation of variables, we didn't sanitize. mysqli has a method real_escape_string() which does that for us. Ensure to always sanitize and properly validate inputs you send to your DB
//Sanitizing inputs
$first_name = $con ->real_escape_string($first_name);
// Do the above for other inputs, then you are good to perform an insert.
$result = $conn->query($sql);
if($result){
//Record has been inserted, you can choose to redirect or do some other logic
}else{
//Record was not successfully inserted. Print your error if in development to get an insight to what went wrong
}
}
$conn->close()
?>

Fix blank database entries on page load?

I have a form on an HTML webpage that sends a user's comment and name to a MySQL database table, where it is stored, and then included back onto the page. The problem is, if the user's name has an apostrophe in it, the server (I pay for hosting, it's not my server and I can't change the configuration on it) is sending them to a error page that says:
"The requested URL was rejected. If you think this is an error, please contact the webmaster.
Your support ID is: 13509873612934211694"
UPDATE:
I just completely rewrote the page using a different php format. Now the apostrophe issue and the server error is fixed. However, the page is sending blank entries to the database on every page load. Any ideas?
<?php
$servername = "my_server";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
$users_request = $_POST['requests'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("INSERT INTO submissions (requests, name)
VALUES ('$users_request', '$users_name')");
$conn->commit();
header("Location: clv3.php");
}
catch(PDOException $e)
{
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="POST" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Make A Request:<br>
<textarea name='requests' id='requests'></textarea> <br>
Your Name (a-z only):<br>
<input type='text' name='name' id='name'/><br>
<input type='submit' value='Send' class='button'>
</form>
Ever heard of SQL injection? This is one you create...
Always escape your data! You are now pushing data given by user directly into database.
$name = mysqli_real_escape_string($conn, $_POST['name']);
$comments = mysqli_real_escape_string($conn, $_POST['comments']);
Also you can encode special chars before insert, and decode when showing
Did you perhaps try:
encodeURI(yourString)
Then on php side you do:
url_decode($_POST['myVariable'])

HTML Form Not Submitting to MYSQL Database

I have been trying to get this to work for some hours. I have researched many threads on here trying to see if I could find the problem with my code. I am new to PHP and I keep getting a Internal Server error, but I cant seem to track it down. I have tried all sorts of methods suggested online to get this to work with no luck. Its a basic user signup form in HTML, in a PHP file.(I was going to do both html and php on the same file but could not get that to work) The idea is to have the form submit to my MYSQL database to a customer table. If any of you could shed some light on what I am doing wrong or point me in the right direction, it would be much appreciated. Thanks in advance.
HTML
<form id="signupField" action="register.php" method="post">
First Name:<br>
<input type="text" name="FN" size="auto"/><br>
Last Name:<br>
<input type="text" name="LN" size="auto"/><br>
Street Address:<br>
<input type="text" name="SA" size="auto"/><br>
City:<br>
<input type="text" name="City" size="auto"/><br>
State:<br>
<input type="text" name="ST" size="auto"/><br>
Zip:<br>
<input type="text" name="Zip" size="auto"/><br>
Email Address:<br>
<input type="text" name="Email" size="auto"/><br>
Password:<br>
<input type="text" name="Password" size="auto"/><br>
<input type="submit" value="submit" name="submit"/>
</form>
Referenced PHP:
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<?php
$FName=$_POST["FN"];
$LName=$_POST["LN"];
$SA=$_POST["SA"];
$City=$_POST["City"];
$State=$_POST["ST"];
$Zip=$_POST["Zip"];
$Email=$_POST["Email"];
$Password=$_POST["Password"];
if (isset($_POST["submit"])) {
$sql = "INSERT INTO Customers(FName,LName,StreetAddress,City,State,Zip,Email,Password) VALUES('$_POST["FN"]','$_POST["LN"]','$_POST["SA"]','$_POST["City"]','$_POST["ST"]','$_POST["Zip"]','$_POST["Email"]','$_POST["Password"]')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
}
?>
EDIT After finding this error: Connection failed: Unknown MySQL server host 'localhost:3306' (0) I was able to solve the connection issue to the database. Now when I put in the rest of the PHP back in I get a 500 Error still. It definitely narrows down where the issue is though!
EDIT I want to thank you all for you help on here. The main issue was the SQL connection. After I got that taken care of, I found that I had an extra bracket in place which was the cause for the other internal error I was receiving.
First, the "basic check" question: the html with the form and register.php are in the same directory, right? Not includes, requires, etc
If you have access to the apache error_log, check it out first to see the error message you're getting. If you can't understand it, post it here to help you.
If you don't have acccess to the file, first we need to find where are you getting the mistake. As an idea, start with this in register.php...
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Got to http://[yourdirectory]/register.php DIRECTLY and see what you get. Then start adding the rest step by step and let us know when you get the mistake.
Other think to check is the database NULL variables configuration. All the columns allow null values? Are you filling all form fields or are you leaving any field empty?
Replace your register.php code with following.
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
if it prints that connection failed; then you have to check your code for connecting to database.
Use isset($_POST["FN"]) .. etc for all post variables and try to use variables $FName , $LName etc. in your insert query instead of direct $_POST variables.
e.g.
$FName = '';
if(isset($_POST["FN"]) && $_POST["FN"] !=''){
$FName = $_POST["FN"];
}
Also check whether connection is opening or failing.
before insert any new field into your db use
mysql_real_escape_string
check for empty params before insert these to db
use the following to turn all error reporting on for MySQLi
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You should use your variables that you assigned for your post fields instead of the $_POST-objects and make sure you sanitize all user inputs.
You could try replacing your $sql-string with the following:
$sql = "INSERT INTO Customers(FName,LName,StreetAddress,City,State,Zip,Email,Password) VALUES('$FName','$LName','$SA','$City','$State','$Zip','$Email','$Password')";

php database connection/selection

I have a login.html in which the form is defined as follows:
<form method="post" action= "do_authorize.php" name="lform">
<span class="style1">First Initial Plus Last Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
My do_authorize is as follows:
<?php
session_start();
require('../databaseConnectionFileFolder/dbconnection.php');
$user = $_POST["user"];
var_dump($user);
$_SESSION['username']=$user;
var_dump($user);
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
var_dump($sql);
$result=#mysql_query($sql,$connection) or die("couldn't execute query");
$num=mysql_numrows($result);
if ($num != 0) {
/*$cookie_name="$user";
$cookie_value="ok";
$cookie_expire=time()+86400;
$cookie_domain=".columbia.edu";
setcookie($cookie_name, $cookie_value, $cookie_expire, "/", $cookie_domain, 0);
*/
print "<script>";
print "self.location='somethingelse.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
My dbconnection.php file is as follows:
<?php
$db_server = "localhost";
$db_name = "DailyExerciseDB";
$db_user = "abc5"; //the database username
//$db_password = "123"; // the database user pasword
$connection=#mysql_connect($db_server,$db_user) or die("Could Not Connect to the Database : ". mysql_error());
var_dump($connection);
$db=#mysql_select_db($db_name, $connection) or die("Could Not Select the Database". mysqli_connect_error());
//var_dump($db);
?>
My Questions:
1) I keep on getting Could Not Select the Database, why does the warning/error message corresponding to . mysqli_connect_error() doesn't get printed on the browser?
2) I have manually entered the user with username abc5 in the database and still it's not able to connect.Does anyone know why?
3) Even if I don't enter anything in the login.html and press login button, the following files gets executed, how can I take user entered into account while verifying with database? I believe since its hardcoded right now abc5, all files are getting executed.
4) var_dump($connection); prints resource(4, mysql link)
mysql_connect() has a third parameter which I'm not seeing you use: the password. Consider the following line:
mysql_connect($db_server, $db_username, $db_password);
Also, you should probably be using mysqli extension instead of the mysql extension (mysql is deprecated in PHP 5.5.0).
I also see you're mixing the mysql and mysqli functions in your code. This is the reason why mysqli_connect_error() shows nothing.

Categories