PHP form in HTML, won't connect - php

So I am very new to PHP,and databases in general, so please be indulgent! :)
I created a simple form in an HTML file:
<h1> Créez votre compte ici</h1>
<form action="form.php" method="post">
<p id="textdone"> </p>
<input type= "text" name="Surname" autocomplete="on" placeholder="Votre nom" required/> <br> <br>
<input type= "text" name="Name" autocomplete="on" placeholder ="Votre prenom" required/> <br> <br>
<input type= "email" name="Email" autocomplete="on" placeholder ="Adresse mail" required/> <br><br>
<input type= "text" name="Pseudo" autocomplete="off" placeholder ="Votre pseudo" maxlength="20" required/> <br>
<p>Ajoutez une photo de profil: <input type= "file" /> <br><br></p>
<p> Entrez un mot de passe: <input type="Password" name="Passwird" autocomplete="off" maxlength="20" required placeholder="Mot de passe"/> <br><br>
Validez votre mot de passe: <input type="password1" autocomplete="off" maxlength="20" required placeholder="Mot de passe"/> <br><br>
</p>
<input type="submit" value="Soumettre"/>
</form>
</body>
And so my action file, the form.php file, saved in the same folder (I made sure) is as follows:
<?php
define('DB_NAME', 'Matchy');
define('DB_USER', 'root#localhost');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use' . DB_NAME. ':'. mysql_error());
}
echo 'Successful connection';
$surname = $_POST['Surname'];
$name = $_POST['Name'];
$email = $_POST['Email'];
$pseudo = $_POST['Pseudo'];
$password = $_POST['Password'];
$sql = "INPUT INTO users (Name) VALUES ('$name')";
$sql1 = "INPUT INTO users (Surname) VALUES ('$surname')";
$sql2 = "INPUT INTO users (Pseudo) VALUES ('$pseudo')";
$sql3 = "INPUT INTO users (Email) VALUES ('$email')";
$sql4 = "INPUT INTO users (Password) VALUES ('$password')";
if (!mysql_query($sql)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql1)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql2)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql3)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql4)) {
die ('Error: ' .mysql_error());
}
mysql_close();
?>
But every time I fill out my form and hit submit, I get this message:
Cannot Post /form.php.
I get this code from this following video (https://www.youtube.com/watch?v=wp6Ngpk5XiY&index=2&list=PL530D33D6E548481F), which was very useful. But I really can't connect. I created my table on my database, with all the right columns.
I use phpMyAdmin.
Thank you so much to anyone who can help!! :)

Let's outline the errors here.
INPUT INTO isn't a valid MySQL expression, the syntax is INSERT INTO.
Then you have name="Passwird" and $_POST['Password'] which do not match and error reporting http://php.net/manual/en/function.error-reporting.php would have told you about it.
Then as outlined in comments by another member:
<input type="password1" autocomplete="off" maxlength="20" required placeholder="Mot de passe"/> this one is providing no love too. No inputtype password1 – Hendra Nucleo
which should have been password and not password1.
Best to use the right and official references http://dev.mysql.com/doc/en/insert.html and switch to PDO with prepared statements or mysqli_* with prepared statements, as the mysql_* functions are deprecated. The official manuals are the best references.
They won't steer you wrong ;-)
That tutorial probably didn't mention anything about SQL injection, so that's a good read in its own right.
Nor did it mention anything about passwords.
I noticed that you may be storing passwords in plain text. This is not recommended.
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 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.
Edit:
That whole block of code could have easily been done in a few lines, such as and without so many calls to the same table:
$sql = mysql_query("
INSERT INTO users (Name, Surname, Pseudo, Email, Password)
VALUES ('$name', '$surname', '$pseudo', '$email', '$password')
");
if($sql){
echo "Success!";
}
else { "Error: " . mysql_error(); }

Yeah, #gmiley raised a good question, check whether you can use input or not and instead use insert query with all the values in single statement. For syntax, you can refer the following link:http://www.w3schools.com/sql/sql_insert.asp

Related

Submitting form, mysql and php

I'm new to php and sql and all that stuff, and I was watching a tutorial on youtube about forums in php and wonder why this code doesn't echo "Success" when submitting the form. I also wonder why it echo out Failure before I have submitted the form. I have connected successfully to the database.
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="register.php" method="POST">
Username: <input type="text" name="username">
<br/>
Password: <input type="password" name="password">
<br/>
Confirm Password: <input type="password" name="confirmPassword">
<br/>
Email: <input type="text" name="email">
<br/>
<input type="submit" name="submit" value="Register"> or Log in
</form>
</body>
</html>
<?php
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysql_query("INSERT INTO users ('id', 'username', 'password', 'email') VALUES('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysql_error();
}
}
?>
Connect.php
<?php
$connect = mysqli_connect("localhost", "root", "") or die("Could not connect to server!");
mysqli_select_db($connect, "php_forum") or die("Could not connect to database!");
?>
There are a few things wrong here.
You're using the wrong identifiers for your columns in (and being quotes):
('id', 'username', 'password', 'email')
remove them
(id, username, password, email)
or use backticks
(`id`, `username`, `password`, `email`)
mysql_error() should have thrown you an error, but it didn't because of:
You're mixing MySQL APIs with mysqli_ to connect with, then mysql_ in your query.
Those two different APIs do not intermix with each other.
Use mysqli_ exclusively and change your present query to:
if($query = mysqli_query($connect, "INSERT...
and change mysql_error() to mysqli_error($connect)
as a rewrite for that block:
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users ('id', 'username', 'password', 'email') VALUES('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
Just to test the error, make the changes as I outlined just above, while keeping the quotes around your columns the way you have it now. You will then see the error that MySQL will throw. You can then do as I've already outlined above and remove the quotes around the column names, or replace them with backticks.
The tutorial you saw may very well used backticks, but were probably not distinguishable enough for you to tell that they were indeed backticks and not single quotes.
However, your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Also, instead of doing:
$connect = mysqli_connect("localhost", "root", "") or die("Could not connect to server!");
mysqli_select_db($connect, "php_forum") or die("Could not connect to database!");
You should be checking for errors instead, just as the manual states
$link = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($link));
http://php.net/manual/en/function.mysqli-connect.php
So in your case:
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
Edit: and I changed action="register.php" to action="" since you're using the entire code inside the same page.
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Username: <input type="text" name="username">
<br/>
Password: <input type="password" name="password">
<br/>
Confirm Password: <input type="password" name="confirmPassword">
<br/>
Email: <input type="text" name="email">
<br/>
<input type="submit" name="submit" value="Register"> or Log in
</form>
</body>
</html>
<?php
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users (`id`, `username`, `password`, `email`) VALUES ('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
:It will echo ;Failure' so executing this bit of code
else{
echo "Failure" . mysql_error();
}
whenever $_POST["submit"]) is not set and it will be not set anytime you open you page (even if you navigate to it from your bookmark of from google search results) or when you submit you FORM in GET mode

register including post fail

I am trying to build a login system with registration etc.
now for the registration i use a form and the method "post". Now it fails in what i think is sending the input trough the post. can you help me fix it? here is the code involved in it:
above !doctype
<?php
include('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST["username"]) && isset($_POST["password"])){
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$query = "INSERT INTO `user` (username, password, email) VALUES ($username, $password, $email)";
$result = mysqli_query($query);
if($result){
$msg = "User Created Successfully.";
}
else
{echo "fail";}
}
?>
the form:
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Registreer</h1>
<form action="" method="POST">
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email" required placeholder="name#email.com" /></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Registreer" />
</form>
</div>
The connect.php
<?php
$servername = "localhost";
$username = "sqluser";
$password = "Welkom01!";
$dbname = "users";
$connection = mysqli_connect($servername, $username, $password);
if (!$connection){
die("Database Connection Failed". mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, $dbname);
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
Thanks in advance.
As per your originally posted question and without marking it as an edit under your newly edited question, should anyone wonder why the answer.
Since we're more than likely dealing with strings
VALUES ($username, $password, $email)
needs to be wrapped inside quotes:
VALUES ('$username', '$password', '$email')
you also need to pass DB connection to your query $result = mysqli_query($query);
Edit: (you added your DB connection code after) from your original post
Since you've not shown what your DB connection is, this would be something like
$result = mysqli_query($connection,$query);
plus, adding or die(mysqli_error($connection)) to mysqli_query()
You also have a missing & in if(isset($msg) & !empty($msg)){ which should read as if(isset($msg) && !empty($msg)){
However, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
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

Getting PHP and MySQL Setup for user login page [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I am trying to create a login page so that certain users within our organization will have access to a form with sensitive information. I decided to use PHP and MySQL to do this and believe I am very close, but am having issues getting the two to connect to one another. I am using WAMP server so I have a localhost setup.
Here is my very basic html form:
<form method="post" action="addemail.php">
<label for="firstname">First Name:</label>
<input type="text" id="firstname" name="firstname" /> <br/>
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lastname" /> <br/>
<label for="email">Email:</label>
<input type="text" id="email" name="email" /> <br/>
<input type="submit" value="submit" name="submit"/>
</form>
On my PHP form, I have this:
$dbc = mysqli_connect('localhost', 'root', 'password', 'leadmen')
or die('Error connection to MySQL server.');
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$query ="INSERT INTO leadmen_usernames (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query)
or die('Error querying database');
echo 'Username Added.';
mysqli_close($dbc);
I don't know too much about these technologies but believe the problem lies either within my connection info to $dbc = mysqli_connect, or maybe there's an error with mysqli vs mysql?
Not sure if this matters, but I used phpmyadmin to create the table.
If you see just the PHP code you probably forgot the opening PHP tag before you start to write actual PHP code.
<?php
$dbc = mysqli_connect('localhost', 'root', 'password', 'leadmen')
or die('Error connection to MySQL server.');
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$query ="INSERT INTO leadmen_usernames (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query)
or die('Error querying database');
echo 'Username Added.';
mysqli_close($dbc);
?>
You can close it again with '?>'

Code doesn't write values in db

The code below should write code into the database.
I have divided into two parts HTML AND PHP code are separate. HTML form code is shown below:
<form name="form1" action="insert.php" method="post">
<h3>Ime </h3> <input type="text" name="field1" > <br/> <br/>
<h3>Prezime </h3> <input type="text" name="field2" > <br/> <br/>
<h3>Firma </h3> <input type="text" name="field3" > <br/> <br/>
<h3>Adresa </h3><input type="text" name="field4" > <br/> <br/>
<h3>Telefon </h3> <input type="text" name="field5" > <br/> <br/>
<h3>Fax </h3><input type="text" name="field6" > <br/> <br/>
<h3>Mobitel </h3> <input type="text" name="field7" > <br/> <br/>
<h3>Email </h3> <input type="text" name="field8" > <br/> <br/>
<h3>Web stranica </h3> <input type="text" name="field9" > <br/>
</form>
PhP code is shown below.
$host="localhost"; // Host name
$username="root"; // username
$password="le30mu09"; // password
$database="imenik"; // Database name
$tbl_name="clanovi"; // Table name
// Replace database connect functions depending on database you are using.
$field1=$_POST['field1'];
$field2=$_POST['field2'];
$field3=$_POST['field3'];
$field4=$_POST['field4'];
$field5=$_POST['field5'];
$field6=$_POST['field6'];
$field7=$_POST['field7'];
$field8=$_POST['field8'];
$field9=$_POST['field9'];
$link=mysql_connect("$host", "$username", "$password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db("$database");
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
$query = "INSERT INTO `clanovi`(`Ime`, `Prezime`, `Firma`, `Adresa`, `Telefon`, `Fax`, `Mobitel`, `Email`, `Web_stranica`) VALUES ( "$field1", "$field2", "$field3", "$field4", "$field5", "$field6", "$field7", "$field8", "$field9")";
mysql_query($query);
mysql_close();
You need to tell us what the actual error is. And bone up on PDO and the dangers of sending unsanitised POST variables to the DB as a matter of priority.
Modify your Insert query. It should be like this:
INSERT INTO clanovi
(column1,column2,column3,...)
VALUES
( $field1, $field2, $field3,.....)
You appear to be using a lot of quotation marks in places that you shouldn't be using them in. It is funny how you can code something for 5 hours and then try to debug it for 2 hours because of a simple quotation mark! It's funny and very depressing at the same time :(
Ok, let's fix the code a little bit!
Database
$link=mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
Notice how I stripped all of the quotation marks out of the code? That will help with database connection and selection.
Now let's move onto the actual inserting of the information into the database!
$query = "INSERT INTO clanovi ('Ime', 'Prezime', 'Firma', 'Adresa', 'Telefon', 'Fax', 'Mobitel, 'Email', 'Web_stranica') VALUES ( $field1, $field2, $field3, $field4, $field5, $field6, $field7, $field8, $field9)";
Again, I stripped all of the quotation marks. Plus I removed backticks and replaced with a ' and also took the '' off of your table name - You should nly use quotation marks when not using a variable.
//Correct
VALUES ($field1, "textnotvariable", $field2...
//Incorrect
VALUES ("$field1", "textnotvariable", "field2"...
The same goes with echo statements. Here's an example...
$myname = "MrJustin";
//Correct
echo $myname;
//or
echo "My name is ". $myname .", it's nice to meet you!";
//Incorrect
echo "My name is $myname, it's nice to meet you";
You'll notice how I used ". $myname ." - that tells the echo to break away from using text, and to pass a variable! :) That to me is the best way to explain how quotations will break a code.
Oh, and you should ALWAYS sanitize your inputs/outputs when using foreign code. I would do some Google searching on that one, and then chat us back up if you run into problems with that!
Hopefully this helps, and happy coding!!
you are not selecting database. you are using double quotes in not its place.
replace this
$db_selected = mysql_select_db("$database");
by
$db_selected = mysql_select_db($database);
and also replace this
$link=mysql_connect("$host", "$username", "$password");
by
$link=mysql_connect($host, $username, $password);
i recomand you to use PDO or mysqli instead.

security help regarding php registration [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL injection in PHP?
This is a simple registration I made in PHP.
I just want to know how to make it really secure, as I am new to PHP, so examples would help also. All in all, any resources or guidance would be great.
<?php
$email = $_POST["email"];
$password = $_POST["password"];
$fname = $_POST["first_name"];
$lname = $_POST["last_name"];
$db = "mydatabase";
$connect = mysql_connect("localhost","root","");
if(!$connect){
die('Could not connect.');
}
$query = "INSERT INTO users (id, email, password, first_name, last_name) VALUES (DEFAULT, '".$email."', '".$password."', '".$fname."', '".$lname."')";
mysql_select_db($db, $connect);
if(!mysql_query($query)){
echo 'Failed: '.mysql_error();
}
else{
echo 'You have registered.';
}
mysql_close($connect);
?>
and this is the register input form
<html>
<head>
</html>
<body>
<form action="new_user_db.php" method="POST">
<input type="text" name="first_name" placeholder="First Name" required><br>
<input type="text" name="last_name" placeholder="Last Name" required><br>
<input type="email" name="email" placeholder="E-mail" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
thanks for all your feedback!
Security Issues:
Use MySQLi/PDO. mysql_ functions are deprecated.
Stop using the root account to run your mysql queries. Create a new database user with the minimum required privileges
Finally (unrelated to PHP), look into SSL and securing the movement of credentials from client to server.
Also, not a security risk but...
Having your credentials in every single PHP file that uses it is bad practice. Put it in a separate PHP and include/require it, whenever you want to make a connection. That prevents you having to make several changes when changing database server/user/password.
Use a Prepared Statement
$db = mysqli_connect($dbserver, $dbuser, $dbpass,$dbname);
$sql = "insert into mytable (mycol1, mycol2) values (?,?)";
$statement = $db->prepare($sql);
$statement -> bindparam("ss",$myval1, $myval2)'
mysqli_stmt_execute(#statement);

Categories