Can't get my data Inserted into MySQL database, using PHP - php

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 .

Related

Not able to insert data using html form and php using wamp [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 1 year ago.
I am trying to insert data into a database from HTML form using php. I made two files html form and other is PHP script. When I click on submit in html form, it shows me the php code. I am using wamp server for database. I put my html files in C:/wamp64/www directory and html files at my local directory. The database table is :
id int(11)
fname varchar(30)
salary int(11) . Id is not auto-incremented and it is a primary key.
Html code:
<html>
<body>
<h2>Employee's Information</h2>
<form action="employee.php" method="POST">
<label for="id">Enter employee id:</label><br>
<input type="text" id="id" name="id" value=""><br>
<label for="fname">Enter First name:</label><br>
<input type="text" id="fname" name="fname" value=""><br><br>
<label for="salary">Enter Employee Salary:</label><br>
<input type="text" id="salary" name="salary" value=""><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
</html>
Php code:
<?php
$mysql_hostname="localhost";
$mysql_username="root";
$mysql_password="";
$mysql_database="employee";
$con=mysql_connect($mysql_hostname,$mysql_username,$mysql_password);
if(!$con){
die('Connection Error: '.mysql_error());
}
mysql_select_db($mysql_database, $con);
if(isset($_POST['submit']))
{
$s_id = $_POST['id'];
$s_name = $_POST['fname'];
$salary = $_POST['salary'];
$employeeinsert = "INSERT INTO employee1
(id, fname, salary)
VALUES('".$s_id."','".$s_name."','".$salary."')";
if(!mysql_query($employeeinsert,$con)) {
echo "Error: " .mysql_error($con);
} else {
echo "1 record added";
}
}
?>
The code is neither giving any error on submitting data nor it is inserting the data into the database.
I am not getting what the error is.
If this is false then the code successfully produces no output:
if(isset($_POST['submit']))
Which is what's happening, since the condition is false. The form has a submit button, but that button has no name attribute to its value isn't sent to the server:
<input type="submit" value="Submit">
Give it a name:
<input type="submit" name="submit" value="Submit">
It's always a good idea to have some kind of indication of any given code branch, even if just logging something somewhere so you can see what's happening. Code will happily produce no output/result if that's what it's instructed to do, but as you've discovered it can leave you with no information about what's happened.
As an aside, and this is important, your code is wide open to SQL injection. You'll want to start addressing that.

How to decrypt md5 passwords in php with substr? [duplicate]

This question already has answers here:
encrypt and decrypt md5
(6 answers)
Closed 5 years ago.
I am sharing my 2 file's code.for insert username and passwords and to retrieve data. My scenario is something different. if username :
abc and password: 123456789
on login screen user have to enter only 3 digits from his password.But that will be random numbers from his password. if now system will ask me for 1st,3rd and 9th digit from password.after reload page it will change randomly. it will display 2nd,5th and 4th etc etc.
I am done this task earlier with my code. but now i am thinking to insert password with md5 encryption method.
I am stuck here if i used md5 for encryption then how to retrive password.
insert.php :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<label>username</label>
<input type="text" name="username">
<label>pin</label>
<input type="password" name="pin">
<label>password</label>
<input type="password" name="password">
<button name="submit">Submit</button>
</form>
</body>
</html>
<?php
include 'conn.php';
if (isset($_POST['submit']))
{
$name = $_POST['username'];
$pass = md5($_POST['password']);
$sql = mysqli_query($conn,'INSERT INTO `emp`(`name`, `pass`) VALUES ("'.$name.'","'.$pass.'")');
if ($sql>0)
{
header('Location: index.php');
}
}
?>
index.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include 'conn.php';
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$pass3 = $_POST['pass3'];
$char1 = $_POST['char1'];
$char2 = $_POST['char2'];
$char3 = $_POST['char3'];
$sql = 'SELECT name,pass,pin from `emp` '
. 'where `name` = "'.$name.'" '
. 'AND SUBSTR(pass, '.($char1).', 1) = \''.$pass1.'\' '
. 'AND SUBSTR(pass, '.($char2).', 1) = \''.$pass2.'\' '
. 'AND SUBSTR(pass, '.($char3).', 1) = \''.$pass3.'\' ';
$sql = mysqli_query($conn,$sql);
$data = mysqli_fetch_assoc($sql);
if ($data)
{
echo 'success';
}
else
{
echo 'Fail';
}
}
// generate unique, not equal numbers
$char_pos = range(1, 9);
shuffle($char_pos);
$char_pos = array_slice($char_pos, 0, 3);
sort($char_pos);
?>
<form action="" method="post">
<input type="hidden" name="char1" value="<?php echo $char_pos[0]; ?>">
<input type="hidden" name="char2" value="<?php echo $char_pos[1]; ?>">
<input type="hidden" name="char3" value="<?php echo $char_pos[2]; ?>">
Username:
<input type="text" name="username" value="">
Password:
<input type="password" class="inputs" maxlength="1" name="pass1" placeholder='<?php echo $char_pos[0]; ?>st' value="">
<input type="password" class="inputs" maxlength="1" name="pass2" placeholder='<?php echo $char_pos[1]; ?>th' value="">
<input type="password" class="inputs" maxlength="1" name="pass3" placeholder='<?php echo $char_pos[2]; ?>th' value="">
<button name="submit">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
</script>
</body>
</html>
MD5() function is not a encrypt decrypt function. it produce data based on input. That data cannot be reverted. if you need to check MD5 output with ordinary text, you have to MD5 ordinary text then compare both MD5 output.
There are several Online MD5 Decrypter present. It is based on Past input history.
www.md5online.org
md5decrypt.net/en/
You can check with this ..
Thank you...
As already pointed out in comments, md5 is a one-way hash function, not an encryption. This means that it is impossible to perform a partial password verification against the hash because the original password cannot be retrieved.
The Smart Architects blog used to have a great article on partial password verification, but now it is only accessible via web archive.
To sum up the possibilities (omitting the completely unsecure storing password in plain text solution):
Store the passwords in an encrypted format, meaning you can retrieve the password in plain text if needed for comparison. Pro: easy to implement. Con: if someone obtains the key, then all passwords can be reversed. If you want something really secure, then you probably need an HSM (Hardware Security Module) for this. Until you get your hands on an HSM, you can try openssl_encrypt() function.
Hash all combination of letters the interface may ask in a hashed format. Pro: probably the most secure storage format (if the right hashing algorithm is used with salts). Con: just think about the number of records you need to create for a long password.
Use Shamir secret sharing scheme. Pro: compromise in storage space vs security. Con: probably the most difficult solution to implement from a coding perspective.

password minimal length doesn't work

I want my password to be at least 6 characters long and if it is less than 6 characters long it has to say an error but it does not say anything.
<?php
if (strlen($_POST['userPassword']) < 6 ) {
$error[]= "wachtwoord moet minimaal 6 karakters bevatten <br />";
} else {
$cryptpass = md5($password);
$query = $dbcon->prepare("INSERT INTO users (userName,userPassword,userMail) VALUES (:userName,:userPassword, :userMail)");
$query->bindParam(":userName", $_POST['userName']);
$query->bindvalue(":userPassword", $cryptpass);
$query->bindParam(":userMail", $_POST['userMail']);
$query->execute();
echo "gebruiker aangemaakt";
}
foreach ($error as $errors) {
echo $errors;
}
?>
this is my form:
<form action="registratie.php" method="post">
Username <br />
<input type="text" id="user_input" name="userName" placeholder="userame" /><br />
Password<br />
<input type="password" id="pass_input" name="userPassword" placeholder="password" /><br />
Password<br />
<input type="password" id="v_pass_input" name="userPassAgain" placeholder="password" /><br />
Email<br />
<input type="email" id="email" name="userMail" placeholder="email"><br />
<input type="submit" id="register" name="register" value="Register" disabled="disabled" />
</form>
Taken from comments:
"plus, is the form and PHP/PDO in the same file? how is this accessed, on a hosted site? local? if local, http://localhost/file.xxx or file:///file.xxx??
and
"#fred-ii- it is local. it is accessed like : file:///file.xxx – Furkan yavuz"
and
"there is the problem ^ #Furkanyavuz and why is this disabled="disabled" /> for submit disabled?"
There's the problem. You have to run this off a webserver and not as file:///file.xxx directly in your web browser.
The browser itself won't parse PHP directives.
But as http://localhost/file.xxx or http://example.com/file.xxx.
If you don't have a webserver/PHP installed, you will have to install one or run it off a hosted website.
Sidenote: If you're running this off the same file, you will first need to check if the inputs are empty or not.
Reference: http://php.net/manual/en/function.empty.php
Also, since you're using PDO, why are you using MD5 to store passwords with? It is no longer safe to do so now.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or crypt, 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.
Footnotes:
Comments from Ali Zia:
You can fix that by using if (isset($_POST['userPassword']) && strlen($_POST['userPassword']) < 6 ) #Furkanyavuz – Ali Zia 2 mins ago
Also if (!empty($error)){ before foreach – Ali Zia 1 min ago
Sidenote: Using !empty() over isset() is better as it checks if it's both set and empty.
if (!empty($_POST['userPassword']) && strlen($_POST['userPassword']) < 6 )
Regarding PDO/query/connection.
The connection is unknown, whether it is in fact PDO.
Note that different MySQL APIs do not intermix. So, if you're using mysqli_ or mysql_ to connect with, that won't work with your PDO query.

Executing query through HTML form

views/registration.php
<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>
classes/registration.php
if(isset($_POST['submit']))
{
// Define form variables
$username = $_POST['username'];
$password= $_POST['password'];
// Insert form data into database
$query = "INSERT INTO users (username, password)
VALUES ('$username', '$password')";
if(mysqli_query($conn, $query))
{
echo "Registration successfull.";
}
}
The problem is, when I click submit, I get a blank page. The query isn't being executed.
I thought the problem might be because my values aren't setup correctly, so I did the following:
VALUES ('$_POST['password']', '$_POST['password']')";
but that gives me an error, presumably because I am using ' inside of '
So now I am back to square one, unsure of why my query isn't being executed
You are getting a blank page because you don't echo something if $_POST submit isn't set.
if(isset($_POST['submit']))
is never true as your $_POST['submit'] is never set. You need to give your submit a name, this (the name) is what get's POSTed / what you can access within $_POST[' /*name of input*/ ']
Change your form to the following, then you should see your
echo "Registration successfull.";
HTML:
<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit"> <!-- <<<<<<<<<<< here -->
As a sidenote, you should absolutely consider using a prepared statement. Running a registration form with your insert query is like an invitation for people keen on ruining your server. You might want to try the query like this:
$query = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$query->bind_param('ss',$username,$password);
$query->execute;
This way, you will be secured against mysql injection.
Your file naming and paths seem to be mismatching(as per the file names you provided).
No matter if you keep:
views/registration.php
views/classes/registration.php
But if you follow:
--/classes
/registration.php
--/views
/registration.php
[Note: '--/' is the path of your root directory]
Then the form action classes/registration.php won't go anywhere.
So change it:
<form action="../classes/registration.php" method="post">
I suggest to follow the naming convention:
filename- for pages with HTML forms, and
filename_action- for action pages
Also notice the possible error cases mentioned by user baao in the other answer.

Grabbing IP on submit, SQL syntax error

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

Categories