HTML Form Not Submitting to MYSQL Database - php

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')";

Related

PHP variable wont show in form input field

I'm trying to select a PHP variable from a database insert it into an html form input. I guess my question is how do you store the query into a variable and then call that variable in an html form? Also, the form is located on a separate page from the form action file. Why is it undefined if it's defined in the PHP file? The desired output is when I load the html page the value from the database for nickname auto-fills that field of the form.
error:
Notice: Undefined variable: Nickname in C:\xampp\htdocs\Client-Projects\Crossfire\templates\CoinSubmission.html on line 45
CoinSubmission.html
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($Nickname); ?>" />
</p>
</form>
AdminCoinSub_Code.php
<?php {
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "administrator_logins";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO coin (ProfileID, Store, Position,
Nickname, ContactNumber, MachineCount, CutOffDate, Coins, location, LastSubmission, Rank)
VALUES (:ProfileID, :Store,:Position, :Nickname,:ContactNumber,:MachineCount,:CutOffDate, :Coins,:location,:LastSubmission,:Rank)");
$stmt->bindParam(':ProfileID', $_POST['ProfileID']);
$stmt->bindParam(':Store', $_POST['Store']);
$stmt->bindParam(':Position', $_POST['Position']);
$stmt->bindParam(':Nickname', $_POST['Nickname']);
$stmt->bindParam(':ContactNumber', $_POST['ContactNumber']);
$stmt->bindParam(':MachineCount', $_POST['MachineCount']);
$stmt->bindParam(':CutOffDate', $_POST['CutOffDate']);
$stmt->bindParam(':Coins', $_POST['Coins']);
$stmt->bindParam(':location', $_POST['location']);
$stmt->bindParam(':LastSubmission', $_POST['LastSubmission']);
$stmt->bindParam(':Rank', $_POST['Rank']);
$stmt->execute();
echo "Success";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
}
$conn=mysqli_connect($servername,$username,$password,$dbname);
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT `Nickname` FROM `adminlogin` WHERE `ProfileID` = ':ProfileID'";
$Nickname = $conn->query($query); // This is where the query is executed
$fetcher = $Nickname->fetch_assoc();
while($row = mysqli_fetch_array($Nickname))
if (mysqli_num_rows($Nickname) > 0) {
echo 'User name exists in the table.';
} else {
echo 'User name does not exist in the table.';
}
?>
First of all, your html page should have the extension .php and not .html, that way it can interpret your php code inside the html file, don't worry this wont break the html.
why is it undefined if it's defined in the php file.
It's because each php script run separately unless you hook them together.
I would recommend yo read a bit more about how php works.
For this example to work i would do it it this way.
CoinSubmission.php
<?php //This goes at the top of the file
include_once('AdminCoinSub_Code.php') //If they are in the same dir else you will need to set the path properly.
?>
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo
htmlspecialchars($Nickname); ?>">
</p>
</form>
The include at the top will "paste" your code of AdminCoinSub_Code in the CoinSubmission file and treat it as one file. So the variable will be accesible for it.
Note: My explanation is oversimplified, it ain't exactily how it works, but should get the gist of it.
Alaa Morad answer if also valid, but remember to change the .html to .php
Happy Coding :)
That's because $Nickname will not be set if Register Globals is off witch is a normal thing !
Register Globals has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0
so use $_POST
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($_POST['Nickname']); ?>">

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!

take database user,pass,name and host info from user's and want to update a database column info

I am new here and noob in programming.
I have created a script that can change a database column but now I want to take database login info from user's and the changed value from user's when they give all info correctly the script changed the database column info which was given by the user's.
Here is my login.html source code :
<html>
<center>
<form action="db.php" method="post">
DB Host: <input type="text" name="host"><br>
DB Username: <input type="text" name="usr"><br>
DB Password: <input type="password" name="psw"><br>
DB Name: <input type="text" name="dbname"><br><br><br>
Admin changed Username: <input type="text" name="admusr"><br>
Admin Changed Password: <input type="password" name="admpsw"><br>
<input type="submit">
</form>
</center>
</html>
and here is my db.php source code which can update database column info manually
<?php
$servername = "localhost";
$username = "admin";
$dbname = "mydb";
$password = "1234";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($conn,"$dbname");
$sql = "UPDATE admins SET user_login='admin1',user_pass='1234' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Is it possible to take value from user's and changed the database column info?
Sorry for bad english.
It's very bad idea... loads of security issues. But if you want to change it from received form values just change your query to this:
// escape received values
$usr = $conn->real_escape_string($_POST['usr']);
$psw = $conn->real_escape_string($_POST['psw']);
// use them in query
$sql = "UPDATE admins SET user_login='".$usr."',user_pass='".$psw."' WHERE id=1";
You got more field which is user filling... I don't know your exact table structure. But if you want to use all of them just add received escaped values to your query:
// escape received values
$usr = $conn->real_escape_string($_POST['usr']);
$psw = $conn->real_escape_string($_POST['psw']);
$host = $conn->real_escape_string($_POST['host']);
$dbname = $conn->real_escape_string($_POST['dbname']);
$admusr = $conn->real_escape_string($_POST['admusr']);
$admpsw = $conn->real_escape_string($_POST['admpsw']);
// use all of them in query depending on your table structure
$sql = "UPDATE admins SET user_login='".$usr."',user_pass='".$psw."' WHERE id=1";
Use $_POST variable to retrieve data that user entered on login.html page
like in db.php for $servername and $username use
$servername = $_POST['host'];
$username = $_POST['usr'];

PHP Instant messenger

I am trying to make a messenger using PHP and SQL
This is my code
<form action="send_post.php" method="post">
<h3>Name:</h3>
<input type="text" name="name">
<h3>Message:</h3>
<input type="text" name="message">
<input type="submit">
</form>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, message FROM chat";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
while(1){
ob_start();
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
sleep(10);
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
ob_end_clean();
}
}
}
$conn->close();
?>
However this does not work, is there any reason for this?
The problems started once I added the infinite while loop to refresh the messages.
PHP works serversided, which means that the client(guest) requests a page that the server then "compiles" to then send to the client as a clientsided language such as HTML. If the PHP code never reaches an end/stop the client browser is going to think the server stopped responding and give an error.
To achieve what you are trying to do you might want to look into something like JQuery AJAX which allows for the client to fetch data from the server seperatly from the main request. That way you can have one file showing only the messages and request that file on a timer, while having the form as usual page load. You can however also make the form dynamic using JQuery AJAX
UPDATE You can look at this blogpost to get an idea of what I'm talking about.

PHP/html email form no longer submitting to mysql database

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

Categories