Error in SQL syntax: Update query error - php

I working in my login form and 1 requirement is to have a change password. For some reason I'm always getting this error-> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users' SET 'password'=SHA1('123') WHERE 'email'='mac.pader#yahoo.com'' at line 1.
<?php
$page_title = 'Change Your Password';
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('userdb');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
//Start the Session
session_start();
if (isset($_POST['email']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$email = $_POST['email'];
$password = $_POST['password'];
// Check for a new password and match
// against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your new password did not match the confirmed password.';
} else {
$np = $_POST['pass1'];
}
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT userid FROM `users` WHERE email='$email' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['email'] = $email;
$_SESSION['np'] = $np;
//$row = mysqli_fetch_array($result, MYSQLI_NUM);
// Make the UPDATE query:
$query = "UPDATE 'users' SET 'password'=SHA1('$np') WHERE 'email'='$email'";
$result = mysql_query($query) or die(mysql_error());
echo"$np and $email";
$count = mysql_num_rows($result);
if ($count == 1){
}else{
// Public message:
echo '<h1>System Error</h1>
<p class="error">Your password could not be changed due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
// Include the footer and quit the script (to not show the form).
//include ('includes/footer.html');
exit();
} else { // Invalid email address/password combination.
echo '<h1>Error!</h1>
<p class="error">The email address and password do not match those on file.</p>';
echo"$num";
}
}
//3.1.4 if the user is logged in Greets the user with message
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo'<h1>Thank you!</h1>
<p>Your password has been updated. You can now Log-In!</p><p><br /></p>';
}else{
echo'try again';
}
mysql_close($select_db);
exit();
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
// Check for a new password and match
// against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your new password did not match the confirmed password.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your new password.';
}
?>

You have to use backticks arround table and field names not single quotes:
UPDATE `users` SET `Password`=SHA1('$np') WHERE `email`='$email'
Also you should not use mysql_* functions because this API is depricated.

Related

How to check if a User already exists in a MySQL database and if the password matches stored hashed password [duplicate]

This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie

Cannot find mistake in PHP + MySQLi register page

I am trying to build a register page using PHP and MySQLi. However, it doesn't work, and I cannot understand the issue. It was previously with no MySQL improved syntax. There is just an empty page in browser.
<?php
include ("bd.php");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['login']))
{
$login = $_POST['login'];
if ($login == '')
{
unset($login);
}
}
if (isset($_POST['password']))
{
$password=$_POST['password'];
if ($password =='')
{
unset($password);
}
}
if (empty($login) or empty($password))
{
exit ("You have entered not all of the information, go back and fill in all the fields!");
}
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
$login = trim($login);
$password = trim($password);
$myrow = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
if (!empty($myrow['id']))
{
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2=mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2=='TRUE')
{
echo "You have successfully signed up!";
}
else
{
echo "Failed to sign up";
}
?>
bd.php:
<?php
$db = new mysqli ("localhost","root","root","kotik");
?>
<?php
include ("bd.php");
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$login = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = htmlspecialchars($password);
if (empty($login) || empty($password)){exit ("You have entered not all of the information, go back and fill in all the fields!");}
$res = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
$myrow = mysqli_fetch_assoc($res);
if (!empty($myrow['id'])) {
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2 =mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2 == true)//use true not 'True' because 'True' is a string
{
echo "You have successfully signed up!";
}
else {
echo "Failed to sign up";
}
?>
EDIT: You should use mysqli_fetch_assoc to get an associative array which corresponds to the fetched row or NULL if there are no more rows.
You cannot use the variable $myrow like this:
$myrow['id']
You need to get the row then you can treat it like an array. It would look something like this:
$row = $myrow->fetch_row()
$row['id']
this gets the first row of the results of the query. If the query returns multiple results you can use something like this:
while($row = $myrow->fetch_row()) {
$rows[]=$row;
}
Then you use $rows as a normal array and get the individual rows 1 by 1 in a for loop, then you can use the same format:
$temp = $rows[0];
$temp['id']

Mysqli not importing letters

I am trying to make a sign up PHP for my website and I am trying to convert an old script that used mysql to mysqli. I am having a problem where that when I type any letters (abc) into any of the text fields the data is not imported into the database. If I use numbers (123) in all of the boxs it works and gets imported fine. I have tried mixing it up with some letters for the username and numbers for the password to see if only one text box was causing the problem but ANY box that have a letter in will cause the script not to work.
This is my PHP script:
<?php
$mysqli = new mysqli("localhost","root","","users_db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Define username */
if(isset($_POST['username'])){
$username = $_POST['username'];
}
/* Define email */
if(isset($_POST['email'])){
$email = $_POST['email'];
}
/* Define password */
if(isset($_POST['password'])){
$password = $_POST['password'];
}
/* Define cpassword */
if(isset($_POST['cpassword'])){
$cpassword = $_POST['cpassword'];
}
if (trim($username) == ''){
echo 'No username entered.';
exit();
}
if (strlen($username) <= 5 || strlen($username) >= 30){
echo 'Username needs to be between 5 and 30 characters';
exit();
}
if (trim($email) == ''){
echo 'No email entered.';
exit();
}
if (trim($password) == ''){
echo 'Invalid password.';
exit();
}
if ($password != $cpassword){
echo 'Passwords do not match';
exit();
}
$run = mysqli_query($mysqli, "SELECT * FROM users WHERE username='$username'");
if (mysqli_num_rows($run)>0){
echo 'Username already exists';
exit();
}
$import = "INSERT INTO users (username,email,password) VALUES ($username,$email,$password)";
if (mysqli_query($mysqli, $import)){
echo 'Registration Successful';
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
$id = $row['id'];
mkdir("../users/" . $id, 0777, true);
fopen("../users/" . $id . "/" . "New User.txt", "w") or die("Unable to create file");
}else{
echo 'Failed to import';
}
?>
I am very new to PHP and mysqli so don't be too harsh if I am doing something stupid :)
Thanks Fred -ii- putting quotes around ($username,$email,$password) worked for me and now everything works. I will also fix the other problems suggested above.

Check if username exists in mysql table via php? [duplicate]

This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie

PHP Login Script result resource [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
When typing in a username and password im getting the error
mysql_num_rows(): supplied argument is not a valid MySQL result resource
IT IS SAYING I HAVE NO DATABASE SELECTED ...
I was wondering what this error means. Could it be a problem connecting to the database or is it a syntax problem. here is the code for the username and password
$query = mysql_query("SELECT * FROM Users WHERE username = '$user'");
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$dbid = $row['id'];
$dbuser = $row['username'];
$dbpass = $row['password'];
$dbactive = $row['active'];
if($password == $dbpass){
if($dbactive == 1){
//set session info
$_SESSION['userid'] = $dbid;
$_SESSION['username'] = $dbuser;
echo "You have been logged in as <b>$dbuser</b> Click here to go to member page.";
}else
echo "You must activate your account to login.";
}else
echo "You did not enter the correct password.";
}else
echo "The username you entered was not found.";
}
}else
echo "You must enter your username.";
}
The problem is in the $query line. the first line
The most likely cause is that your not connected or not selecting the correct database, you should use mysql_error() to track this down. But I also see some logic confusion, here is an example of a super simple login, checks should be made on the database query, not by PHP (plus there is no need to store the password anywhere other then in the database). You should also hash user account passwords & escape user input, hope it helps..
<?php
session_start();
$db = mysql_connect('host','uesr','pass') or die(mysql_error());
mysql_select_db('database') or die(mysql_error());
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['username']) && isset($_POST['password'])){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT `username`,`active`
FROM Users
WHERE username ='$user' && password='$password' && active=1
LIMIT 1");
if(mysql_num_rows($query) == 1){
//Log in user found
$row = mysql_fetch_assoc($query);
$_SESSION['username'] = $row['username'];
$_SESSION['active'] = $row['active'];
$_SESSION['logged_in'] =true;
header('Location: ./members.php');
die;
}else{
//failed login
$_SESSION['logged_in']=false;
$_SESSION['log_in_error']='Fail!! Account not active or incorrect login information!';
header('Location: ./login.php');
die;
}
}
?>
Like zerkms suggested, try printing the mysql_error() to screen.
Something like:
$query = mysql_query("your_query here");
if(!$query){
echo 'Error! : ' . mysql_error();
}
http://www.php.net/manual/en/function.mysql-error.php
Before you do all of this, make sure you are connected to a database. For example:
http://php.net/manual/en/function.mysql-connect.php
$link = mysql_connect('localhost', 'database_user', 'database_password');
if(!$link){
die('Could not connect: ' . mysql_error());
}
//select your db
mysql_select_db("YOUR_DB_NAME",$link);
$result = mysql_query("SELECT * FROM Users WHERE username = '$user'");
if(!$result){
echo 'Error! ' . mysql_error();
}

Categories