Please could someone help me understand why the echo command, 'Incorrect Membership Number, please try again.' isn't working?
Everything else seems to be functioning okay.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'DBNAME');
define('DB_USER', 'USER');
define('DB_PASSWORD', 'PASS');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());
$mem_no = $_POST['mem_no'];
function SignIn()
{
session_start();
if (!empty($_POST['mem_no'])) {
$query = mysql_query("SELECT * FROM members where mem_no = '$_POST[mem_no]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if (!empty($row['mem_no'])) {
$_SESSION['mem_no'] = $row['mem_no'];
header("Location: " . $_POST['cat_link']);
} else {
echo "Incorrect Membership Number, please try again.";
} // This line is not executing
} else {
echo "Please go back and enter a Membership Number";
}
}
if (isset($_POST['submit'])) {
SignIn();
}
HTML Form as follows:
<form method="post" action="/check.php">
<p>Membership No.</p>
<input name="mem_no" type="text" id="mem_no">
<input name="cat_link" type="hidden" value="https://www.redirectlink.com">
<input name="submit" type="submit" id="submit" value="AELP Member Rate">
</form>
Link to test: https://www.eiseverywhere.com/ehome/index.php?eventid=106953&tabid=239372 and a valid 'Membership Number' is 1234 if you wish to test.
Leaving the form blank does give the correct error message and entering a valid number does redirect me correctly, but inputting an invalid number (9999 for e.g.) doesn't give me the correct output message.
Thank you in advance for any responses.
Regards,
Ash
You need to count rows, because even when a sql query has no results it is not empty. So count it.
function SignIn()
{
session_start();
if (!empty($_POST['mem_no'])) {
$query = mysql_query("SELECT * FROM members where mem_no = '". $_POST['mem_no'] ."'") or die(mysql_error());
#count rows
$count = mysql_num_rows($query);
$row = mysql_fetch_array($query) or die(mysql_error());
#check count
if ($count != 0) {
$_SESSION['mem_no'] = $row['mem_no'];
header("Location: " . $_POST['cat_link']);
} else {
echo "Incorrect Membership Number, please try again.";
}
} else {
echo "Please go back and enter a Membership Number";
}
}
Just a small reminder. mysql_ class in PHP is deprecated and will be removed in the next versions, I suggest you going to use mysqli_ or work with PDO's
Your script is hard to debug for several reasons:
It's unindented (I've fixed that for you in the question)
You're using deprecated mysql functions (see this). Switch to PDO or mysqli.
You have several exit points in your script. Everytime you make a call to the database, you "die" if you fail. that's not good
regardless, I suspect that one of those "die" making your script end prematurely. Instead of using die, handle the errors yourself.
I think this should work:
(Also put error reporting at the top!)
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
<?php
session_start();
define('DB_HOST', 'localhost');
define('DB_NAME', 'DBNAME');
define('DB_USER', 'USER');
define('DB_PASSWORD', 'PASS');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
//$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error()); //Useless
$mem_no = $_POST['mem_no'];
function SignIn() {
if (!empty($_POST['mem_no'])) {
$query = mysql_query("SELECT * FROM members WHERE mem_no = '" . $_POST['mem_no'] . "'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
$count = mysql_num_rows($query);
if ($count >= 1) {
$_SESSION['mem_no'] = $row['mem_no'];
header("Location: " . $_POST['cat_link']);
} else {
echo "Incorrect Membership Number, please try again.";
} // This line is not executing
} else {
echo "Please go back and enter a Membership Number";
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
It doesnt make sense to put two else statements in a row. Take the last else block out of the inner if block
if(!empty($_POST['mem_no'])) {
//code
}else{
echo "Please go back and enter a Membership Number";
}
That should execute just fine
Related
So for some reason if the password is correct it knows and takes the user to the correct user account, but if the pass is wrong, it wont log them in but still takes them to the account page that isn't logged in.
Can someone please help me out to not re-direct them if the password is wrong
<?php
session_start();
//$connection = mysqli_connect('localhost', 'root', '');
$connection = mysqli_connect("pdb18.awardspace.net","*****","******","*****");
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, '******');
if (!$select_db)
{
die("Database Selection Failed" . mysqli_error($connection));
}
$username=trim($_POST['username']);
$password=trim($_POST['password']);
//$encoded_password = base64_encode($password);
$sql = "SELECT * from register where Username='".$username."' and Password='".$password."'";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));
$result = $con->query($sql);
$count = mysqli_num_rows($result);
//echo $count;
if ($count == 1){
while($row = $result->fetch_assoc()) {
$id=$row['id'];
}
$_SESSION['User'] = $username;
$_SESSION['UserId'] = $id;
echo "valid";
}
else{
echo "Invalid";
}
?>
Remove this line:
$result = $con->query($sql);
You are using procedural functions, mysqli_*.
This part of code $con->query is OOP style, which you are not using in your code, and overwritting the value o $result variable.
You can use both styles, but you should use the same connection, or $connection in your case.
I'm trying to save data from a multi-page form into a database. I followed this tutorial but the connection always fails. I had to change to function from mysql_connect to mysqli_connect as I am running PHP7, so this could be part of the issue. Here is the code:
<?php
session_start();
if (isset($_POST['state'])) {
if (!empty($_SESSION['post'])){
if (empty($_POST['address1'])
|| empty($_POST['city'])
|| empty($_POST['pin'])
|| empty($_POST['state'])){
// Setting error for page 3.
$_SESSION['error_page3'] = "Mandatory field(s) are missing, Please fill it again";
header("location: finder-step-3.php"); // Redirecting to third page.
} else {
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']); // Function to extract array.
$connection = mysqli_connect("localhost", "root", "root");
$db = mysqli_select_db($connection, "finder_form"); // Storing values in database.
$query = mysqli_query($db, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')", $connection);
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
unset($_SESSION['post']); // Destroying session.
}
} else {
header("location: finder-step-1.php"); // Redirecting to first page.
}
} else {
header("location: finder-step-1.php"); // Redirecting to first page.
}
?>
Can anyone spot where I am going wrong? Thanks in advance!
Update 1:
#Damon Swayn, I have changed it to the below but still receive the form submission failed message:
$connection = mysqli_connect("localhost", "root", "root", "finder_form");
$query = mysqli_query($connection, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')", $connection);
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
#lps, I setup the following on a test.php page in the same directory and it connected successfully:
<?php
$con = mysqli_connect('localhost', 'root', 'root') or die('Could not connect the database : Username or password incorrect');
mysqli_select_db($con, 'finder_form') or die ('No database found');
echo 'Database Connected successfully';
?>
Update 2: Solved
The changes suggested by Damon Swayn worked, I just had to remove the $connection at the end of the query. Here is the working code:
$connection = mysqli_connect("localhost", "root", "root", "finder_form");
$query = mysqli_query($connection, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')");
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
mysqli_connect() can take 4 parameters, the fourth being the database name.
you are using the return value of mysqli_select_db() as the connection param for every following call, mysqli_select_db() returns a boolean true/false value, try replacing the $db param in the following calls after mysqli_select_db() with the $connection variable.
This is all really new to me and I only know the very basics. I'm creating a frontend login for a webpage (obviously security isn't a huge deal or I wouldn't be doing it). I keep getting in issue with my "where" clause, stating that the "user" does not exist. Database is setup like this:
dbname=connectivity
table=users
users has id, user, and pass.
Anyone want to give me some pointers? Thanks in advance.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Ya done goofed: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Ya done goofed: " . mysql_error());
function SignIn()
{
session_start();
if(!empty($_POST['user']))
{
$query = mysql_query("SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['user']) AND !empty($row['pass']))
{
$_SESSION['user'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Please stop using mysql_*. use mysqli_* or PDO. Have a look to the code:-
<?php
// Force PHP to show errors
error_reporting(E_ALL); // Get all type of errors if any occur in code
ini_set('display_errors',1); // Display those errors
session_start(); // start session
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("connection not established"); Or use $con = mysqli_connect('localhost','root','','connectivity') or die("connection not established");
if(isset($_POST['submit'])){
SignIn();
}
function SignIn(){
if(!empty($_POST['user'])) {
$username = mysqli_real_escape_string($con , $_POST['user']); // prevent form SQL injection
$password = mysqli_real_escape_string($con , $_POST['pass']); // prevent form SQL injection
$query = mysqli_query($con,"SELECT * FROM users where user = '".$username."' AND pass = '".$password."'") or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){ // check count of resultset
$_SESSION['user'] = $_POST['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}else{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
?>
There are some issues here:
SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'
The quote styles are all over the place. Try this:
SELECT * FROM `users` WHERE `user` = '$_POST[user]' AND `pass` = '$_POST[pass]'
Also, you should pre-process for SQL injection if you're not already.
This is the correct formatted SQL.
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error());
One thing to note is that you MUST escape and validate all global variables. For more information I strongly recommend you to read this SO post: How can I prevent SQL injection in PHP?
There are multiple things wrong with your code check it down below:
<?php
session_start(); // This needs to be on top of every page
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
// Use mysqli_* as mysql_* is depracted and will be removed
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die("connection not established");
// Add a bit of security
$user = mysqli_real_escape_string($con, $_POST['user']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
function SignIn($user, $pass) {
// Add backticks ` around column and table names to prevent mysql reserved word error
$query = mysqli_query($con, "SELECT * FROM `users` WHERE `user` = '$user' AND `pass` = '$pass'");
// No need to fetch the data you already have
// Check if the query returns atleast 1 row (result)
if( mysqli_num_rows($query) >= 1 ) {
$_SESSION['user'] = $pass;
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
if(isset($_POST['submit']) && !empty($user) && !empty($pass) ) {
SignIn($user, $pass);
} else {
echo "SORRY... THERE ARE EMPTY FIELDS... PLEASE RETRY...";
}
?>
Just changed your code like follows:
SELECT * FROM users where user ='$_POST[user]'AND pass = '$_POST[pass]'
That line need to rewrite like follows:
SELECT * FROM users WHERE user = '".$_POST[user]."' AND pass = '".$_POST[pass]."'
I believe that should work in every server without any kind of trouble.
You are missing quotations
Corrected code:
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error())
I am trying to UPDATE a row from a MySQL Table with a button in my html page. When i press the button it outputs "Query failed". What should I change to make it work ?
My Html Code:
<form action="status1.php">
<input type="submit" name="approve" value=" + ">
</form>
My Php Code:
<?php
require_once('config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="UPDATE applications SET (status) values('1') WHERE today='$today'";
$result = mysql_query($qry);
if($result) {
header("location: applications-admin.php");
exit();
}else {
die("Query failed");
}
?>
You're using the wrong syntax for an UPDATE; it should be something like this:
$qry="UPDATE applications SET status='1' WHERE today='$today'";
HOWEVER
You should look at moving away from the mysql_* functions, as they're being deprecated - you should look at using PDO or mysqli instead.
UPDATE tablename SET fieldname=value WHERE [conditions]
<body>
<?php
session_start();
function salt($pw) {
$salt = "This comment should suffice as salt.";
return sha1($salt.$pw);
}
if (isset($_POST['submit'])) {
$link = mysql_connect('localhost', 'codekadiya', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password = salt($password);
$query = mysql_query("SELECT * FROM test WHERE username='$username' AND password='$password'");
if (mysql_num_rows($query)== 0) {
header("location:register.php");
exit;
}
else {
$_SESSION['user'] = $username;
header("location: register.php");
}
}
?>
</body>
I checked on my Connection. It says connection successful but I cant figure out what the other mistake are. Can someone guide me the mistake I have done? I can't find it.
echo 'Connected successfully';
mysql_close($link);
So you're closing the connection and then try to run queryes ? how should that work out ?
You should close the connection ( mysql_close($link); ) after you made you're query to the database ( meaning after $query = mysql_query("SEL..... )
You haven't really told us what doesn't work exactly, but it seems you are closing the MySQL link before the authentication query.
i don't tend to use isset instead i just use if($_POST["something"]) that way i get more relevant errors
also - you're closing the $link before you use it - ???