I'm new to php form insertion and can't seem to find an answer to my specific issue. I'm able to send the name/email to a database, however I need to specify the input table in order to keep it more organized. With my current setup, I only know how to create new databases for each product giveaway, but I'm sure there is a better way than that.
Here is my current php code, please keep in mind I'm two weeks into php! If you could specify where I need to enter anything that would help a lot.
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
mysql_connect("localhost","username","password");//database connection
mysql_select_db("myusername_mytable");
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
// Get values from form
$name = $_POST['name'];
$email = $_POST['email'];
//inserting data order
$order = "INSERT INTO user_info
(name, email)
VALUES
('$name','$email')";
//declare in the order variable
$result = mysql_query($order);
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Registration Complete!';
}
*********UPDATE***********
Turns out I was using deprecated language, so I switched to PDO. Thank you all for the help!
IF any other newbies were wondering with the previous form, I was missing an incredibly easy fix where it says $order = "INSERT INTO user_info which was the table name!
Firstly, you need to be using the MySQLi or PDO libraries, which are more secure than the now deprecated mysql_ library.
Assuming you want to store information on the giveaway and the entrants, you can create a single database with two tables, entrants and giveaways.
Give giveaways the structure of
id int primary key auto_increment
name varchar(100),
start_date datetime
end_date datetime
and entrants the structure of
id int primary key auto_increment
giveaway_id int //this is a foreign key linking the entrant to the relevant giveaway
email varchar(100),
name varchar(150)
With that in mind, let's have a look at your code:
//setting your arrays for later
$data = array();
$errors = array();
//checking your posted data values
if(empty($_POST['name'])) $errors['name'] = "Name is required.";
if(empty($_POST['email'])) $errors['email'] = "Email is required.";
//find out if we had any errors
if(!empty($errors)) {
//if we did, then we return them
$data['success'] = false;
$data['errors'] = $errors;
} else {
//and if we didn't, continue
$sql = new MySQLi(/*your host, username, password and database name here */);
if($sql->connect_error) {
//if we can't get a connection to the database, kill the script and print out a handy message
die("Connection error: ".$sql->connect_error." ".$sql->connect_errorno);
}
}
//get your securimage script
include_once($_SERVER['DOCUMENT_ROOT'].'/securimage/securimage.php');
if ($securimage->check($_POST['captcha_code']) == false) {
//do some error handling for the captcha checking
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
//did all that work? Awesome, let's continue
//ALWAYS escape your form data. It's not a sure win against SQL injection but it's the best place to start
$email = $sql->real_escape_string($_POST['email']);
$name = $sql->real_escape_string($_POST['name']);
//assuming that there can only be one giveaway running at any one time...
//get the id of the active giveaway, where it's end date is more than the current time
$query = "SELECT id FROM giveaways WHERE end_date > NOW()";
//query the database or kill the script and print an error (further down the line, don't print the error for security reasons
$result = $sql->query($query) or die($sql->error);
if($result->num_rows > 0) {
//if there's an active giveaway, fetch that result
$row = mysqli_fetch_assoc($result);
//and set a variable to the id we want
$id = $row['id'];
//insert into your entrants the now linked entrant details and giveaway key
$query = "INSERT INTO entrants (giveaway_id, name, email) VALUES ('$id', '$name', '$email')";
//again, query or error handling
$result = $sql->query($query) or die($sql->error);
//if that query worked, do your success message, if it didn't tell the entrant that something went wrong
if($result) {
$data['success'] = true;
$data['message'] = "Registration complete!";
} else {
$data['success'] = false;
$data['message'] = "There was an error registering you, please try again soon.";
}
}
Now, when you need to return all entrants to a specific giveaway you simply do:
SELECT name, email FROM entrants WHERE giveaway_id = //the id of the giveaway
If you change the structure of your table, you can save the giveaway name.
SQL
ALTER TABLE user_info ADD COLUMN giveaway VARCHAR(64) NOT NULL;
PHP
$giveaway = $_POST['giveaway'];
$order = "INSERT INTO user_info
(name, email, giveaway)
VALUES
('$name','$email','$giveaway')";
I'd recommend using bound parameters in your query and sanitizing your data input from $_POST, too. Check out PDO.
Related
I'm new to PHP. I'm currently doing an email validation. My code is supposed to generate a random number, send to user via email and verify it when user enters.
Here is my code:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
session_start();
// initializing variables
$email = $_SESSION ['email'];
$user_code = "";
$errors = array();
// generate a four digit random number
$gen_code = strval (rand (10000, 99999));
// send code to user email
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'register');
// REGISTER USER
if (isset($_POST['email_confirm'])) {
// receive all input values from the form
$user_code = mysqli_real_escape_string($db, $_POST['code']);
// check whether both codes match
if ($user_code != $gen_code) { array_push($errors, "The codes do not match"); }
else {
// set isConfirmed == true
if (count($errors) == 0) {
$query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
mysqli_query($db, $query);
$_SESSION['email'] = $email;
header('location: user_details.php');
}
}
}
?>
Here email_confirm is the name of my submit button and code is the name of text box.
It all works fine when page is first loaded. I get an email with a random integer.
Problem starts when I click my submit button. I receive another email with different number and the number I already entered is not equal to the one I received from email.
Please help
If this is a simpler and an experimental application, you should store gen_code in this session soon after its sent to the user confirmation email. Otherwise, store the code in db and retrieve it when your application receives email confirm POST request and compare the code that was sent by the user against the session or db wherever you'd stored it.
if (isset($_POST['email_confirm'])) {
// receive all input values from the form
$code = $_SESSION['gen_code']; // in case you would wish to store and retrieve code from db, replace this code with one which retrieved from db by email id... SELECT code from user where email=$email
$user_code = mysqli_real_escape_string($db, $_POST['code']);
// check whether both codes match
if ($user_code != $code) {
array_push($errors, "The codes do not match");
} else {
if (count($errors) == 0) {
$query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
mysqli_query($db, $query);
$_SESSION['email'] = $email;
header('location: user_details.php');
}
}
}
I'm so close to completing the login/registration section of my site but I've got some bugs that don't show up in error_log or anything.
About an hour ago, the script worked for the most part. It would validate, insert into/check database, and redirect to index.php (located in user directory along with login and register forms).
Contents of index.php:
/*
If validation script is successful, continue to $destinationUrl, otherwise, go back to try
again. Ultimately, the TRUE statement's output will be the referring page's URL stored as
$_SESSION['Return_Url'] to send users back to where they were, simply as a convenience.
*/
session_start();
if(isset($_SESSION['UserData'])) {
exit(header("location:" . $destinationUrl));
} else {
exit(header("location:" . $loginUrl));
}
That's exactly what I want except one detail: it won't show any user input errors. While trying to fix that, I've managed to screw everything up again and now it still submits data and inserts into the database but doesn't insert $email, and doesn't redirect or anything. On top of that, I don't get any PHP errors so I'm at a loss.
I know the login and registration will work because it did before, but I don't know what I did to cause this issue due to know errors being thrown. I just want the input errors to show up. I'm going to post the original code I copied and edited because what I'm messing with right now is a mess but the validation section is the same.
I did not write these, they were found online after hours of trying script after script. Only this one worked. Therefore, I don't understand exactly what's going on with every part of the script, but I do understand the basic mechanics of what happens, or is supposed to happen as far as validation of input data and adding to/checking data against the database when the form is submitted. The only thing that I have absolutely no idea what and how it works is the output($var) function
Included Scripts
$db= mysqli_connect($dbhost,$dbuser,$dbpwd,$dbase); }
function safe_input($db, $data) {
return htmlspecialchars(mysqli_real_escape_string($db, trim($data)));
}
/*
Currently, I have no idea about JSON or any other languages. Only a decent
portion of PHP, and HTML, of course. Can I just forget this function and use
{return $var;} instead? Because that would make everything so much easier
and I probably wouldn't even be posting these questions... but it's a new
language to me that I couldn't tell you the first thing about.
*/
function output($Return=array()){
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
exit(json_encode($Return));
}
Validation Scripts
(Both scripts are in one file)
<?
require 'config.php';
require 'functions.php';
if(!empty($_POST) && $_POST['Action']=='login_form'){
$Return = array('result'=>array(), 'error'=>'');
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid email address.";
}elseif($password===''){
$Return['error'] = "Please enter password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' AND password='".md5($password)."' LIMIT 1");
if(mysqli_num_rows($result)==1){
$row = mysqli_fetch_assoc($result);
$Return['result'] = $_SESSION['UserData'] = array('id'=>$row['id']);
} else {
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
if(!empty($_POST) && $_POST['Action']=='registration_form'){
$Return = array('result'=>array(), 'error'=>'');
$name = safe_input($db, $_POST['Name']);
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if($name===''){
$Return['error'] = "Please enter Full name.";
}elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid Email address.";
}elseif($password===''){
$Return['error'] = "Please enter Password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' LIMIT 1");
if(mysqli_num_rows($result)==1){
$Return['error'] = 'The email you entered already belongs to an account, please login.';
}else{
mysqli_query($db, "INSERT INTO tbl (GUID, email, password, entry_date) values(MD5(UUID()), '$email', '".md5($password)."' ,NOW() )");
$id = mysqli_insert_id($db);
mysqli_query($db, "INSERT INTO `tbl' (id,name) VALUES('$id','$name')");
$Return['result'] = $_SESSION['UserData'] = array('id'=>$id);
}
output($Return);
}
?>
I'm not sure how I would echo the $Return array values. I tried making a function out of it like so:
function inputErr($Return) {
if($Return['error']!=''){
output($Return);
}
}
but that didn't work either. Is there a special way to echo an array value? Without the index name attached
Also, if you have any ideas why the email $var is not being added to db while everything else is, please, do share! With the script not throwing any PHP errors, I have no idea where to start.
I have created a script for users to invite a friend using a email address, the email address and a randomly generated 10 character string 'inviteCode' is sent to a table called 'referrals'.
The invited person then receives an email with a URL link that contains their email and their unique inviteCode; http://website.com/register.php?email=email&inviteCode=1234567890
When the user clicks on the link the page register.php should then check the URL and if they data is valid in the 'referrals' table. If so then I have an include line to add the register form, if not then they are redirected. The point is nobody can access register.php unless they have been invited and sent a link.
At the moment the page keeps redirecting to index.php;
Register.php script:
<?php
include 'config.php';
if (isset($_GET['email'],$_GET['inviteCode'])) {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
echo 'lol';
}
else
{
echo 'no';
exit;
}
}
else
{
echo 'problem'; //Page not accessible if neither email nor referral entered
}
?>
I replaced the first if statement with:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else
And I receive a blank page with no errors. I believe there may be something wrong with the email and invite code not being set.
Any help on this would be much appreciated (Y) thanks.
You should really be looking at handling the errors first. Try something like this:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='$email' AND inviteCode='$inviteCode'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
include'register-form.php';
} else {
die(header('Location: index.php'));
}
}
Breakdown
The if block checks to see if GET[email] or GET[inviteCode] are not set. if that is the case, kill the app with die() and redirect the user to index.php.
The second change is this line:
if ($query->num_rows > 0) {
That will check to ensure the rows returned are more than 0 (meaning there are actually rows returned.) Because you were just testing the presence of the $query->num_rows before.
Another Note:
Turn on error reporting, it will help you emensly during debugging:
ini_set('display_errors', 1);
error_reporting(E_ALL);
You could alternatively change your sql query to select the COUNT(id) and check if that is greater than 0, but that seems like overkill for what you're trying to do.
Do this to find out if anything is being returned by your query:
Start by making sure that the connection to your database is succeeding:
$mysqli = new Mysqli(/* your connection */);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$email = $mysqli->real_escape_string($_GET['email']);
Add that then let us know the results afterward, also provide specific error messages.
To debug your num_rows, replace this:
$query = $mysqli->query($sql);
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
With this:
$query = $mysqli->query($sql);
$count = $query->num_rows;
print $count;
exit;
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
If it shows 0, I have a suspicion it is because your sql statement needs to be concatenated.
"SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
There are many questions about email confirmation, databases, and permissions on Stackoverflow, but nothing I could find that would help me with this.
This specific question is directed to an email confirmation function built with PHP. The tutorial I am using can be found here: http://www.phpeasystep.com/phptu/24.html. Everything is working, however when the user clicks the email confirmation link (which would move their information from the temp_table to the confirmed_table), I receive this error:
Error updating database: No database selected
From what I have gathered from different sites/research/Stackoverflow questions is that this is due to the permissions of the database(s) I am working with (please correct me if it is another problem). I have read that I need to change all the users to be able to READ, but am unsure whether I should do this to both the databases as a whole (I couldn't find whether you can set the privileges for all the users in a database to automatically have the READ privileged), or the PHP when I add them to the temp_table. The tutorial I showed above doesn't say anything about it, so I am confused.
Registration form code:
<?php
session_start();
if(isset($_SESSION['aI']) || isset($_SESSION['pss'])) {
header("Location: pa.php");
}
include 'db.php';
if(isset($_POST['rSub'])) {
// connects to database using PHP Data Objects, throws exception if error in connection
try {
$conn = new PDO("mysql:host=$svrHost;db=$svrDb", $sUme, $sp);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "ERROR: " . $e->getMessage();
}
$error = '';
if($_POST['fN'] == '' || $_POST['lN'] == '' || $_POST['aI'] == '' || $_POST['eml'] == '' || $_POST['pss'] == ''
|| $_POST['pss2'] == '') {
$error = "<li style=\"color:#C70000; font-weight:bold;\"><center>- All fields are required. Try again.</font><center></li>";
}
if($error == '') {
$fN = ucfirst($_POST['fN']);
$lN = ucfirst($_POST['lN']);
$aI = $_POST['aI'];
$eml = $_POST['eml'];
$pss = $_POST['pss'];
$pss2 = $_POST['pss2'];
$admin = 0;
if($error != '') {
$error = "<ul>".$error."</ul>";
$_SESSION['error'] = $error;
}
else {
$hF = "$2y$10$"; // 2y = blowfish and 10 = num of hashes
$sa = "testsaltforwebsite1219"; //"random" 22-character sa
$fAS = $hF.$sa;
$sha = crypt($pss, $fAS);
// Random confirmation code
$c_cd=md5(uniqid(rand()));
$insert = $conn->prepare("INSERT INTO t_awhole (c_cd, fN, lN, aI, eml, pss)
VALUES (:c_cd, :fN, :lN, :aI, :eml, :pss)");
$insert->bindParam(':c_cd', $c_cd);
$insert->bindParam(':fN', $fN);
$insert->bindParam(':lN', $lN);
$insert->bindParam(':aI', $aI);
$insert->bindParam(':eml', $eml);
$insert->bindParam(':pss', $sha);
$result=$insert->execute();
// ---------------- Confirmation email ---------------- \\
// table name
$t_apart=t_awhole;
if($result){
// send e-mail to ...
$to=$eml;
// Your subject
$subject="Registration Confirmation";
// From
$header="from: no-reply#example.com"; //Need the address to send the eml to.
// Your message
$message="Copy and paste this link in your browser to activate your account: \r\n";
$message.="\n";
$message.="(serverAddress)/confirmation.php?passkey=$c_cd \r\n";
$message.="\n";
$message.="Thank you";
// send eml
$sml = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "Your email Is Not Registered. Please Register.";
}
// if your email succesfully sent
if($sml){
echo '<script> window.location.href="emlC.php"</script>';
}
else {
echo "Cannot Send Confirmation Link To Your email Address.";
}
// ---------------- Confirmation email ---------------- \\
$_SESSION['aI'] = $aI;
$_SESSION['pss'] = $pss;
$_SESSION['admin'] = 0;
$stmt = $conn->prepare("SELECT DISTINCT dN, dU, ex FROM doc WHERE aI != '0'");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row)
{
$ex = $row['ex'];
$dU = $row['dU'];
$dN = $row['dN'];
$insert = $conn->prepare("INSERT INTO doc (dN, dU, aI, ex)
VALUES (:dN, :dU, :aI, :ex)");
$insert->bindParam(':aI', $aI);
$insert->bindParam(':ex', $ex);
$insert->bindParam(':dU', $dU);
$insert->bindParam(':dN', $dN);
$insert->execute();
}
}
}
?>
Confirmation page code:
<?php
include('db.php');
// passkey that got from link
$pk=$_GET['pk'];
$t_awhole_conf="t_awhole";
// Retrieve data from table where row that match this passkey
$sql_conf1="SELECT * FROM $t_awhole_conf WHERE confirm_code ='$pk'";
$result_conf=mysql_query($sql_conf1) or die ('Error updating database: '.mysql_error());
// If successfully queried
if($result_conf){
// Count how many row has this passkey
$count=mysql_num_rows($result_conf);
// if found this passkey in our database, retrieve data from table "t_awhole"
if($count==1){
$rows=mysql_fetch_array($result_conf);
$fN = $rows['fN']; // capitalizes the first letter (6-26-14)
$lN = $rows['lN']; // capitalizes the first letter (6-26-14)
$aI = $rows['aI'];
$eml = $rows['eml'];
$pss = $rows['pss'];
$pss2 = $rows['pss2'];
$a_whole_conf="a_whole";
// Insert data that retrieves from "t_awhole" into table "a_whole"
$sql_conf2="INSERT INTO $a_whole_conf(fN, lN, aI, eml, pss, admin)
VALUES ($fN, $lN, $aI, $eml, $pss, $admin)";
$result_conf2=mysql_query($sql_conf2);
}
// if not found passkey, display message "Wrong Confirmation code"
else {
echo "Wrong Confirmation code";
}
// if successfully moved data from table"t_awhole" to table "a_whole" displays message "Your account has been activated" and don't forget to delete confirmation code from table "t_awhole"
if($result_conf2){
echo "Your account has been activated";
// Delete information of this user from table "t_awholeb" that has this passkey
$sql_conf3="DELETE FROM $t_awhole_conf WHERE confirm_code = '$pk'";
$result_conf3=mysql_query($sql_conf3);
}
}
?>
In your Registration form code, you have two lines that create the connection to the database (new PDO ...). You can further use $conn to execute statements.
In your Confirmation code, you don't create any connection before calling mysql_query (why the switch from PDO to mysql functions ?).
See the mysql_query documentation here.
Okay.. I am completely new to this PDO stuff.. I have tried to recreate my mysql script (working) to a PDO script (not working).. I have tested that my DB login informations is correctly programmed for PDO..
This is my PDO script...
<?
session_start();
//connect to DB
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the email and password
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
$sql -> execute();
$count = $sql->rowCount();
$result = $sql -> fetch();
// Now use $result['rowname'];
$stmt = $conn_business->prepare("SELECT * FROM members WHERE email='".$email."'");
$stmt ->execute();
$act = $stmt -> fetch();
//if email exists
if($count > 0)
{
//compare the password
if(strcmp($result["password"],$pass)==0)
{
// check if activated
if($act["activated"] == "0")
{
echo "act"; //account is not activated yet
}
else
{
echo "yes"; //Logging in
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no"; //Passwords don't match
}
else
echo "no"; //Invalid Login
?>
And this is my old mysql script...
session_start();
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the username and password
$sql="SELECT email, password members WHERE email='".$email."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$sql2="SELECT * FROM members WHERE email='".$email."'";
$result2=mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$act = $row2['activated'];
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
// check if activated
if($act == "0")
{
echo "act";
}
else
{
echo "yes";
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no";
}
else
echo "no"; //Invalid Login
Does anybody know, what I have done wrong? It is an automatically script.. It is called through AJAX and return data based on 'no', 'yes' and 'act' that tells the AJAX/jQuery script what to do.. As I said - the mysql script is working, so please if anyone could tell me what I have done wrong with the PDO script..
EDIT:
when it returns the data to the jQuery script, this should happen:
if yes: start session, redirect to page2.php with session started.
else if act: write in a field that the account is not activated.
else: write that email and password didn't match.
The thing is, that when I try to write the correct e-mail and password - it continues to write : "email and password didn't match" instead of redirecting.. When I say that it is not working it is because the mysql script does as described but the PDO script doesn't..
And I have tried to change the 'echo "no";' to 'echo "yes";' to see if the login would start anyway, but somehow it continues to write that the email and password didn't match..
SOLUTION:
I ahven't told this because I thought it was unnecessary, but the reason for it not to work was because of that i have had my old mysql code in comment marks on top of the page, so that the session_start command didn't work.. After deleting the old code it worked, but then I found something else to change, and that is in the PDO script when it is validating it says:
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
and then I just changed the '-' after $sql to '=' and now, everything works perfectly... Anyhow thank you everybody.. hope this code can help others..
Did you even read the manual before you "started using" PDO?
That is not how prepared statements are supposed to be used! Your code is filled with SQL injections.
Why are you selecting same row twice ?
The strcmp() is not for checing if one string is identical to another.
And hashing passwords as simple MD5 is just a sick joke.
session_start();
//very stupid way to acquire connection
require_once("connect.php");
//get the posted values
$email = htmlspecialchars($_POST['email'],ENT_QUOTES);
if (filter_var( $email, FILTER_VALIDATE_EMAIL))
{
// posted value is not an email
}
// MD5 is not even remotely secure
$pass = md5($_POST['psw']);
$sql = 'SELECT email, password, activated FROM members WHERE email = :email';
$statement = $conn_business->prepare($sql);
$statement->bindParam(':email', $email, PDO::PARAM_STR);
$output = 'login error';
if ($statement->execute() && $row = $statement->fetch())
{
if ( $row['password'] === $pass )
{
// use account confirmed
if ( $row['activated'] !== 0 ) {
$output = 'not activated';
$_SESSION['email'] = $email;
}
$output = 'logged in';
}
}
echo $output;
i believe the second query in your scripts is not necessary you could simple do
SELECT * FROM members WHERE email=:EMAIL AND password=:PWS;
use bindParam method
$qCredentials->bindParam(":EMAIL",$EMAIL);
$qCredentials->bindParam(":PWS",$PWS);
then do more understable outputs rather than yes or no..
try "Unable to login: Invalid credentials supplied" for invalid types of values or "Unable to login: Invalid credentials, couldn't find user" for invalid user credentials.
You could try to start the session after the user has been successfully logged in your IF condition returning yes, and the methods
$PDOstatement->debugDumpParams()
$PDOstatement->errorInfo()
$PDOstatement->errorCode()
will help you understand what went wrong with a query!