Troubleshooting 'undefined variable' error
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 tabl开发者_JS百科e 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.
精彩评论