i need to set a session called BusinessID in php but its not working on my live server , i cannot figure out what is wrong with it
what happens is that it executes the first query but does not set session and redirect to dashboard.php
heres the code
<?php
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
if(isset($_POST["register"]))
{
$company = $_POST["company"];
$address = $_POST["address"];
$contact = $_POST["contact"];
$city = $_POST["city"];
$tags = $_POST["tags"];
$email = $_POST["email"];
$password = $_POST["password"];
$sql="INSERT INTO business(`companyname`, `email`, `password`, `address`, `tel`, `city`, `tag`,`status`, `created_at`,`type`)
VALUES('$company','$email','$password','$address','$contact','$city','$tags','unblocked',CURRENT_TIMESTAMP,'Null')";
if (mysqli_query($link, $sql)) {
$query = "select id from business where email='$email' and password='$password'";
$result = mysqli_query($link,$query);
if (mysqli_fetch_assoc($result))
{
$_SESSION["businessID"] = $result[0]["id"];
header("Location: dashboard.php");
}
else
{
header("Location: login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// Close connection
mysqli_close($link);
?>
You have missed
session_start();
after php tag
You can set the Session first in the code.
<?php
// Start the session
session_start();
?>
Check this one. https://www.w3schools.com/php/php_sessions.asp
Related
I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?
You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.
so i have a login page which works very well using php mysqli, but is non prepare so i usually use mysqli_real_escape to secure the data.
But am now migrating to using prepared statement, have manage this with my register page and this as work very well.
here is my non prepared login code:
$loginQuery = "select * from user where user_name = '$user_name' AND password = '$password'";
$result = mysqli_query($con,$loginQuery);
if(mysqli_num_rows($result)){
$row = mysqli_fetch_array($result);
// password verify
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = strtoupper($row['user_name']);
$user_type = strtolower($row['user_type']);
if(strtolower($user_type) == 'member'){
$_SESSION['user_type'] = 'member';
//header('Location: member-dashboard-home.php');
header('Location: profile.php');
}elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
$_SESSION['user_type'] = strtolower($user_type);
//header('Location: admin-dashboard-home.php');
header('Location: profile.php');
}
}else{
$_SESSION['main_notice'] = "Invalid login details!";
header('Location: '.$_SERVER['PHP_SELF']);exit();
}
And below is my effort in using prepared statement.
$stmt = $mysqli->prepare("SELECT user_name FROM user WHERE user_name = ? ");
$stmt->bind_param('s', $user_name);
$stmt->execute();
$stmt->bind_result($user_name);
if($res = $stmt->num_rows()){
$row = $stmt->fetch_array($res);
// password verify
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = strtoupper($row['user_name']);
$user_type = strtolower($row['user_type']);
if(strtolower($user_type) == 'member'){
$_SESSION['user_type'] = 'member';
//header('Location: member-dashboard-home.php');
header('Location: profile.php');
// exit;
}elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
$_SESSION['user_type'] = strtolower($user_type);
//header('Location: admin-dashboard-home.php');
header('Location: profile.php');
//exit;
}
}else{
$_SESSION['main_notice'] = "Invalid username OR password details, please try again!";
header('Location: '.$_SERVER['PHP_SELF']);exit();
}
}
I didn't get any error code when i tried to login, but the form just return blank and didn't redirect to user profile.
I don't think this is redirection issue tho or is it?
i don't i arrange the $stmt properly, hopefully you guy see what i can't.
thanks in advance
From your comment,
i did include at the top and i receive this error Notice: Undefined variable: mysqli in /home/connection.php... ...
Look at your code here,
$con = new mysqli("localhost", "***", "***", "***");
if ($mysqli->connect_errno) {
^^^^^^^^^^^^^^^^^^^^^^
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
}
Your connection handler is $con, not $mysqli, it should be like this:
$con = new mysqli("localhost", "***", "***", "***");
if ($con->connect_errno) {
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
Update(1): Change your code in the following way,
$stmt = $con->prepare("SELECT * FROM user WHERE user_name = ? ");
$stmt->bind_param('s', $user_name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
// username exists
$row = $result->fetch_array();
// your code
}else{
// username doesn't exist
// your code
}
The member system code always redirect me to "email already registered page"
Thats the code I use in processing to check whether the email, that will be the username,
is already been taken or not
please help!!!!
<?php
$db_host = "localhost";
$db_user = "ms_admin";
$db_pass = "secretpassword";
$db_name = "member_system";
$connection = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if(mysqli_connect_errno())
die("Databse connection failed." . mysqli_connect_error()
. " (" . mysqli_connect_errno() . ")" );
?>
<?php
function check_email($e_mail)
{
$query = "SELECT email FROM members ";
$query .= "WHERE email='$e_mail'";
$result = mysqli_query($connection, $query);
$num_rows = mysqli_num_rows($result);
if($num_rows>0) header("Location: registration_successful.php");
else header("Location: registration_unsuccessful.php");
}
?>
<?php
$full_name = ucwords($_POST["full_name"]);
$email = strtolower($_POST["email"]);
$password = md5($_POST["password"]);
check_email($email);
?>
I changed those:
if($num_rows>0) header("Location: registration_successful.php");
else header("Location: registration_unsuccessful.php");
to:
if($num_rows>0) header("Location: registration_unsuccessful.php");
else header("Location: registration_successful.php");
It seems that ($num_rows>0) always return FALSE :(
please help,,
Thank you....
$connection variable is missing in check_email() please set global $connection; for db connection like
function check_email($e_mail){
global $connection;
$query = "SELECT email FROM members ";
$query .= "WHERE email='$e_mail'";
$result = mysqli_query($connection, $query);
$num_rows = mysqli_num_rows($result);
if($num_rows>0) header("Location: registration_successful.php");
else header("Location: registration_unsuccessful.php");
}
check_email($email);
OR
function check_email($e_mail, $connection){
$query = "SELECT email FROM members ";
$query .= "WHERE email='$e_mail'";
$result = mysqli_query($connection, $query);
$num_rows = mysqli_num_rows($result);
if($num_rows>0) header("Location: registration_successful.php");
else header("Location: registration_unsuccessful.php");
}
check_email($email, $connection);
Though i like 1st one :)
The problem is in the test before you redirect the user :
// if the rows are > 0 then it means the email already exists
// which means we should redirect to the unsuccessful registration page
if($num_rows>0) header("Location: registration_unsuccessful.php");
else echo header("Location: registration_successful.php");
// else, we redirect to successful registration page (meaning the email does not exists in DB)
and as #Mihai mentioned, you forgot to concatenate your query string.
Try below code
<?php
function check_email($e_mail)
{
$query = "SELECT email FROM members";
$query .= "WHERE email='$e_mail'";
$result = mysqli_query($connection, $query);
$num_rows = mysqli_num_rows($result);
if($num_rows>0) header("Location: registration_unsuccessful.php");
else echo header("Location: registration_successful.php")
}
?>
<?php
$full_name = ucwords($_POST["full_name"]);
$email = strtolower($_POST["email"]);
$password = md5($_POST["password"]);
check_email($email);
?>
Use
$query = "SELECT email FROM members ";
$query .= "WHERE email='".$e_mail."'";
You missed Space after members , copy paste it in your code.
OR use simple solution
$query = "SELECT email FROM members WHERE email='".$e_mail."'";
Update
mysqli_store_result($connection);
$num_rows= mysqli_num_rows($user_query);
if($num_rows>0)
Reason ->
Use store_result for buffering the result.
I am learning PHP and able to create a Registration form. But the code doesn't working properly. It always goes to else statement of Username exists Try Again. Any help appreciated and any explanation greatly welcomed :)
function session() {
$usn = $_POST['username'];
$pwd = $_POST['password'];
$email = $_POST['Email'];
$con=mysqli_connect("********","***********","**********","*********");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Accounts
WHERE username = '$usn'");
If($result == Null) {
mysqli_query($con,"INSERT INTO Accounts (username, password, Email)
VALUES ('$usn', '$pwd','$email')");
$result = mysqli_query($con,"SELECT * FROM Accounts WHERE username = '$usn'");
while($row = mysqli_fetch_array($result)) {
if (($row['password']==$pwd) and ($row['Email']==$email)) {
echo "Registration Success";
}
else {
echo "Registration Failed";
}
}
}
else {
echo "Username Exists Try Again";
}
mysqli_close($con);
}
$result will never be null. You need to check for something like number of rows -
$row_cnt = mysqli_num_rows($result);
If that is greater than 0, then go to your else.
This code works, I believe. But it doesn't echo the confirmation or error.
<?php
require 'config.php';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$servername="localhost";
$username="root";
$conn= mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("web", $conn);
$mypassword=$_POST['pwd'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$address=$_POST['address'];
$location=$_POST['location'];
$sqlsel="SELECT * FROM users WHERE username='$id' AND pwd='$mypassword' ";
$result=mysql_query($sqlsel,$conn) or die(mysql_error());
$count=mysql_num_rows($result);
if($count==1){
$sql="UPDATE users " .
"SET fname = '$fname',
lname = '$lname',
address = '$address',
location = '$location'" .
"WHERE pwd = '$mypassword'";
$res = mysql_query( $sql, $conn );
//IS THIS CORRECT TO REFRESH THE PAGE???
header("Location: edit.php?id=" . $id);
//IT WON'T ECHO....
echo 'Information updated.';
}
else {
//ALSO THIS ONE...
echo print "Invalid Password.";
}
mysql_close($conn);
}
?>
It seems to work on my other form but it won't work on this edit form.
How can I resolve this?
After header location, anything won't work.
what you could do is
header("Location: edit.php?id=" . $id . "&msg=1");
then on edit.php
just get $_GET["msg"] like
if isset($_GET["msg"])
echo 'Information updated.';
You have sent redirection headers, after that browser starts to redirect and doesnt echo. Remove the header call.
Comment out this part
//header("Location: edit.php?id=" . $id);
Also
echo print "Invalid Password.";
Should be
echo "Invalid Password.";
when header location is declared it will redirect page ONLY when its the first php/html declared
anything after wont work or display