Data is not inserted in sql
When the password are not equal password are not equal is working. However when the password match no data is being updated in my sql.
Had already tried to import data to sql directly from the database and also confirmed that connection to the database is done.
<?php
$host= 'localhost';
$user= 'root';
$pass= '';
$db= 'newusers';
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$con=mysqli_connect($host,$user,$pass,$db);
if($con)
/*echo 'Connected Successfully to newusers database';*/
//if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check passwords are equal
if($_POST['password'] != $_POST['confirmpassword']){
echo 'Passwords are not equal';
}
if ($_POST['password'] == $_POST['confirmpassword']){
$sql = "INSERT INTO signup (Name, Surname, Email, Password) values ('$name', '$surname', '$email', '$password')";
}
?>
The expected result is that if the passwords are equal the data will be uploaded to mysql
You have several problems with your code. First, you do not have curly brackets in the right places to make sure your comparisons are in context. You should have curly brackets surrounding your connect check:
if($con) {
// your code here
}
Fixing that, you then need to execute your query. One way of doing it is with mysqli_query():
$host= 'localhost';
$user= 'root';
$pass= '';
$db= 'newusers';
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$con=mysqli_connect($host,$user,$pass,$db);
if($con) { // added opening bracket here
/*echo 'Connected Successfully to newusers database';*/
//if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check passwords are equal
//} added closing bracket here
if($_POST['password'] != $_POST['confirmpassword']){
echo 'Passwords are not equal';
} else { // you don't need another 'if' statement
$sql = "INSERT INTO signup (Name, Surname, Email, Password) values ('$name', '$surname', '$email', '$password')";
$result = mysqli_query($con, $sql); // execute the query
}
}
WARNING!
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. It is not necessary to escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
Always check for errors!
Add error reporting to the top of your file(s) right after your opening <?php tag error_reporting(E_ALL); ini_set('display_errors', 1);
Add error checking, such as or die(mysqli_error($con)) to your queries. Or you can find the issues in your current error logs.
Related
The form sends the data to this page. The print_r outputs everything I want to put into the table onscreen to check it's there, but nothing goes to the table. I have only managed to populate the table manually in phpmyadmin. Iam sorry if it's a really easy fix - I have only been learning for two weeks!
There are no errors showing in the logs or on screen when I run the page. The print_r does echo the array as it should be but nothing appears in the table
<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'users';
$username = ($_POST['username']);
$password = ($_POST['password']);
$companyName = ($_POST['companyName']);
$confirmPassword = ($_POST['confirmPassword']);
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (mysqli_connect_errno()) {
// If there is an error with the connection, stop the script and
display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
print_r ($_POST);
// Now we check if the data was submitted, isset() function will check
//if the data exists.
if (!isset($_POST['username'], $_POST['password'],
$_POST['companyName'])) {
// Could not get the data that should have been sent.
die ('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) ||
empty($_POST['companyName'])) {
// One or more values are empty.
die ('Please complete the registration form');
}
print_r ($_POST);
// We need to check if the account with that username exists.
if ($stmt = $con->prepare('SELECT id, password FROM phplogin WHERE
username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the
//password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the
// database.
if ($stmt->num_rows > 0) {
// Username already exists
echo 'Username exists, please choose another!';
} else {
// Username doesnt exists, insert new account
/* $stmt = $con->prepare('INSERT INTO phplogin (username, password,
companyName ) VALUES (?, ?, ?)');*/
if (false !== true){
/* We do not want to expose passwords in our database, so hash the
password and use password_verify when a user logs in.
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['$username'], $password,
$_POST['$companyName']);
$stmt->execute();*/
$sql = 'INSERT INTO phplogin (username, password, companyName )
VALUES ($username, $password, $companyName)';
echo 'You have successfully registered, you can now login!';
echo (" ".$password." ".$username." ".$companyName);
echo ' well done';
} else {
/* Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.*/
echo 'Could not prepare the new statement!';
print_r ($_POST);
}
}
}
$con->close();
?>
//$sql = 'INSERT INTO phplogin (username, password, companyName ) VALUES ($_POST[username], $password, $_POST[companyName])';
PHP thinks it should execute VALUES even though it is not any proper action. Use /* THIS IS COMMENT */ because it prevents stuff like this happening.
Also as a side note: Do not assign values in if statement. You can assign $stmt on its own line and just check
If($stmt === true) {}
Or
If($stmt !== true) {}
You get the point.
Also another side note is that you should prefer using PDO. It is alot of easier to handle and understand because of ts syntax and it makes OOP much much more easier. Mysqli is ok to use, but i personally do not recommend using it.
If I want to add content to the table using "INSERT INTO", I don't get an error message and the table is not filled. I'm new with PHP. explanations would be nice. The database runs on XAMPP.
I don't know what to try. I've already used another table, but it doesn't work. The user should have full access to the table. The names also match.
<?php
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if($passwort == $passwort2) {
echo "Password is correct.";
$db = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
} else if(!($passwort == $passwot2)) {
echo "Password is not correct";
} ?>
The variable $db actually contains information about the connection. You cannot insert a query into your database the way you are trying to
You can use $db (in your case) in order to check whether the connection has been correctly established or not and then if everything works correctly you can user mysqli_query() to inject the query into your database.
You can do it like so:
<?php
if(isset($_POST['submit'])){ //You have to check if your submit button is pressed
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if(!$db){
die('Connection could not be established! Check provided information');
}
if($passwort == $passwort2) {
echo "Password is correct.Inserting query now";
$query = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
$result = mysqli_query($db, $query); //keep $result for debugging purposes.
} else {
die("Password is not correct");
} //no need for else if as there are only 2 conditions.
if(!$result){ //check if query was successful.
die('Query Error');
}
echo "Query Updated successfully";
}
?>
This code is really simplistic and for testing purposes only.
I just wanted to show you the way you can send queries to your database. You better use other encryption techniques i.e. crypt() and of course functions like mysqli_real_escape_string() when retrieving data from users, in order to avoid potential injection attacks.
Check this post for more info about preventing injections.
Hope that helps.
I have a simple demo php scripts am trying out. i have been using the deprecated mysql_ extensions earlier, trying to migrate from that to mysqli_ is being overly buggy. when trying to use mysqli_real_escape_string php throws a variable not defined error cant seem to figure out why.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bridgoo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
//do stuff
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO bridgoo_users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $password, $email);
//generate password hash using blowfish algorithm
$password_hash = password_hash($_POST['password'], PASSWORD_BCRYPT, ["cost" => 9]);
$username = clean_input($_POST['username']);
$password = clean_input($password_hash);
$email = clean_input($_POST['email']);
function clean_input($input){
$input = htmlentities($input);
$input = htmlspecialchars($input,ENT_QUOTES);
$input = mysqli_real_escape_string($conn,$input);
return $input;
}
$stmt->execute();
$stmt->close();
$conn->close();
?>
php error Notice: Undefined variable: conn in C:\xampp\server1\htdocs\bridgoo\inc\register.php on line 24
The error about undefined variable $conn has to do with PHP variable scope, and other people have answered that.
But your code needs some other suggestions too.
You don't need to clean inputs at all if you use query parameters. That's the point of using query parameters: No need for mysqli_real_escape_string() because parameters are automatically safe.
In fact, you must not use mysqli_real_escape_string(), because your data will be inserted to your database literally with \' escaped apostrophes.
Simply put: SQL parameters and mysqli_real_escape_string() are mutually exclusive. Don't do both.
Also, it makes no sense to use htmlentities() or htmlspecialchars () at all for sanitizing SQL inputs, even if you use mysqli_real_escape_string() instead of parameters.
Those html-related functions are for HTML output only. They're very important for protecting your web app against XSS vulnerabilities, which is another unrelated web security risk you need to know about. But they're not needed for sanitizing SQL input.
Other comments:
It's confusing that you're re-using username and password variables for both the mysqli connection and the application data. There's no reason to re-use variables, they don't cost you anything.
Make sure the order of parameters in your INSERT matches the order of bind variables you pass to bind_param().
Always check the return value of prepare() and execute(). They return FALSE if they fail. If they fail, you must log the error and report to the user that the page didn't work.
I prefer to log the technical error message to the PHP error log
file, and report something more friendly to the user.
Get into the habit of keeping a window open to watch your PHP error log during development, it'll help you a lot.
Here's how I suggest you write your code:
<?php
$mysql_servername = "localhost";
$mysql_username = "root";
$mysql_password = "";
$mysql_dbname = "bridgoo";
$conn = new mysqli($mysql_servername, $mysql_username, $mysql_password, $mysql_dbname);
if ($conn->connect_error) {
error_log($conn->connect_error);
die("Sorry, a database error occurred.");
}
$stmt = $conn->prepare("
INSERT INTO bridgoo_users (username, password, email)
VALUES (?, ?, ?)");
if ($stmt === false) {
error_log($conn->error);
die("Sorry, a database error occurred.");
}
$stmt->bind_param("sss", $username, $password_hash, $email);
//generate password hash using blowfish algorithm
$password_hash = password_hash($_POST['password'], PASSWORD_BCRYPT, ["cost" => 9]);
$username = $_POST['username'];
$email = $_POST['email'];
if ($stmt->execute() === false) {
error_log($conn->error);
die("Sorry, a database error occurred.");
}
if ($stmt->affected_rows == 1) {
echo "Success!"
} else {
echo "Sorry, an unknown problem occurred, and your record was not saved."
}
Your clean_input function does not have access to your $conn variable, it lives in a different scope.
The easy solution would be to add the connection as a parameter to the function. Something like this:
<?php
...
$username = clean_input($_POST['username'], $conn);
$password = clean_input($password_hash, $conn);
$email = clean_input($_POST['email'], $conn);
function clean_input($input, $conn){
...
Wether that is the best or cleanest solution I'll leave in the middle, but it should work just fine.
You should pass $conn as parameter to your function clean_input;
$username = clean_input($conn, $_POST['username']);
$password = clean_input($conn, $password_hash);
$email = clean_input($conn, $_POST['email']);
function clean_input($conn, $input){
$input = htmlentities($input);
$input = htmlspecialchars($input,ENT_QUOTES);
$input = mysqli_real_escape_string($conn,$input);
return $input;
}
when I submit this form i have the same error message all the time . even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message :
Please enter a username and password .
so what is the problem . and i am sure about my fields on data base .
<?
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password)
{
$connect = mysql_connect("localhsost","root","adminffpass") or die("Couldent connet to database ");
mysql_select_db("login") or die("No data base found ");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
while ($row= mysql_fetch_array($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password==$dbpassword)
{
echo "Login successul .<a href='memeberarea.php'>Click to enter member area</a>";
$_SESSION['username'] = $dbusername;
}
else
echo "incorrect password ";
}
else
die ("That user name dosent exist");
}
else
die ("Please enter a username and password");
?>
Even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message
Typo: localhsost for one thing. Plus, you may not be able to use mysql_ functions, since they are deprecated and may not be available for you to use.
Plus, your POST arrays may be failing, so make sure your form is a POST method and that your elements bear the name attribute.
I.e.:
<input type="text" name="username">
etc.
if i write wrong name database i don't have any error . why ?"
Because, you're just using or die("Couldent connet to database ") instead of getting the real error mysql_error()
mysql_connect() => http://php.net/manual/en/function.mysql-connect.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Plus, instead of if ($username && $password) you should be using a conditional !empty() for your inputs.
It is also best to use proper and consistent bracing throughout your code.
else{
echo "incorrect password ";
}
etc.
Not doing so, could have adverse effects.
Storing a password hash
Using PDO with prepared statements and password_hash():
Pulled from ircmaxell's answer: https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You may print some information for yourself, so you could see, what's wrong. Change the following line:
echo "incorrect password ";
to something like this:
echo "incorrect password, u:[$username/$dbusername] p:[$password/$dbpassword]";
If you will see that detailed message, you will know, what's wrong.
EDIT: of course, don't left pwd printing in your final code :)
I have a simple user registration form and external connection script with some strange results.
The page register.php shows the form fine, however seems to display my entire connection string before the form?
It then throws up errors in relation to my connection variable '$dbcon' (I have commented the line at which this happens) Here is my register.php code:
<?php
session_start();
require "connect.php";
if (isset($_SESSION['username'])){
header("location: members.php");
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if ($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill all fields";
}
else
{
if ($pass != $rpass)
{
echo "Passwords do not match";
}
else
{
//This is where the errors are found
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user' ") or die ("Cannot query table");
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "This username is already taken";
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Cant insert data");
echo "Successfully added user!";
}
}
}
}
?>
And here is my connection file 'connect.php' (the $dbcon string is the one that prints out??)
$server = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'bodgett';
$dbcon = mysqli_connect($server, $user, $pass, $dbname)or die("Can not connect to Server.");
Specifically, the error is 'Notice: Undefined variable: dbcon in C:\webserver...\register2.php'
Can anyone suggest why is doesn't recognize this variable?
Probably a wrong filename (maybe file isn't called connect.php) OR wrong file extension? (html instead of .php)
I just copied all your code, and it works for me. Aswell I don't see php start and closing Tags.
I agree with #Xatenev. Also, you may want to consider using PDO for your database interactions, it's the most secure way. I found this very helpful: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Sorry if this seems irrelevant, just trying to help.
The connection file 'connect.php' is not enclosed within tags, hence not usable and explains why the text was simply printing out at the top of the page.
Check if mysqli extension is enabled
the code that generates $dbcon is inside a class or inside some function?
If yes, maybe you need to return or call it properly.