Data not Inserting into Database and no error - php

I have a problem...
Im trying to take data inserted into my html5 form and insert it into a database. Now i have the form made along with a script that should be working; instead there is no data being inserted into the database and there is no error showing. Please help.
form.php
<form name="loginForm" method="post" action="process.php">
<input id="username" type="text" placeholder="Username" name="username">
<input id="password" type="password" placeholder="Password" name="password">
<input type="submit" id="Login" class="form-control" value="Log In">
</form>
process.php
<?
$username=$_POST['username'];
$password=$_POST['password'];
mysql_connect("localhost", "root", "toor") or die(mysql_error());
mysql_select_db("formd") or die(mysql_error()); mysql_query("INSERT INTO `data` VALUES ('$username', '$password')");
Print "Your information has been successfully added to the database.";
?>
Now i know this isnt a secure way to store passwords or usernames but this isnt for any website really i just wanna know how to take information from my form and store it into a database.

You've added minimal error handling to all mysql functions call but the one involved in the actual query....
The script is also prone to sql injections.
The mysql_* extension is mared as deprecated, better pick another mysql extension.
<?php
$mysql = mysql_connect("localhost", "root", "toor")
or die(mysql_error());
mysql_select_db("formd", $mysql)
or die(mysql_error($mysql));
$username=mysql_real_escape_string($_POST['username'], $mysql);
$password=mysql_real_escape_string($_POST['password'], $mysql);
mysql_query("INSERT INTO `data` VALUES ('$username', '$password')", $mysql)
or die(mysql_error($mysql));
echo "Your information has been successfully added to the database.";
using or die(mysql_error()) can lead to Information Leakage issues

Im still learning the very basics myself, i have not tested this and just snipped it out of a very long sql script i have so it may work and may not, hopefully it does help you out.. if not take a look at the link below the code. Hope it works for you or may need a little tweak. Thanks
<?php
if (isset($_POST['submit'])) {
$submit = $_POST['submit'];
$username = $_POST['username'];
$password = $_POST['password'];
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'toor';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: '.mysql_error());
}
$sql = "INSERT INTO data (username','password')
VALUES('$username','$password')";
mysql_select_db('formd');
$retval = mysql_query($sql, $conn);
if (!$retval) {
die('Could not enter your data: '.mysql_error());
}
echo "Entered your dara successfully\n";
mysql_close($conn);
} else {
echo "Something has gone wrong.";
}
?>
Alternative link to take a look at: http://www.jotform.com/help/126-How-to-send-Submissions-to-Your-MySQL-Database-Using-PHP

Related

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 doesn't insert form data into MySQL database

I got it all working, thanks for all your help and pointing me in the right direction.
i have a web host, which has MySQL, and phpMyAdmin. The code below shows the PHP in my .php file. When i submit the form, the data does not store in the SQL database.
My database is a table called 'Logins'. It has three fields: 'userID' which is an autoincrement type,'email' which is a VARCHAR, and 'password' which is also a VARCHAR.
I have tested my connection, and it does work, meaning something in the code is wrong, but i can't find it. I would be grateful if you guys could help me.
This is my code:
<form action="index.php" method="post">
<p>Email Address:</p>
<input type="text" name="email" required autofocus pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" placeholder="Please enter your email">
<p>Password:</p>
<input type="text" name="password" required placeholder="Enter your password">
<p>Confirm Password:</p>
<input type="text" name="confirmpassword" required placeholder="Confirm your password">
<br>
<input class="button" type="submit" value="Register">
</form>
<?php
if($_POST['submit']=="Submit")
{
$email = cleanData($_POST['email']);
$password = cleanData($_POST['password']);
$message = "wrong answer";
addData($email, $pasword);
}
function cleanData($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = strip_tags($data);
return $data;
}
function addData ($email, $password)
{
//include("dbinfo.php");
$dbhost = 'mysql11.000webhost.com';
$dbuser = '************'; //censored for security
$dbpass = '******'; //censored for security
$conn = mysql_connect("$dbhost", "$dbuser", "$dbpass");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql="INSERT INTO Logins ('userID','email','password') VALUES (null, '$email', '$password')";
$result=mysql_query($sql) or die(mysql_error());
}
?>
The sql insert field names should not be in quotes and you mentioned that userID is autoincrementing so no need to include it unless you want to set it to a specific value.
$sql="INSERT INTO Logins (email, password) VALUES ('$email', '$password')";
You should also consider changing to mysqli since mysql is depreciated.
Edit: Your mysql_connect is missing the database select variable in the code you provided.
You will find debugging mysql queries much easier if you make use of the return values of each mysqli function. The below code checks for, and returns, any errors relating to database connection, query prepare, parameter binding, and execution.
This procedure makes it much easier to identify problems if they occur and with modification can be used to log errors, and report errors to the user even in production.
function addData ($email, $password)
{
//include("dbinfo.php");
$dbhost = 'mysql11.000webhost.com';
$dbuser = '************'; //censored for security
$dbpass = '******'; //censored for security
$dbname = ''; // this is currently missing
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* check connection */
if ($mysqli->connect_errno) {
die("Connect failed: ".$mysqli->connect_error);
}
// define the query
$sql="INSERT INTO Logins (email, password) VALUES (?, ?)";
// prepare the query
if (!$stmt = $mysqli->prepare($sql)) {
// failed to prepare query;
die("Prepare failed: ".$stmt->error);
}
// bind the parameters
if (!$res = $stmt->bind_param('ss', $email, $password)) {
// failed to bind
die("Bind failed: ".$stmt->error);
}
// execute
if (!$res = $stmt->execute()) {
// failed to execute
die("Execute failed: ".$stmt->error);
}
echo "Rows inserted: ".$stmt->affected_rows;
}
change if($_POST['submit']=="Submit")
to if(!empty($_POST['email']) && !empty($_POST['password']))
you must replace the line :if($_POST['submit']=="Submit")
By if(!empty($_POST['submit']))
Or by if($_POST['submit']=="Register")
Try to connect with wrong password and wrong login want to know if
it display the message

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'];

Data not being inserted into database from form, what am i doing wrong?

I have the following 2 files and a database that is running in the background. When ever I submit the form. The data is not being inserted into the database. It connects to my database successfully but it does not insert:
update.html
<html>
<head><title>Test Page</title></head>
<body>
<h2>Data Collection</h2><p>
<form action="update.php" method="post">
<table>
<tr><td>id</td><td><input type="text" name="id" /></td></tr>
<tr><td>title</td><td><input type="text" name="title" /></td></tr>
<tr><td>name</td><td><input type="text" name="name" /></td></tr>
<tr><td>hello</td><td><input type="text" name="hello" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" /></td></tr>
</table>
</form>
</body>
</html>
update.php
<?php
$GLOBALS['title'];
$GLOBALS['id'];
$GLOBALS['name'];
$GLOBALS['hello'];
$hostname="localhost:3036";
$username="root";
$password="";
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Check connection
if (mysql_error())
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_select_db('website');
$sql="INSERT INTO articles (id, title, name, hello)
VALUES('$id','$title','$name','$hello')";
mysql_close($con);
echo "test";
All help is appreciated.
You are not executing the query at all and as correctly stated in the comments, you weren't setting the variables correctly;
change your code to match:
$title = $_POST['title'];
$id = $_POST['id'];
$name = $_POST['name'];
$hello = $_POST['hello'];
$hostname="localhost:3036";
$username="root";
$password="";
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Check connection
if (mysql_error())
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_select_db('website');
$sql="INSERT INTO articles (id, title, name, hello)
VALUES('$id','$title','$name','$hello')";
mysql_query ( $sql, $con);
mysql_close($con);
Please try this code:
Note: i just ignore your deprecated msqyl function
<?php
$hostname="localhost:3036";
$username="root";
$password="";
$title = $_POST['title'];
$id = $_POST['id'];
$name = $_POST['name'];
$hello = $_POST['hello'];
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Check connection
if (mysql_error())
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_select_db('website');
$sql=mysql_query("INSERT INTO articles (id, title, name, hello)
VALUES('$id','$title','$name','$hello')") or die(mysql_error());
mysql_close($con);
echo "test";
First you are not defining the variables that are inserting. '$id','$title','$name','$hello'.
Define previous to insert, when the $_POST is accepted, use
else {$id'= $_POST['id'];}
Second. and more important, don't ever use this code which by the way is old, deprecated and very unhealthy. It's prone to SQL INJECTION.
Instead use PDO, and sanitize user submitted values.
Also avoid use of $GLOBALS, the same, old, deprecated, unsafe.
Please refer to PHP sanitize which explains how to clean your user submitted data. Check this:
$id=filter_var($_POST['id'], FILTER_SANITIZE_STRING);

trying to get PHP and database to work together

I'm trying to teach myself how to work with php and mysql. For practice, I made a simple test website that takes a username and a password, and a database using phpmyadmin and mysql. I was able to create a successful connection to my DB, but now I'm trying to take the data from the form on my website and insert it into a table called 'account'. Account has three fields: 'username', 'password', and 'userID'(primary key). user ID is supposed to auto increment, so that field doesn't require input data. I wrote code that I thought would collect the username and password and add it as a new record in the account table, but I get an error message:
Internal Server Error
The server encountered an internal error or misconfiguration and was
unable to complete your request.
Additionally, a 404 Not Found error was encountered while trying to
use an ErrorDocument to handle the request.
Below I've included my code. I've never worked with PHP before or made a DB before so it's possible I've made very obvious mistakes.
php_script
<?PHP
$db_host = "stevie.heliohost.org";
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = #mysql_connect ("$db_host","$db_username", "$db_pass")
or die ("could not connect to mySQL");
#mysql_select_db("$db_name") or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('$_POST[user]','$_POST[password]')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
?>
HTML FORM
<form name="LOGIN" action="php_script.php" method="post">
Username: <input id="username" type="text" name="user">
password: <input id="password" type="text" name="password">
<input id="submit" type="submit" value="Submit">
</form>
try this out
$db_host = 'stevie.heliohost.org';
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = mysql_connect($db_host,$db_username, $db_pass)
or die ("could not connect to mySQL");
mysql_select_db($db_name) or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('".$_POST[user]."','".$_POST[password]."')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
OBS: u should use mysqli or PDO , your code is easy for sql injections
If you are teaching yourself PHP, the First thing you should do is learn PDO. Because, the way you are using mysql, you are leaving your site open for SQL-Injection type of hacking, which anyone can do. Since you are directly submitting the value of $_POST['']; in your database. Start learning PDO today, it is much more secure. You can find the a good tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Additionally, Check this code as I have modified it a little bit. and host name, is almost always localhost
<?PHP
$db_host = "localhost";
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = mysql_connect ("$db_host","$db_username", "$db_pass")
or die ("could not connect to mySQL");
mysql_select_db("$db_name") or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('$_POST[user]','$_POST[password]')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
?>
First of all you shouldn't be using mysql_ functions because they are being deprecated. Try to use PDO or likes.
second try this
$db_host = 'stevie.heliohost.org';
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = mysql_connect($db_host,$db_username, $db_pass)
or die ("could not connect to mySQL");
mysql_select_db($db_name) or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('".mysql_escape_string($_POST[user])."','".mysql_escape_string($_POST[password])."')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
you should be escaping your values in your query too so the its not up for SQL injection
I am not up for for using mysql_escape_string either you should be using atleast mysqli
So go through a good tutorial to learn more about it

Categories