I keep getting the following error Undefined variable: password on line 33 how do I correct this problem? So this error will stop showing.
Here is the php code.
$first_name = mysqli_real_escape_string($mysqli, $purifier->purify(htmlentities(strip_tags($_POST['first_name']))));
$password1 = mysqli_real_escape_string($mysqli, $purifier->purify(strip_tags($_POST['password1'])));
$password2 = mysqli_real_escape_string($mysqli, $purifier->purify(strip_tags($_POST['password2'])));
// Check for a password and match against the confirmed password:
if ($password1 == $password2) {
$sha512 = hash('sha512', $password1);
$password = mysqli_real_escape_string($mysqli, $sha512);
} else {
echo '<p class="error">Your password did not match the confirmed password!</p>';
}
//If the table is not found add it to the database
if (mysqli_num_rows($dbc) == 0) {
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"INSERT INTO users (user_id, first_name, password)
VALUES ('$user_id', '$first_name', '$password')");
}
//If the table is in the database update each field when needed
if ($dbc == TRUE) {
$dbc = mysqli_query($mysqli,"UPDATE users
SET first_name = '$first_name', password = '$password'
WHERE user_id = '$user_id'");
echo '<p class="changes-saved">Your changes have been saved!</p>';
}
There's only one place where a value is assigned to $password
if ($password1 == $password2) {
$sha512 = hash('sha512', $password1);
$password = mysqli_real_escape_string($mysqli, $sha512);
}
So, if the condition isn't met there will be no $password. And in that case it doesn't make sense to perform the UPDATE query anyway.
At the top define
$password = '';
then change the DBC check to
if ($dbc == TRUE && $password != ''){
As you can see, the database insert is done whether the first if() was true or false. If it's false ($password1 and $password2 doesn't match), $password won't be defined.
If this condition fails:
if ($password1 == $password2) {
$password will not get defined, raising an error in one of the lines it is used in later.
You don't raise an ERROR with an ELSE statement on the $password = ...... line so there is clearly an error there and it's not being defined. The top level if statement is fine, but the error is on the $password declaration line. Do you see how that works?
Instead of retrying the query if the insert fails (presumably because the user_id already exists - you've made that your primary key?), you could use the alternate INSERT INTO ... ON DUPLICATE KEY UPDATE syntax:
INSERT INTO users (user_id, first_name, password)
VALUES ('$user_id', '$first_name', '$password')
ON DUPLICATE KEY UPDATE
first_name=VALUES(first_name),
password=VALUES(password)
On a nitpicky point, your comments say "if the table is not found" and "if the table...". You're not dealing with table creation/modification - you're working with records that are stored in a table.
Related
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' password='$2y$10$QV6'' at line 1
I'm fairly new to server-side scripting, please take a look at the syntax below and align it where neccesary or assist me with an alternative solution regarding this error.
<?php
$tbl_name = "user_accounts"; // Table name
// Connect to server and select database.
$mysqli = new mysqli("localhost", "root", "", "ems");
// email and password sent from form
$email = $_POST['email'];
$password = $_POST['password'];
if (!$_POST['email'] | !$_POST['password']) {
print "<script>alert('Your email & password do not match!');
javascript:history.go(-1);</script>";
exit;
}
// To protect MySQL injection
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysqli_real_escape_string($mysqli, $email);
$password = mysqli_real_escape_string($mysqli, $password);
$hash = password_hash($password, PASSWORD_BCRYPT);
$sql = "SELECT account_type, email and password FROM $tbl_name WHERE email='$email', password='$hash'";
$mysqli_result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
// Mysql_num_row is counting table row
$count = mysqli_num_rows($mysqli_result);
// If result matched $email and $password, table row must be 1 row
if ($count == 1) {
// Register $email, $password and redirect to file "index.php"
$_session['email'] = $email;
$_session['password'] = $password;
//Checking User Account Type
if ($_SESSION['account_type'] == 'user') {
header("location:user.php");
} else if ($_SESSION['account_type'] == 'admin') {
header("location:admin.php");
} else {
print "<script>alert('This Account Doesn't Exist!');
javascript:history.go(-1);</script>";
exit;
}
} else {
echo "Wrong email or Password";
}
?>
A few problems here:
You do not separate conditions using a comma, instead you use AND
You cannot check a password hash like that as it will be different every time as the salt is generated dynamically. Instead you should get the password from the row and use the password compare function password_verify().
You should use a prepared statement instead of escaping your input to avoid sql injection.
password_hash generates every time a new hash, even with the same value.
Your Query should only query for the email and then execute password_verify($password, $passwordFromQuery).
More about password_hash() here and about password_verify() here
I woud recommend using prepared statements. Read more about it here
Try this
$sql="SELECT account_type, email and password FROM $tbl_name WHERE email='".$email."', password='".$hash."'";
$mysqli_result=mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
I am coding a "social media site" for a class project, and I am having trouble in one section.
When first registering an account, the user must enter a username and password, and click a submit button. PHP code checks the inputs to make sure they're all valid and that there will not be any duplicates, and if everything passes, it adds in the username and password into a SQL table called "users". Users has 3 columns: username, password, and userID. userID is the primary key.
Once that process is completed, we redirect to a separate page, where the user can enter more personal information, such as first and last name, city, country, etc. This table, called "userInfo" has the columns: firstName, lastName, emailAddress, address, city, country, and userID. userID, once again, is the primary key.
What I'm trying to figure out is how to match the two user ID's in an insert statement. I have a form that gathers all the required information, but I am not sure how to set up the SQL query to make sure that users.userID matches userInfo.userID.
Here's my PHP for users (initial registration)
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
if(isset($_POST['submit'])){
// Get inputs
$username = $_POST['user'];
$password = $_POST['password'];
// Clean inputs and encrypt password
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$password = md5($password);
// Check username not empty
if (empty($username)) {
$error = "true";
$errorMessage = "Please enter a value for your username";
}
// Check username does not already exist
$checkUserQuery = "SELECT username FROM users WHERE username = '$username'";
$checkResult = $conn->query($checkUserQuery);
if($checkResult->num_rows > 0) {
$error = "true";
$errorMessage = "This username already exists";
}
// Username does not exist, add to database
else {
$insertUserQuery = "INSERT INTO users (username, password) VALUES('$username', '$password')";
$insertResult = $conn->query($insertUserQuery);
$_SESSION['username'] = $username;
header("Location: userInfo.php");
}
}
?>
Here's my PHP code so far for userInfo:
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
// Get inputs
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$emailAddress = "fakeEmailAddress#fakeyfakefake.com";
$address = $_POST['address'];
$city = $_POST['city'];
$country = $_POST['country'];
// Clean inputs
$firstName = mysqli_real_escape_string($conn, $firstName);
$lastName = mysqli_real_escape_string($conn, $lastName);
$address = mysqli_real_escape_string($conn, $address);
$city = mysqli_real_escape_string($conn, $city);
$country = mysqli_real_escape_string($conn, $country);
// Validate Inputs (Only validating first and last name, location entries are not required)
if(empty($firstName) || empty($lastName)) {
$error = "true";
$errorMessage = "Please enter your first AND last name";
}
else {
}
}
?>
Apologies if this is super messy. Databases are NOT my strong suit lol.
Many thanks to anyone who can help!
You'll want to get the mysqli_insert_id for your insert into the users table and pass that along (potentially via your $_SESSION) for creation in userInfo.
<?php
session_start();
//Obtain data from register page
$email = $_POST['email'];
$password = $_POST['password'];
//Check to see user has input
if ($username !='' || $password !='' || $confirmpassword !='' || $email !='') {
if ($password1 == $password2) {
// connect to database
$db = new mysqli('removed', 'removed','removed' ,'removed');
// Check to see if connection was successful
if ($db->connect_errorno) {
die ('Sorry, we are having some issues with our database. We should be back online soon.');
}
// Prepare statement
$query = "INSERT INTO `database`.`users` (
`id` ,
`minecraftusername` ,
`email` ,
`password` ,
`joined` ,
`rank`
)
VALUES (
NULL , ?, ?, ?, NOW( ) , '1'
);";
$stmt=$db->prepare($query);
$stmt->bind_param('sss', $username, $email, $password);
//Execute query
$stmt->execute();
// header("Location: ../default.php");
echo 'You have successfully registered an account!';
} else {
// header("Location: ../default.php");
echo 'Passwords do not match.';
}
} else {
// header("Location: ../default.php");
echo 'Please fill out all the fields';
}
?>
When you try to register, it does echo the registered successfully message, but when I go to phpmyadmin the number of rows hasn't changed.
I am really not sure what errors I have made.
Any help would really be appreciated.
$password = $_POST['password'];
Here you set only $password, but then you expect other variables to exist,
if ($username !='' || $password !='' || $confirmpassword !='' || $email !='') {
if ($password1 == $password2) {
$confirmpassword and $password1 and $password2 are never set. Noted in comments by #RobP and #Ali.
You connect to the database only if $password1 == $password2, and you only die() in that block as well. So you might easily skip that whole block, and not die(), and go on to try to run the INSERT without having connected to the database. Noted in comment from #Erico.
if ($db->connect_errorno) {
It's connect_errno, not "connect_errorno". If that block of code were run, it would generate a notice: PHP Notice: Undefined property: mysqli::$connect_errorno. So this proves that your code to connect to the database was never run.
$stmt=$db->prepare($query);
$stmt->bind_param('sss', $username, $email, $password);
$stmt->execute();
You should always check the return value of prepare() and execute(). They return false if there is any problem with the statement. Like if you had a syntax error, or violated a unique constraint or something. Right now your INSERT might be failing but you'll never know. Also noted in a comment by #sanketh.
Or else you can set mysqli_report(MYSQLI_REPORT_STRICT) to raise exceptions if there's an error. Then you don't need to write code to check the return values, because your script will die if there's any mysqli error. You have to set this report mode before you connect to the database.
Also, you never set a value for $username.
I have an issue with my PHP code for a registration form on my website. Some of the code doesn't get executed when the form is submitted.
if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "") {
$con = mysqli_connect("localhost","root","","login")or die("Can't connect to database");
$user = $_POST['user'];
$pass = $_POST['pass'];
$name = $_POST['fname'];
$email = $_POST['email'];
$pwd = crypt('$pass', '$user');
$pwd = md5($pwd);
$tblname = "users";
$flp="INSERT INTO $tblname (Name, Username, Password, Email Address)
VALUES
('$name','$user','$pass','$email')";
$res = mysqli_query($con, $flp)or die("Can't insert to table");
if ($res) {
$complete = "Registered successfully please log in to continue";
} else {
echo "error";
}
}
Everything works fine until it gets to the line starting $flp="INSERT INTO...
Can anyone assist in helping me debug this code, also, please don't link to already written code I want to be able to use this code.
EDIT:
I changed a line to purposely cause an error so I know PHP is reading the line and it does give me the syntax error for the line starting $res=mysqli_...
"Parse error: syntax error, unexpected '$res' (T_VARIABLE) in C:\XamppNew\htdocs\site\regusr.php on line 85"
I removed the semi-colon at the end of the Insert line just to get the error.
EDIT:
I've managed to isolate the problem to the start of the if statement. It seems to be that the line doesn't treat each error as having no content. However, if the error exists it will be displayed on the page next to the form and no such error gets displayed.
Try this:
<?php
//if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "")
//{
// Connect to DB
$mysqli = new mysqli("localhost", "root", "", "login");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Parse Input
$user = $mysqli->real_escape_string($_POST['user']);
$pass = $mysqli->real_escape_string($_POST['pass']);
$pwd = md5(crypt('$pass', '$user'));
$name = $mysqli->real_escape_string($_POST['fname']);
$email = $mysqli->real_escape_string($_POST['email']);
// Insert Record
if ($mysqli->query("INSERT INTO users (`Name`, `Username`, `Password`, `Email Address`) VALUES ('$name', '$user', '$pwd', '$email')")) {
printf ("New user has id %d.\n", $mysqli->insert_id);
} else {
printf("Failed to insert row: %s\n", $mysqli->error);
}
// Close DB Connection
$mysqli->close();
//}
?>
You need to quote (with backticks) your column name Email Address since it has a space in it.
Use backticks in Email Address field because it has space.
$flp="INSERT INTO $tblname (`Name`, `Username`, `Password`, `Email Address`)
Try this ..........
$flp="INSERT INTO $tblname (Name, Username, Password, EmailAddress)
VALUES
('".$name."','".$user."','".$pass."','".$email."')";
I'm trying to INSERT INTO a mySQL database and I'm getting this error on:
if (mysql_num_rows($login) == 1){
Here is the php, The php does add the user to the database. I can't figure it out.
<?
session_start();
require("config.php");
$u = $_GET['username'];
$pw = $_GET['password'];
$pwh = $_GET['passwordhint'];
$em = $_GET['email'];
$zc = $_GET['zipcode'];
$check = "INSERT INTO family (loginName, email, password, passwordhint, location) VALUES ('$u', '$pw', '$pwh', '$em', '$zc')";
$login = mysql_query($check, $link) or die(mysql_error());
if (mysql_num_rows($login) == 1) {
$row = mysql_fetch_assoc($login);
echo 'Yes';exit;
} else {
echo 'No';exit;
}
mysql_close($link);
?>
Thanks,
You're doing an INSERT query, so $login won't contain any result set, it's either true or false.
So instead of this:
if (mysql_num_rows($login) == 1) {
You can either do this:
if (mysql_affected_rows($link) == 1) {
Or this:
if ($login == true) {
Also, you don't need this line anymore:
$row = mysql_fetch_assoc($login);
Unrelated to your question, but a very important thing to remember when doing SQL queries: you'll need to escape all your $_GET data with mysql_real_escape_string() just before inserting, so as to prevent SQL injection.
mysql_query() returns True/False for INSERT, UPDATE, DELETE, DROP...