( Sorry for my bad english )
I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?
Existing Code :
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Seeing that your code is coming from a POST form, you can use a conditional statement around it.
For example, in your HTML form:
<input type="submit" name="submit" value="Submit" />
then use:
if(isset($_POST['submit'])){
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
}
another thing is to make sure that fields are not left empty, using empty() I.e.:
if(empty($_POST['username'])){
echo "Enter a username.";
exit;
}
also isset(). I.e.:
if(isset($_POST['username'])){
// do something
}
You can also use a header("Location: http://www.example.com/page.php");
but make sure there is nothing else above your PHP, echo, HTML, etc.
In regards to your present code:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.
Related
I am trying to pass text variables from a form form a previous page and insert it into a SQL table. The problem I'm having is on the line: $sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ($firstName, 'smith')";.
If I were to replace "$firstName" with a basic string like "John", the name and last name would be inserted into the SQL table as intended. But, since I'm trying to insert a text value gathered from a form, I need to be able to use the non-static variables but for some reason that I cannot figure out, doesn't work. From everything I read online, just adding the variable into the parameter should make it work but it just doesn't.
I'm very new to this so I'm sorry if my question is confusing. Also, I am fairly certain that the issue does not lie on the file with the form on it.
Any help would be so awesome. thanks!
Here is the code that I'm having trouble with:
<html>
<?php
$username = $_Post['username'];
$email = $_Post['email'];
$phone = $_Post['number'];
$firstName = $_Post['firstName'];
$lastName = $_Post['lastName'];
$address = $_Post['address'];
$password = $_Post['password'];
$conn = new mysqli('localhost','root','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ($firstName, 'smith')";
$conn->query($sql);
echo $execval;
echo "Registration successfully...";
$conn->close();
}
?>
</html>
To summarize all other answers,
First, you should replace $firstName to '$firstName' because otherwise the text (e.g. "John") will be placed in your query without quotes, like this: INSERT INTO CUSTOMER (fname, lname) VALUES (John, 'smith') This results in an error because it thinks John is some sort of variable.
Second, your code is vulnerable to SQL Injection. This is a very serious vulnerability in your website as attackers can use it to read your entire database, and in this case, even create entries in your database, which can result in attackers being able to completely take over your site by writing files!
More in-depth info here: https://owasp.org/www-community/attacks/SQL_Injection
The important thing is that the user can control the $firstName variable that you use in $sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ('$firstName', 'smith')"; This way the attacker can change the query at that point. He could for example use the payload ', 'a'); DROP TABLE CUSTOMER;-- to delete all information in the CUSTOMER table.
There are multiple ways to prevent this, but the easiest is to use prepared statements. It looks something like this:
$stmt = $dbConnection->prepare("INSERT INTO CUSTOMER (fname, lname) VALUES (?, ?)");
$stmt->bind_param('ss', $param_firstName, $param_lastName);
$param_firstName = $firstName; // New line
$param_lastName = $lastName; // New line
$stmt->execute();
This way you make sure MySQL doesn't interpret any user input as SQL code, but only as values.
Again, more in-depth information here:
https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
If you get user input to insert into a database you should always use "Prepared statements" to prevent "SQL injection" or comparable things.
Check here:
PHP Prepared Statements - w3school
The solution of Aashish gaba should work as well but it's unsecure.
This should work for your code:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$phone = $_POST['number'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$address = $_POST['address'];
$password = $_POST['password'];
$conn = new mysqli('localhost','root','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("INSERT INTO CUSTOMER (fname, lname) VALUES (?, ?)");
$stmt->bind_param("ss",$fname, $lname);
// set parameters and execute
$fname = $firstName;
$lname = $lastName;
$stmt->execute();
echo $execval;
echo "Registration successfully...";
$conn->close();
}
?>
A nice to have of a prepared statement is the fact that they are reusable like:
// set parameters and execute
$fname = "person1_fname";
$lname = "person1_lname";
$stmt->execute();
$fname = "person2_fname";
$lname = "person2_lname";
$stmt->execute();
Also don't forget to use somthing to prevent other injections if you print a value to a user. Like:
echo "Registration successfully for" . htmlspecialchars($_Post['username']);
In addition save the password as hash (with a secure hashfunction) into the database.
As a quick fix you can update your $sql like this:
$sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ('{$firstName}', '{$lastName}')";
But now your code is vulnerable to SQL Injection.
At least you should use mysqli escape function before your $sql statement, like this:
$firstName = $mysqli->real_escape_string($firstName);
$lastName = $mysqli->real_escape_string($lastName);
But I strongly recommend you considering using more advanced options like PDO for the further steps and Production environments.
Remplace $firstName to '$firstName'.
or use prepared request
I have a file named reg.php that extends my registration.php for a login system.
The registration is connected with a mysqli database and I have a manual
increase in user id in php instead of autoincrement in mysqli because I could
not make this work.
When I hit the register button, my code is creating two entries in the db and
I dont know why.
<?php
if(isset($_POST["register_user"])){
header('location: login.php');
}
if(isset($_POST["username"])){
$username = mysqli_real_escape_string($db, $_POST['username']);
}
if(isset($_POST["email"])){
$email = mysqli_real_escape_string($db, $_POST['email']);
}
if(isset($_POST["password"])){
$password = mysqli_real_escape_string($db, $_POST['password']);
}
if(isset($_POST["passwordconfirm"])){
$passwordconfirm = mysqli_real_escape_string($db, $_POST['passwordconfirm']);
}
$idcount = mysqli_num_rows(mysqli_query($db, "SELECT id FROM user"));
$regquery = "INSERT INTO user (id, name, email, password) VALUES ('$idcount', '$username', '$email', '$password')";
mysqli_query($db, $regquery);
?>
all I want is one single entry.
There's nothing in the code, in your question, that could insert two rows in your database. My guess it that you call this script twice, probably because your form has two ways of submitting the same data:
The normal way, with the form action attribute.
Through an event, like onSubmit
You've got to stop the former, if the latter is used. Look at the example in the link for 2. It tells you how to stop the form from submitting as well:
// For this example, don't actually submit the form
event.preventDefault();
So if the onSubmit works, it stops the normal form submission, but if it doesn't work, the form is submitted the normal way.
I created a table in mysql as'cus_info'. It has columns as 'iD' 'NAME' 'PASSWORD' 'eMAIL'. iD column is auto increment. I want to insert a new row to this table when a new customer registered. For that I wrote the following code in PHP
<?php
error_reporting(0);
require "init.php";
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."');";
if(!mysql_query($con, $sql)){
echo '{"message":"Unable to save the data to the database."}';
}
?>
but always I get the message as "unable to save data to the database"
Could you please tell me where I have gone wrong?
Thanks in advanced.
Could you please tell me where I have gone wrong?
In more than one place.
To most directly answer your question, you can use mysql_error() to print the error you're getting from mysql. To even more directly answer it, you have swapped the order of the parameters and you don't need the semicolon to be included in the query. (See example code here.)
You shouldn't be using PHP's "mysql_*" functions, which were deprecated in PHP5.5 and even removed in PHP7. You also should not be passing user input from a form directly into a MySQL database without any cleaning.
First show your $con and then put error_reporting(1) to check if other error occurs.
And finnaly copy and replace in your code.
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."')";
Try This
<?php
error_reporting(0);
require "init.php";
if(isset($_REQUEST["save"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = mysql_query("INSERT INTO `cus_info` (`name`,`password`,`email`) VALUES ('$name','$password','$email')");
$values=mysql_insert_id();
if($values!='')
{
echo '{"message":"Successfully save the data to the database."}';
}
else
{
echo '{"message":"Unable to save the data to the database."}';
}
}
?>
I'm having an issue with a form I have created (Test purposes only, I am aware it's vulnerable to SQL Injection)
Basically, the form does not insert into the DB, yet it seems to be returning true on the script.
The code is as follows:
form.php
<form action="create.php" method="post">
<p>Username: <input type="text" name="username" />
</p>
<p>Password: <input type="password" name="password" />
</p>
<p><input type="submit" value="Create" name= "cre" />
</p>
</form>
create.php
<?php
session_start();
$dbname = "obsidian";
if(isset($_POST['cre'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$hashed_password = password_hash($password,PASSWORD_DEFAULT);
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if($registerquery = true)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
?>
I get the success message, but as I stated, the values do not get inserted into the DB.
Any help would be good.
This defines a query, but does NOT run it:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
The this is NOT "testing" for success. It's simply seeing the variable to true:
if($registerquery = true)
= is assignment, == is for equality testing.
You have to query the database. Try this:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if ($mysqli->query($registerquery))
{
// success.
}
else
{
// failed.
}
Here is the documentation: http://php.net/manual/en/mysqli.query.php
You missed the step where you actually hand the SQL query to the database.
$mysqli->query($registerquery);
has to be run before it will be inserted.
You can also change your if statement to the following
if ($mysqli->query($registerquery))
Also, you're currently using a single =, which is setting $registerquery instead of checking its value.
All you are doing here:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if($registerquery = true)
is setting a string and then later setting the string to true. This is always going to return true. There are two problems with this:
You need to execute the SQL statement that you have stored in the string for anything to happen in the database.
You are not really checking the return value ("=="), but rather using "=", which simply sets the variable. A very common mistake.
Additionally, you should probably no longer use the mysqli built in functions, since they will soon be deprecated. I would recommend switching to PDO before moving any further.
Formally, You should do something like this:
if(isset($_POST['cre'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$hashed_password = password_hash($password,PASSWORD_DEFAULT);
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
$stmt=$mysqli->prepare($registerquery);
if($stmt->execute())
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
$stmt->close();
}
Also, you could call only mysqli_query
if($mysqli->query($registerquery)){
....
}
It would be enough. The first call is better if you need to bind parameters and make several calls to the same query with different values.
Regards.-
I am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.