Update accounts table with the user preferences in PHP - php

I have the following SQL database:
CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
'experience' enum('Beginner', 'Intermediate', 'Advanced) NULL, Default Beginner,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `accounts` (`id`, `username`, `password`, `email`, 'experience') VALUES (1, 'test', '$2y$10$SfhYIDtn.iOuCW7zfoFLuuZHX6lja4lF4XA4JqNmpiH/.P3zB8JCa', 'test#test.com');
And besides this, I also have a registration form that will populate the database with the given values using a registration form.
And the following HTML form which will be the update form:
<div class="card bg-light">
<div class="register">
<h1>Update My Preferences</h1>
<form action="update_preferences.php" method="post" autocomplete="off">
<div class="form-group input-group">
<select name="new_experience" class="form-control">
<option selected="">Change Investment Experience</option>
<option>Beginner</option>
<option>Intermediate</option>
<option>Advanced</option>
</select>
</div>
<!-- form-group end.// -->
<label for="username">
<i class="fas fa-user"></i>
</label>
<input type="text" name="new_username" value="<?=$_SESSION['name']?>" id="username">
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="new_password" placeholder="" value="" id="password">
<label for="email">
<i class="fas fa-envelope"></i>
</label>
<input type="email" name="new_email" value="<?=$email?>" id="email">
<input type="submit" value="Update">
</form>
</div>
</div>
I manage to add the following code for update_preferences.php but then I got stuck with the error "Could not prepare statement!
Fatal error: Call to a member function close() on boolean in /home2/freemark/public_html/update_preferences.php on line 71":
<?php
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogindb';
// 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());
}
// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['new_experience'], $_POST['new_username'], $_POST['new_password'], $_POST['new_email'])) {
// 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['new_experience']) || empty($_POST['new_username']) || empty($_POST['new_password']) || empty($_POST['new_email'])) {
// One or more values are empty.
die ('Please complete the registration form');
}
$new_exp_level=$_POST['new_experience'];
$new_username=$_POST['new_username'];
$new_password=$_POST['new_password'];
$new_email=$_POST['new_email'];
// We need to check if the account with that username exists.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
if (!filter_var($_POST['new_email'], FILTER_VALIDATE_EMAIL)) {
die ('Email is not valid!');
}
if (preg_match('/[A-Za-z0-9]+/', $_POST['new_username']) == 0) {
die ('Username is not valid!');
}
if (strlen($_POST['new_password']) > 20 || strlen($_POST['new_password']) < 5) {
die ('Password must be between 5 and 20 characters long!');
}
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['new_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
if ($stmt = $con->prepare('UPDATE accounts SET $new_exp_level = ?, $new_username = ?, $new_password = ?, $new_email = ? WHERE id = ?')) {
// 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['new_password'], PASSWORD_DEFAULT);
$stmt->bind_param('ssss', $_POST['new_username'], $password, $_POST['new_email'], $_POST['new_experience']);
$stmt->execute();
header('Location: login.html');
exit();
echo 'You have successfully registered, you can now login!';
}
else {
// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
echo 'Could not prepare statement!';
}
}
$stmt->close();
} else {
// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
echo 'Could not prepare statement!';
}
$con->close();
?>

Not sure what you stuck at but query for multiple fields updating looks like this:
$sql = "UPDATE accounts SET field1 = ?, field2 = ?, field3 = ? WHERE id = ?";
// binding values can be done something like
$stmt->bind_param('ssss', $variable1, $variable2, $variable3, $_SESSION['id']);
Also, read this page about password hashing and never store plain passwords.

if(empty($new_password){
is missing a closing bracket
if(empty($new_password) *)*{
since your update your error is here:
else {
// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
echo 'Could not prepare statement!';
}
}
$stmt->close(); <-- this is line 71 (after pasting your code into my IDE so i assume it's the full content)
so $stmt does not have a method called 'close'. this should, I think, say $con->close();
really, if an error is point you to an exact line with an exact message, it shouldn't be too difficult to debug
-- update--
Also i just noticed you're not binding enough parameters
UPDATE accounts SET $new_exp_level = ?, $new_username = ?, $new_password = ?, $new_email = ? WHERE id = ? //<-- 5 placeholders
$stmt->bind_param('ssss', $_POST['new_username'], $password, $_POST['new_email'], $_POST['new_experience']); // <-- 4 params

Related

By using php mysql create the table and retrieve the data,How to modify the data displayed in html?

I am new to the html and php, I had created the database in mysql by using the html and php,i had inserted values and retrieve the data from mysql to php,how can i modify the table means deleting the row,updating the row.
Below is my html code:
<html>
<head>
<title>STUDENT_DATA</title>
</head>
<body>
<form action="1.php" method="post" >
<center>
sname: <input type="text" name="sname" required><br></br>
sno:<input type="text" name="sno"><br></br>
marks:<input type="text" name="marks"><br></br>
class:<input type="text" name="class"><br></br>
phno:<input type="text" name="phno" onkeypress='return event.charCode >
= 48 && event.charCode <= 57'><br></br>
DOB:<input type="date" placeholder="DD-MM-YYYY"
required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}"
name="DOB"/><br></br>
<button>submit</button></br>
</center>
</form>
Below is my PHP code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$sname=$_POST['sname'];
$sno=$_POST['sno'];
$marks=$_POST['marks'];
$class=$_POST['class'];
$phno=$_POST['phno'];
$DOB=$_POST['DOB'];
if($sname!='' and $sno!='' and $marks!='')
{
$query = mysql_query("insert into hello1(sname, sno, marks, class, phno ,
DOB)
values ('$sname', '$sno', '$marks', '$class','$phno','$DOB')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else
{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
mysql_close($connection);
?>
Is there any one to help me?
Updation;
$query = "UPDATE hello1 SET column_name_1=value_1,column_2=value_2,... WHERE some_column=some_value;
$query = mysql_query($query);
Deletion
$query = "DELETE FROM hello1 WHERE some_column=some_value;
$query = mysql_query($query);
This is for ur comment :
take data from ur form, keep a unique constraint to use in where condition,
for example if the data u need to modify is "password" for username='admin', what u have to do is,
$query = "UPDATE hello1 SET password=$new_pw WHERE username=admin;
here $new_pasword should contain ur new pasword and username should be unique (if not, it will update all the rows with username as 'admin')
This is with reference to the code which u have sent to me.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
You cannot update like this because you haven't specified the required row(s) for updation.
for that what u have to do is just add a where condition.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
This means, u are updating name, adress and rollnumber of ur table venu, WHERE 'id' of
your row = 'the required one'
Hope this helps :)

Secured Mysqli Statement to avoid SQL Injection but the form sends only blank Info

Good day! I'm having a problem in using $stmt to avoid SQL Injection on my database. Whenever I click submit, the form only sends blank user and password but there's an multiple id that has been created. :( Is there anyone who can help me through this?
Here's my Form
<form action="index.php" method="POST">
<h1>Create Username</h1>
Username: <input type="text" name="user"><br />
Password: <input type="password" name="pass"><br />
<input type="submit" value="Submit">
</form>
And my for Action is here.
$name = $_POST['user'];
$password = $_POST['pass'];
//$mysqli is my connection stored at my config.php
if ($stmt = $mysqli->prepare("INSERT INTO users (user, password) VALUES (?, ?)")) {
// Bind the variables to the parameter as strings.
$stmt->bind_param("ss", $name, $password);
// Execute the statement.
$stmt->execute();
// Close the prepared statement.
$stmt->close();
}
if($stmt){
echo "Data Sent";
}else{
echo "Error in Sending";
}
Mysqli doesn't quote like PDO. Do it manually.
INSERT INTO `users` (`user`, `password`) VALUES ('?', '?')
For validating user, if you are using password_hash() and password_verify() functions of php select them first and check password.
If you're using md5, sha1, ... first md5 the input password from post, then
select * from `users` where `username`= '...' AND `password` = 'Here it should be the hashed pw';

How to prevent username duplicates in mySQL (PHP) [duplicate]

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
This is how my users register for database, but my question is: How can I prevent the database from having copies of the same username, or in other words, how can I prompt to the user that "Your username already exists" if their username exists in the database.
<?php
$error = ""; // error
$GoodJob = "";
//When submit button is pressed, send data.
if(isset($_POST['submit'])){
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
$error = "<br>Please insert only letters or numbers.";
}else{
// Define username, firstname, lastname, email and password.
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Define database information
$hostnameV = "***";
$usernameV = "***";
$passwordV = "***";
$databaseV = "***";
//connection to the database
$connection = mysql_connect($hostnameV, $usernameV, $passwordV)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseV,$connection)
or die("Could not select company");
// To protect MySQL injection for Security purposes
$username = stripslashes($username);
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$email = stripslashes($email);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
// SQL query to send information of registerd users
# FORMULA: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
$query = mysql_query("INSERT INTO `company`.`users` (`id`, `username`, `firstname`, `lastname`, `email`, `password`)
VALUES (NULL, '$username', '$firstname', '$lastname', '$email', '$password')", $connection);
//close the connection
mysql_close($connection);
} // end if statement
***
}
?>
<div id="main">
<div id="login">
<h2>REGISTER</h2>
<form action="" method="post">
<input id="name" name="username" placeholder="Pick a username" type="text">
<input id="name" name="email" placeholder="Your email" type="text">
<input id="name" name="firstname" placeholder="firstname" type="text">
<input id="name" name="lastname" placeholder="lastname" type="text">
<input id="password" name="password" placeholder="Create a password" type="password">
<input name="submit" type="submit" value=" REGISTER ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
I would first start by not using the mysql_* functions as they are deprecated and switch to PDO as it works correctly.
To answer your question, you should simply query the database for the username, if it exists, tell the user.
Before the Insert, using PDO and prepared statements.
$stmt = $dbh->prepare('SELECT count(*) FROM user WHERE username = ?');
$stmt->execute(array($username));
$res = $stmt->fetch(PDO::FETCH_NUM);
$exists = array_pop($res);
if ($exists > 0) {
// tell the user it already exists.
} else {
// carry on with your insert.
}
As others have suggested, making the username unique should also be done. I wouldn't write my code to fail though when trying to insert a duplicate username, I would still test if it exists.
So to provide a bit more clarity, in reference to the below comments about using exceptions, here's why I wouldn't write my code to throw an exception if someone enters a username that is already taken. Exceptions, in my opinion, should be exceptions. That means that something exceptional happened. Someone entering a username that is already taken, I consider that to be a normal operation of the application and it should be handled in a normal non-exceptional fashion. If however, someone entered a valid username and between the time that I checked that it was not taken and when I'm running my insert, someone else grabbed that username (in that 2 millisecond timeframe), that would be an exception and I would handle it. To the user, that "exception" would look exactly the same, but in my code it would be handled as an exception.
So that's why I wouldn't just write my code to do an insert that throws an exception when someone enters a username that is already taken. I would check whether it's taken or not and then insert it, throwing an exception if that username was snagged between the time I checked and when it was inserted. I think that's good application design and proper use of exceptions. Others can disagree, but that's how I would do it. Exceptions should be exceptional, not part of the normal course of doing business.
You can set a validation for checking the username is exist or not.
<?php
function checkUserExist($username){
$checkExist = "SELECT username from userTable WHERE username ='" . $username . "'" or die(mysql_error());
mysql_query($checkExist);
if($checkExist > 0){//That means username is existed from the table
return true;
}else{//username isn't exist
return false;
}
}
if(checkUserExist($username)){//function return true
echo "username is already exist, please change.";
}else{
//Insert the user info into db
}
This is an example for checking the username by using function with mysql_query, you can also use PDO to implement it, Cheers!

How add user data to an already registered user

I am very new to the database world. In my registration process a user has to give the values, which are required (e-mail and password). Now when already registered and logged in, I want to give the user the opportunity to add the not required info to his row in my database.
EDIT2:
Here is an updated version of the relevant part of my code. It is obviously not working, I would be beyond happy, if you could point me into the right direction once again! Thank you!!
<?php
require_once 'config.php';
require_once 'database_connection.php';
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$URL= trim($_REQUEST['URL']);
//Get the logged in user's ID
$user_id = $_REQUEST['user_id'];
//Select the logged in user
$select_query = "SELECT * FROM users WHERE user_id = " . $user_id;
//Update the user's row
$update_sql = sprintf("UPDATE users (first_name, last_name, URL) " .
"VALUES ('%s', '%s','%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($URL));
//Parameterized queries
$stmt = $dbh->prepare("UPDATE `users` SET (first_name, last_name, URL) VALUES (:first_name, :last_name, :URL) WHERE (user_id = :user_id)");
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
$stmt->bindParam(':URL', $URL);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
mysql_query($select_query, $update_sql, $stmt)
or die(mysql_error());
header("Location: show_user.php?user_id=" . mysql_insert_id()); //where to redirect
exit();
?>
The form, which should execute the above code but does not:
<body>
<!-- start register -->
<div id="register">
<form name="completeProfileForm" action="/php/complete_user.php" method="POST" enctype="multipart/form-data">
<h2>Complete your information:</h2>
<!-- first name -->
<label>First Name</label>
<input name="first_name" id="first_name" type="name" placeholder="Enter your first name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your firstname'" />
<!-- last name -->
<label>Last Name</label>
<input name="last_name" id="last_name" type="name" placeholder="Enter your last name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your last name'" />
<!-- website-->
<label>Website</label>
<input name="URL" id="URL" type="text" placeholder="Enter your website domain" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your website domain'" />
<!-- register button -->
<input type="submit" id="submitButton" class="button" value="Complete my profile" />
</form>
</div> <!-- end register -->
</body>
Last but not least the error message:
Notice: Undefined index: user_id in C:\xampp\htdocs\php\complete_user.php on line 10
Notice: Undefined variable: dbh in C:\xampp\htdocs\php\complete_user.php on line 20
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\php\complete_user.php on line 20
Thank you so much for all the good input!
Your Updatescript should work as far as i know if you chain the text and variables together correctly.
The concatenation in PHP works with the dot '.'.
So your SQL Statement must look like
$update_sql = ("UPDATE `users` SET `first_name` = ".$first_name.", `last_name` = ".$last_name.", `user_type` = ".$user_type.", `URL` = ".$URL." WHERE `user_id` = ".$user_id);
BUT you shouldn't just use the input from user in your querys. See more about SQL Injection here!
You must escape the user input!
You can do this with certain functions, these are two of them:
$user = $mysqli->real_escape_string($user);
$user = htmlentities($user);
Also you shold use parameterized queries. This is an simple example with the first parameter of your Update Query, just add the rest of your code in the same pattern after you escaped it!:
$stmt = $dbh->prepare("UPDATE `users` SET (firstname) VALUES (:firstname) WHERE (userid = :userid)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':userid', $userid);
$stmt->execute();
Further you are using mysql_insert_id() which Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). More Information about that in the official documentation.
But MySQL will only generate a ID if you are INSERTING a new User in your case, but your updating a existing one. So no ID will be returned. You need to get the ID from the User manually with a SELECT after the UPDATE and than add this ID to your redirect.
EDIT2
You can, and should to save traffic, put your
$stmt = $dbh->prepare("UPDATE `users` SET (first_name) VALUES (:first_name) WHERE (user_id = :user_id)");
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
$stmt = $dbh->prepare("UPDATE `users` SET (last_name) VALUES (:last_name) WHERE (user_id = :user_id)");
$stmt->bindParam(':last_name', $last_name);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
$stmt = $dbh->prepare("UPDATE `users` SET (URL) VALUES (:URL) WHERE (user_id = :user_id)");
$stmt->bindParam(':URL', $URL);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
in a single statement
$stmt = $dbh->prepare("UPDATE `users` SET (first_name, last_name, URL) VALUES (:first_name, :last_name, :URL) WHERE (user_id = :user_id)");
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
$stmt->bindParam(':URL', $URL);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
I'm going through your Error messages and tell you what they mean, i think that should be enough so that you can fix them
Notice: Undefined index: user_id in C:\xampp\htdocs\php\complete_user.php on line 10
This means that your $_Request['user_id'] doesn't find a keyuser_id`. Watching your HTML, this is a bit complicated. You need to save the user_id in a Session when he's logging in and access it then with $_SESSION['user_id']. It would be to broad to wrote this here, but that's what you need. What you are doing now is to require the UserId from the Form, but the Form never works with the userId and the form also never sends the userId to the PHP File.
Notice: Undefined variable: dbh in C:\xampp\htdocs\php\complete_user.php on line 20
$dbh is just from the example. You never initialized this variable. You need to work with your own instance from the MySQLi Class. This should be done in your php file that handles your database connection. So i'm guessing that you already have this instance, you just called the wrong variable.
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\php\complete_user.php on line 20
Since $dbh isn't a instance from MySQLi you obviously can't call the prepare() function from MySQLi because PHP has no clue from it. So you need to work with your own MySQLi instance, preferbly from your database.php.
Hint: The same goes with MySQL as you're working with that, but you should change it to MySQLi since MySQL is deprecated and will be deleted in the 5.5 Version of PHP.

PHP use mySQL to check existing username [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have been following this tutorial for building a simple registration / login script.
http://forum.codecall.net/topic/69771-creating-a-simple-yet-secured-loginregistration-with-php5/
I am new with PHP, but I have a lot of experience using C++, so I thought the transitions wouldn't be too hard, I just need to figure out the syntax. I also did a very very quick introduction to mySQL at university, so I thought it would be a lot easier to use mySQL to check for an existing username when the user has registered, though my knowledge isn't too good. I thought something like this would work;
SELECT username
FROM codecalltut
WHERE username = username;
Would this actually work? It is selecting the username from the database codecalltut and then it checks to see if the username being inputted is already a username? Even if this is correct I don't know how to include it in my PHP.
I've tried using
$qry = "SELECT username
FROM codecalltut
WHERE username = username;"
But I just get a syntax error when it moves to the next statement.
<?php
$qry = "SELECT username
FROM codecalltut
WHERE username = username;"
//if register button was clicked.
} else {
$usr = new Users; //create new instance of the class Users
$usr->storeFormValues( $_POST ); //store form values
//if the entered password is match with the confirm password then register him
if( $_POST['password'] == $_POST['conpassword'] ) {
echo $usr->register($_POST);
} else {
//if not then say that he must enter the same password to the confirm box.
echo "Password and Confirm password not match";
}
}
?>
This is the query used to construct the database:
CREATE DATABASE `codecalltut` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `codecalltut`;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varbinary(250) NOT NULL,
PRIMARY KEY (`userID`,`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
This is the HTML code for when the user clicks "Register"
<li class="buttons">
<input type="submit" name="register" value="Register" />
<input type="button" name="cancel" value="Cancel" onclick="location.href='index.php'" />
</li>
Your HTML form for Registration
<form action='' method='POST'>
<input type='text' name='username' />
<input type='password' name='password' />
<input type='password' name='re-password' />
<input type='submit' name='submit' />
</form>
Your PHP code
if($_POST){
if(empty($_POST['username']) && empty($_POST['password']) && empty($_POST['re-password'])) {
echo 'Please enter all fields';
}else {
$username = $_POST['username'];
$password = $_POST['password'];
$re_password = $_POST['re-password'];
if($password !== $re_password){
echo 'Both passwords do not match';
}else {
$db_name =
$db_user =
$db_pass =
$conn = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx',
array( PDO::ATTR_PERSISTENT => true )
);
$stmt = $conn->prepare("SELECT username,password FROM users WHERE username = ? AND password = ?");
$stmt->execute(array($username, $password));
if($stmt->rowCount() === 0 ) {
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->execute(array($username, $password));
if($stmt->rowCount() ===1){
echo 'Registration complete';
}else {
echo 'Sorry, unknown error: please try again later';
}
}else {
echo 'Sorry, the username '.$username.' already exists';
}
}
}
}
Did you omit the part where you execute the query? All I see is that you're assigning the query to a variable but not executing it.
I see that you're using PDO, so you should NOT concatenate the username you're checking for into the query, as it leaves you open to SQL injection. I'm assuming your database object is called "$con" and your table is codecalltut. Do this:
$qry = "SELECT * FROM codecalltut WHERE username=?";
$stmt = $con->prepare($qry);
$stmt->execute(array($_POST['username']));
$exists = ($stmt->rowCount() === 1) ? true : false;
Remove the last ; :
$qry = "SELECT username
FROM codecalltut
WHERE username = username;";
REMOVE THIS --^ ^----ADD THIS
Followed by what #Nelson said. You should also enclose strings in your query with ' single quotes like this:
$qry = "SELECT username FROM codecalltut WHERE username = 'username' ";
Also, if you are writting inside, any table, row names, which might conflict with the database language itself, make sure to enclose them with backticks (`)
bytheway
A simple login script would work out this way. (hope, you are using PDO or mysqli instead of mysql functions to interact with your database
// set isset(), to validate if form is submited and then
$username = $_POST['username'];
$pass= $_POST['pass'];
Now, the code.
$conn = new PDO('mysql:host=localhost; dbname=***;', 'db-user', 'user-pass');
$stmt = $conn->prepare("SELECT username,password from members WHERE username = ? AND password = ?");
$stmt->execute(array($username, $password));
if($stmt->rowCount() === 1){
echo 'welcome'.$username;
}else {
echo $username.' is not found'
}

Categories