Unable to insert data into database using PDO [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've written this code for a registration page, but I am unable to get insert data into my database using PDO(or doing something incorrectly rather). Here is the registration page code:
<?php
if (empty($_POST)){
?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label>
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php
}
else{
$form = $_POST;
$username = $form['username'];
$password = $form['passowrd'];
$fname = $form['fname'];
$lname = $form['lname'];
$email = $form['email'];
$user = 'root';
$pass = 'pdt1848!';
$db = new PDO('mysql:host=localhost;dbname=phpproject', $user, $pass);
$sql = "INSERT INTO users (username, password, fname, lname, email)VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$result = $query->execute(array(':username'=>$username, ':password'=>$password,
':fname'=>$fname, ':lname'=>$lname, ':email'=>$email));
if ($result){
echo "Thanks for registering with us!";
} else {
echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
};
};
?>

The error is right here, passowrd
$password = $form['passowrd'];
A mere typo.
change it to:
$password = $form['password'];
when one fails, the whole query fails.
Had you error reporting in your code, it would've picked it up right away.
Ways that you can use in the future are a try & catch method, such as:
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
as well as
error_reporting(E_ALL);
ini_set('display_errors', 1);
Links that you can consult for further reading:
PDO
http://www.php.net/manual/en/pdo.error-handling.php
http://www.php.net/manual/en/pdo.errorinfo.php
MySQL
http://www.php.net/manual/en/mysqli.error.php
http://www.php.net/mysqli_error
(more)
http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/en/errorfunc.configuration.php#ini.display-startup-errors
http://php.net/manual/en/function.error-reporting.php
Passwords
I also noticed that you are storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP

Well I do something like this,
$user = 'your username';
$pass = 'your pass';
$db = new PDO( 'mysql:host=localhost;dbname=your_data_base_name', $user, $pass );
/*Grab Post*/
$form = $_POST;
$username = $form[ 'username' ];
$password = $form[ 'password' ];
$first_name = $form[ 'first_name' ];
$surname = $form[ 'surname' ];
$address = $form[ 'address' ];
$email = $form[ 'email' ];
// Sql
$sql = "INSERT INTO users ( username, password, first_name, surname, address, email ) VALUES ( :username, :password, :first_name, :surname, :address, :email )";
$result = $query->execute( array( ':username'=>$username, ':password'=>$password, ':first_name'=>$first_name, ':surname'=>$surname, ':address'=>$address, ':email'=>$email ) );
if ( $result ){
echo "Thank you. You have been registered";
} else {
echo "Sorry, there has been a problem inserting your details.";
}
In addition I always, enable my error reporting as Tuga suggested. It never fails me.

apart from the typo in the passowrd you should enable exceptions for PDO and use a try and catch statement to catch the exception. Also some other little changes, like structuring the PHP first and removing the odd re-assign of the POST superglobal.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$result = "Thanks for registering with us!";
try{
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
$sql = "INSERT INTO users (username, password, fname, lname, email)
VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$_POST['username'],
':password'=>$_POST['password'],
':fname'=>$_POST['fname'],
':lname'=>$_POST['lname'],
':email'=>$_POST['email']));
}catch(PDOException $e){
$result = 'Sorry, an error occurred while editing the database. Contact the guy who built this garbage.';
//or use $e->getMessage(); for the real error
}
echo $result;
}
else{ ?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label>
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php } ?>
Also its a very bad idea to store plain-text passwords in your db. ~ Read: Best way to store password in database.
Edit,
Added some validation of your inputs to help you get started, hope it helps. not tested.
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch(PDOException $e){
die('Sorry, an error occurred while editing the database. Contact the guy who built this garbage.');
//or use $e->getMessage(); for the real error
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//create empty error array - to fill with errors if any
$error = array();
//validate username
if(empty($_POST['username'])){
$error['username'] = 'Enter a username';
}elseif(strlen($_POST['username']) <= 2){
$error['username'] = 'Username too short > 2 chars';
}else{
//check for existing user
$sql = "SELECT 1
FROM `users`
WHERE username = :username";
$query = $db->prepare($sql);
$query->execute(array(':username' => $_POST['username']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(!empty($result)){
$error['username'] = 'User already exists';
}
}
//validate pass
if(empty($_POST['password'])){
$error['password'] = 'Please enter password';
}elseif(strlen($_POST['password']) < 6){
$error['password'] = 'Password too short, password should be 6 chars or longer';
}
//validate fname
if(empty($_POST['fname'])){
$error['fname'] = 'Please enter your first name';
}
//validate fname
if(empty($_POST['lname'])){
$error['lname'] = 'Please enter your last name';
}
//validate email
if(empty($_POST['email'])){
$error['email'] = 'Please enter your email';
}else{
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error['email'] = 'Please enter valid email';
}
}
//no errors detected so insert
if(empty($error)){
$sql = "INSERT INTO users (username, password, fname, lname, email)
VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$_POST['username'],
':password'=>$_POST['password'],
':fname'=>$_POST['fname'],
':lname'=>$_POST['lname'],
':email'=>$_POST['email']));
$result = 'Thanks for registering with us! Click here to login';
}else{
$result = 'Please correct the errors';
}
}?>
<?php echo isset($result) ? $result : null;?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: <?php echo isset($error['username']) ? $error['username'] : null;?></label>
<input type="text" name="username"/><br />
<label for "password">Password: <?php echo isset($error['password']) ? $error['password'] : null;?></label>
<input type="password" name="password"/><br />
<label for "fname">First Name: <?php echo isset($error['fname']) ? $error['fname'] : null;?></label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: <?php echo isset($error['lname']) ? $error['lname'] : null;?></label>
<input type="text" name="lname"/><br />
<label for "email">Email: <?php echo isset($error['email']) ? $error['email'] : null;?></label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>

Related

Multicolumn form in PHP PDO

Although everything looks fine in my program (e.g. register2.php), I have some syntax and binding issues. As it keeps throwing the error on line 73 even though the data successfully entered my database named "webprojadmin", and the table named "users".
here is my connected PDO database:
<?php
session_start();
$host = "127.0.0.1:3308";
$username = "root";
$password = "root";
$dbname = "webprojadmin";
$dsn = "mysql:host=$host;dbname=$dbname";
$optionen = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
// Create connection
$cxn = new PDO($dsn, $username, $password, $optionen);
// set the PDO error mode to exception
$cxn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Success: A proper connection to MySQL was made! The"." ".$dbname." "."database is great." . PHP_EOL;
//echo "Host URL: " . $host . PHP_EOL;
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
And here is my program, register2.php
<?php
require "dbcxn.php";
?>
<center>
<div>
<h1>Add a new web user account</h1>
<form action="" method="post">
<p>Full Name:<input type="text" name="fullname" placeholder="enter your full name"></p>
<p>Email:<input type="text" name="email" placeholder="enter your email address"></p>
<p>Password:<input type="password" name="pass" placeholder="enter passowrd"></p>
<p>Type<select name="utype">
<option value="FA">Academic, Faculty & Staff</option>
<option value="UG">Undergraduate Student</option>
<option value="PG">Postgraduate Student</option>
<option value="AU">Undergraduate Alumni</option>
<option value="AP">Postgraduate Alumni</option>
</select><p>
<p>Bio:<br><textarea id="textboxid" type="text" name="bio" placeholder="May you introduce to us, briefly?"></textarea></p>
<p>Awards:<br><textarea id="textboxid" type="text" name="awards" placeholder="Have you received any awards? If yes, what are they?"></textarea></p>
<p>Publications:<br><textarea id="textboxid" type="text" name="pub" placeholder="Have you published any written works? If yes, what are they?"></textarea></p>
<p>Thesis Topic:<br><textarea id="textboxid" type="text" name="ttopic" placeholder="What is the title of the Thesis you are doing/about to do/recently done?"></textarea></p>
<p>Thesis abstract:<br><textarea id="textboxid" type="text" name="tabstract" placeholder="If you have told the thesis topic, what is it about? Tell us briefly. If not, leave it blank."></textarea></p>
<p><input type="submit" name="btn_register" value="Create an account"/></p>
</form>
</div>
</center>
<?php
if (isset($_POST["btn_register"])) //button name "btn_register"
{
$fullname = strip_tags($_POST["fullname"]);
$email = $_POST["email"];
$pass = $_POST["pass"];
$utype = $_POST["utype"];
$bio = $_POST["bio"];
$awards = $_POST["awards"];
$pub = $_POST["pub"];
$ttopic = $_POST["ttopic"];
$tabstract = $_POST["tabstract"];
$sql = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
echo ("<pre>\n".$sql."\n</pre>\n");
if(empty($fullname)) {
$errorMsg[]="Please enter username"; //check username textbox not empty
}
else if(empty($email)) {
$errorMsg[]="Please enter email"; //check email textbox not empty
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsg[]="Please enter a valid email address"; //check proper email format
}
else if(empty($pass)) {
$errorMsg[]="Please enter password"; //check passowrd textbox not empty
}
else if(strlen($pass) < 6) {
$errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
}
else
{
try
{
$select_stmt=$cxn->prepare("SELECT fullname, email FROM users
WHERE fullname=:ufname OR email=:uemail"); // sql select query
$select_stmt->execute(array(':ufname'=>$fullname, ':uemail'=>$email)); //execute query
$row=$select_stmt->fetch(PDO::FETCH_ASSOC);
if($row["fullname"]==$fullname){
$errorMsg[]="Sorry username already exists"; //check condition username already exists
}
else if($row["email"]==$email){
$errorMsg[]="Sorry email already exists"; //check condition email already exists
}
else if(!isset($errorMsg)) //check no "$errorMsg" show then continue
{
$new_pass = password_hash($pass, PASSWORD_DEFAULT); //encrypt password using password_hash()
$query = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
//$query2 = $sql;
//$query2run = $cxn->prepare($query2);
//$query2exec = $query2run->execute();
//$row=$query2run->fetch(PDO::FETCH_ASSOC);
$insert_stmt=$cxn->prepare("INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES (:ufname,:uemail,:upass,:uutype,:ubio,:uawards,:upub,:uttopic,:utabstract)"); //sql insert query
if ($insert_stmt->execute(array( ':ufname' =>$fullname,
':uemail'=>$email,
':upass'=>$new_pass,
':uutype'=>$utype,
':upass'=>$bio,
':upass'=>$awards,
':upass'=>$pub,
':upass'=>$ttopic,
':upass'=>$tabstract))) {
$registerMsg = "Register Successfully..... Please Click On Login Account Link"; //execute query success message
header("refresh:1; index.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
if(isset($errorMsg))
{
foreach($errorMsg as $error)
{
?>
<div>
<strong>WRONG ! <?php echo $error; ?></strong>
</div>
<?php
}
}
if(isset($registerMsg))
{
?>
<div>
<strong><?php echo $registerMsg; ?></strong>
</div>
<?php
}
?>
</section>

Database insert not working (MySQL, PHP)

I have this PHP that basically is being used for inserting an email and password into an SQL database:
<?php
error_reporting(E_ALL ^ E_STRICT);
require "database.php";
$message = '';
if (!empty($_POST["email"]) &&!empty($_POST["password"])):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":password", password_hash($_POST['password'], PASSWORD_BCRYPT));
if ($stmt->execute() ):
$message = 'Successfully created a new user';
else:
$message = 'Sorry there must have been an issue whilst registering';
endif;
endif;
?>
Here is the form:
<div class="jumbotron" id="jumbotron-6">
<div class="container text-center">
<?php if (!empty($message)):
?>
<h3 id="h3message"><?= $message ?> </h3>
<?php endif; ?>
<form action="signup.php" method="POST">
<input type="text" placeholder="enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="submit">
</form>
</div>
</div>
It doesn't insert into the database (all the fields, variables are correct i think - just email and password) and it comes back with the error message that I created that says 'Sorry there must have been an issue whilst registering'
Here is the database.php file
<?php
$server = 'localhost';
$username = "root";
$password = "";
$database = "auth";
try{
$conn = new PDO ("mysql:host={$server};dbname={$database};" , $username, $password);
}
catch (PDOException $e) {
die ( "Connection failed; " . $e->getMessage());
}
?>
Hash the password before you bind it:
$UserPWHash = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(":password", $UserPWHash));

Inserting data to database using PDO

I try to make registration form using PDO.I got next form:
<form name="registration" action="registration.php" method="POST">
<label for 'username'>Username: </label>
<input type="text" name="userName"/>
<label for 'password'>Password: </label>
<input type="password" name="pass"/>
<label for 'first_name'>First name: </label>
<input type="text" name="fullName"/>
<label for 'email'>Email: </label>
<input type="text" name="email"/>
<br/>
<button type="submit">Submit</button>
</form>
And I got registration.php file to connect database and insert values:
<?php
$user = 'root';
$pass = '8169x5it';
$db = new PDO( 'mysql:host=localhost;dbname=reg_form', $user, $pass );
$form = $_POST;
$usernName = $form[ 'userName' ];
$pass = $form[ 'pass' ];
$fullName = $form[ 'fullName' ];
$email = $form[ 'email' ];
$sql = "INSERT INTO WebsiteUsers ( userName, pass, fullName, email ) VALUES ( :userName, :pass, :fullName, :email )";
$query = $db->prepare( $sql );
$query->execute( array( ':userName'=>$userName, ':pass'=>$pass, ':fullName'=>$fullName, ':email'=>$email ) );
?>
So, the problem is when I put some in fileds and press Submit button my data NOT insert to database. Please help me, I'm new in PDO and mysql and I can't understand what's wrong. Thanks in advance!
Check for errors
Remove unnecessary variables
Check if post variables are set with isset()
try{
$user = 'root';
$pass = '8169x5it';
$db = new PDO( 'mysql:host=localhost;dbname=reg_form', $user, $pass );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO WebsiteUsers ( userName, pass, fullName, email )
VALUES ( :userName, :pass, :fullName, :email )";
if($query = $db->prepare($sql)){
$query->bindValue(':userName', $_POST['userName']);
$query->bindValue(':pass', $_POST['pass']);
$query->bindValue(':fullName', $_POST['fullName']);
$query->bindValue(':email', $_POST['email']);
if($query->execute()){
echo 'execute() success ';
echo 'affected rows = '.$stmt->rowCount();
}else{
echo 'execute() failed';
}
}else{
echo 'prepare() failed';
}
}catch(PDOException $e) {
// Print PDOException message
echo $e->getMessage();
}

It say {"success":0,"message":"Database Error2. Please Try Again!"} [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<?php
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both a Username and Password.";
die(json_encode($response));
}
else if (empty($_POST['name']) || empty($_POST['mobilenumber']) || empty($_POST['address']) || empty($_POST['city']) || empty($_POST['state'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter the required marked ** field.";
die(json_encode($response));
}
else if (strlen($_POST['password']) < 6) {
$response["success"] = 0;
$response["message"] = "Your password should be at least 6 characters.";
die(json_encode($response));
}
else if ($_POST['password'] != $_POST['confirmpassword']){
$response["success"] = 0;
$response["message"] = "Confirm Password is not the same with Password you have entered.";
die(json_encode($response));
}
$query = " SELECT 1 FROM user WHERE email = :email";
$query_params = array(
':email' => $_POST['username']
);
//Now let's make run the query:
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//fetch is an array of returned data. If any data is returned,
//we know that the username is already in use, so we murder our
//page
$row = $stmt->fetch();
if ($row) {
// For testing, you could use a die and message.
//die("This username is already in use");
//You could comment out the above die and use this one:
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
$query = "INSERT INTO user ( name, email, password, mobilenumber, address, city, postcode, state) VALUES ( ;name, :email, :password, :mobilenumber, :address, :city, :postcode, :state) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':name' => $_POST['name'],
':email' => $_POST['username'],
':password' => $_POST['password'],
':mobilenumber' => $_POST['mobilenumber'],
':address' => $_POST['address'],
':city' => $_POST['city'],
':postcode' => $_POST['postcode'],
':state' => $_POST['state']
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);
//for a php webservice you could do a simple redirect and die.
//header("Location: login.php");
//die("Redirecting to login.php");
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Name:<br />
<input type="text" name="name" value="" />
<br /><br />
Email:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
Confirm Password:<br />
<input type="password" name="confirmpassword" value="" />
<br /><br />
Mobile Number:<br />
<input type="text" name="mobilenumber" value="" />
<br /><br />
Address:<br />
<input type="text" name="address" value="" />
<br /><br />
City:<br />
<input type="text" name="city" value="" />
<br /><br />
Postcode:<br />
<input type="text" name="postcode" value="" />
<br /><br />
State:<br />
<input type="text" name="state" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
This is the message I got back
{"success":0,"message":"Database Error2. Please Try Again!"}
I dont know what kind of exceptional the program catch... , Anyone help me out please?
It is very much appreciate of you all help.
If needed any else coding i can give it here.
$query = "INSERT INTO user ( name, email, password, mobilenumber, address, city, postcode, state) VALUES ( ;name, :email, :password, :mobilenumber, :address, :city, :postcode, :state) ";
change to
$query = "INSERT INTO user ( name, email, password, mobilenumber, address, city, postcode, state) VALUES ( :name, :email, :password, :mobilenumber, :address, :city, :postcode, :state) ";

user_login and password_login correct, but are not working PDOPHP

I am trying to get my login script to work using PDO. The problem I am having is that when a user types in his/her username and passsword, it goes to the section of the code where it says it is incorrect, even if the password is correct. What can I do to fix this, and where can I implement the PDO error to show up to possibly help diagnose the problem.
The Login Script from index.php
<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
$password_login=md5($password_login);
$db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
$db->prepare($sql);
if ($db->execute(array(
':user_login' => $user_login,
':password_login' => $password_login))); {
if ($sql->rowCount() > 0){
while($row = $sql->fetch($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
exit("<meta http-equiv=\"refresh\" content=\"0\">");
} else {
echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
exit();
}
}
}
?>
index.php
<? include("inc/incfiles/header.inc.php"); ?>
<?
$reg = #$_POST['reg'];
//declaring variables to prevent errors
$fn = ""; //First Name
$ln = ""; //Last Name
$un = ""; //Username
$em = ""; //Email
$em2 = ""; //Email 2
$pswd = ""; //Password
$pswd2 = ""; //Password 2
$d = ""; //Sign up Date
$u_check = ""; //Check if username exists
//registration form
$fn = #$_POST['fname'];
$ln = #$_POST['lname'];
$un = #$_POST['username'];
$em = #$_POST['email'];
$em2 = #$_POST['email2'];
$pswd = #$_POST['password'];
$pswd2 = #$_POST['password2'];
$d = date("y-m-d"); // Year - Month - Day
if ($reg) {
if ($em==$em2) {
// Check if user already exists
$statement = $db->prepare('SELECT username FROM users WHERE username = :username');
if ($statement->execute(array(':username' => $un))) {
if ($statement->rowCount() > 0){
//user exists
echo "Username already exists, please choose another user name.";
exit();
}
}
//check all of the fields have been filled in
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
//check that passwords match
if ($pswd==$pswd2) {
//check the maximum length of username/first name/last name does not exceed 25 characters
if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
echo "The maximum limit for username/first name/last name is 25 characters!";
}
else
{
//check the length of the password is between 5 and 30 characters long
if (strlen($pswd)>30||strlen($pswd)<5) {
echo "Your password must be between 5 and 30 characters long!";
}
else
{
//encrypt password and password 2 using md5 before sending to database
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$sql = 'INSERT INTO users (username, first_name, last_name, email, password, sign_up_date)';
$sql .= 'VALUES (:username, :first_name, :last_name, :email, :password, :sign_up_date)';
$query=$db->prepare($sql);
$query->bindParam(':username', $un, PDO::PARAM_STR);
$query->bindParam(':first_name', $fn, PDO::PARAM_STR);
$query->bindParam(':last_name', $ln, PDO::PARAM_STR);
$query->bindParam(':email', $em, PDO::PARAM_STR);
$query->bindParam(':password', $pswd, PDO::PARAM_STR);
$query->bindParam(':sign_up_date', $d, PDO::PARAM_STR);
$query->execute();
$query=$db->prepare($sql);
$array = array(
':username' => $un,
':first_name' => $fn,
':last_name' => $ln,
':email' => $em,
':password' => $pswd,
':sign_up_date' => $d);
$query->execute($array);
die("<h2>Welcome to Rebel Connect</h2>Login to your account to get started.");
}
}
}
else {
echo "Your passwords do not match!";
}
}
else
{
echo "Please fill in all fields!";
}
}
else {
echo "Your e-mails don't match!";
}
}
?>
<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
$password_login=md5($password_login);
$db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
$db->prepare($sql);
if ($db->execute(array(
':user_login' => $user_login,
':password_login' => $password_login))); {
if ($sql->rowCount() > 0){
while($row = $sql->fetch($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
exit("<meta http-equiv=\"refresh\" content=\"0\">");
} else {
echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
exit();
}
}
}
?>
<table class="homepageTable">
<tr>
<td width="60%" valign="top">
<h2>Already a member? Login below.</h2>
<form action="index.php" method="post" name="form1" id="form1">
<input type="text" size="25" name="user_login" id="user_login" placeholder="username" />
<br />
<input type="password" size="25" name="password_login" id="password_login" placeholder="password" />
<br />
<input type="submit" name="button" id="button" value="Login to your account!">
</form>
</td>
<td width="40%" valign="top">
<h2>Sign up below...</h2>
<form action="#" method="post">
<input type="text" size="25" name="fname" placeholder="First Name" value="<? echo $fn; ?>">
<input type="text" size="25" name="lname" placeholder="Last Name" value="<? echo $ln; ?>">
<input type="text" size="25" name="username" placeholder="Username" value="<? echo $un; ?>">
<input type="text" size="25" name="email" placeholder="Email" value="<? echo $em; ?>">
<input type="text" size="25" name="email2" placeholder="Re-enter Email" value="<? echo $em2; ?>">
<input type="password" size="25" name="password" placeholder="password" value="<? echo $pswd; ?>">
<input type="password" size="25" name="password2" placeholder="Re-enter Password" value="<? echo $pswd2; ?>"><br />
<input type="submit" name="reg" value="Sign Up!">
</form>
</td>
</tr>
</table>
</body>
</html>
logout.php
<?
session_start();
session_destroy();
header("Location: index.php");
?>
home.php
<?
session_start();
$user = $_SESSION["user_login"];
//If the user is not logged in
if (!isset($_SESSION["user_login"])) {
header("location: index.php");
exit();
}
else
{
//If the user is logged in
echo "Hi, $user, You're logged in<br />Welcome to what is soon to be your NEWSFEED
Logout?
";
}
?>
header.inc.php
<?
include ("inc/scripts/db_connect.inc.php");
session_start();
if (!isset($_SESSION["user_login"])) {
}
else
{
header("location: home.php");
}
?>
<html>
<head>
<link href="css/main.css" rel="stylesheet" type="text/css">
<title>Rebel Reach - PHS Student Social Network</title>
</head>
<body>
<div class="headerMenu">
<div id="wrapper">
<div class="logo">
<img src="img/find_friends_logo.png">
</div>
<div class="search_box">
<form method="get" action="search.php" id="search">
<input name="q" type="text" size="60" placeholder="Search..." />
</form>
</div>
<div id="menu">
Home
About
Sign Up
Login
</div>
</div>
</div>
<br />
<br />
<br />
<br />
Not an answer but some advice for your code that couldn't fit in the comment. You can greatly reduce your code; actually you shouldn't repeat functionality too often... You can reduce:
$fn = ""; //First Name
$ln = ""; //Last Name
...
$fn = #$_POST['fname'];
$ln = #$_POST['lname'];
...
To half by writting it like this:
$fn = (!empty($_POST['fname'])) ? $_POST['fname'] : '';
$ln = (!empty($_POST['lname'])) ? $_POST['lname'] : '';
$un = (!empty($_POST['username'])) ? $_POST['username'] : '';
$em = (!empty($_POST['email'])) ? $_POST['email'] : '';
$em2 = (!empty($_POST['email2'])) ? $_POST['email2'] : '';
$pswd = (!empty($_POST['password'])) ? $_POST['password'] : '';
$pswd2 = (!empty($_POST['password2'])) ? $_POST['password2'] : '';
Furthermore, although this would require some other changes, you can reduce that to a couple of lines by writing it in an array like this:
// Retrieve user data
foreach (array('fname', 'lname', 'username', 'email', 'email2', 'password', 'password2') as $Value)
$User[$Value] = (!empty($_POST[$Value])) ? $_POST[$Value] : '';
I think your problem is here:
"SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
When you use PDO prepare method like ? or : do not use single quotation mark (').
correct it like this:
"SELECT id FROM users WHERE username = :user_login AND password = :password_login LIMIT 1";
I hope now it will work!
RE your "Fatal error: call to undefined method PDO::execute() in ... line 110" issue:
"execute()" is a method in PDOStatement, not PDO, which is why your "$db->execute..." blew up.
(I know this should be a comment, but I'm not allowed yet. Sorry)

Categories