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
Related
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
<?php
require 'includes/common.php';
$email=$_POST['email'];
$password=$_POST['password'];
$email= mysqli_real_escape_string($con, $email);
$password= mysqli_real_escape_string($con, $password);
//md5($password);
$select_user_query="select id , email from users where email='$email' and password= $password";
//removed 'email' to email//
$select_user_result= mysqli_query($con, $select_user_query) or die (mysqli_error($con));
if (mysqli_num_rows($select_user_result==0))
{
echo 'There no such user ';
}
else
{
$row=mysqli_fetch_array($select_user_result);
$_SESSION['email']=$email;
$_SESSION['id']= $row[0];
header('location:products.php');
}
?>
here is the code
**
here i am geting
email and password from post method
From my login page
i think most of the code is right
If i login with a user it logs in with any password
**
Your error is not in the query. it is on your condition
if(mysqli_num_rows($select_user_result) == 0){
echo 'No User found';
}else{
echo 'oK';
}
You ca try this way. I think your error is you inserted the ==0 inside the mysqli_num_rows() it must be outside.
I'm assuming password is a string..
$select_user_query="select id , email from users where email='$email' and password= $password";
is what you wrote,
you've maybe forgotten to put single quotes around $password here.
Please verify this code:
I use this code for login:
if user provides the Correct Credentials-- If part will work,
if not then else part will be work
<?php
// Grab User submitted information
$user = $_POST["username"];
$pass = $_POST["password"];
//$uc_id=$_GET["user_check_id"];
// Connect to the database
$con = mysqli_connect("localhost","root","pass123");
// Make sure we connected successfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysqli_select_db($con, "login");
//$query ="SELECT user_check_id from loginpage where username='$user' and password='$pass'";
$query ="SELECT * from loginpage where username='$user' and password='$pass'";
//echo $query;
if ($query)
{
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
if($row["username"]==$user && $row["password"]==$pass)
{
echo "Welcome Admin";
}
else
{
echo"Please Enter the Correct Username/Password...!!";
}
}
?>
Put single quotes around $password in your query and then try.
I'm trying to show welcome message with user name. I have a session setted up, everything is working without errors, however I can't make user name appear next to "welcome". I read loads of posts, most of the suggestions were asking to add session_start(); before echo. Still nothing..
Here is code for session.php if someone could help me:
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["user_name"])) {
header('Location: login.php');
}
?>
And here is code for the profile page where user name should appear:
<?php
include('session.php'); //file shown above
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i>
<?php
session_start();
echo $_SESSION['fname'];
?>
</i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
I'm just learning PHP and this is a basic test.
Thank You for any information.
Hava a nice day !
UPDATE:
loginscript.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$uname=$_POST['uname'];
$password=$_POST['password'];
$conn = mysql_connect("**.***.***.***", "*********", "*********");
$uname = stripslashes($uname);
$password = stripslashes($password);
$uname = mysql_real_escape_string($uname);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("*********", $conn);
$query = mysql_query("select * from WebsiteUsers where password='$password' AND uname='$uname'", $conn);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$uname;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
mysql_close($conn);
}
}
?>
logout.php:
<?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>
You need to quote your array keys, for example you have:
$_SESSION["UserID"] = $row[user_id];
But this should in fact be
$_SESSION["UserID"] = $row['user_id'];
Note the single quotes around the array key in $row. I see you use double quotes and I think there are minor differences but the point is, use quotes around array key strings. Please read https://stackoverflow.com/a/2317969/3536236 .
There also might be an issue that you set the value with double quotes and then call the value with single quotes --
$_SESSION["fname"] = $row['fname'];
print $_SESSION['fname'];
But that's just a theory there.
Further debugging:
Print_r($_SESSION); <== what does this give you after the values are set?
Use MySQLi or PDO rather than MySQL_ as this is now deprecated and should no longer be used.
Add exit; after your header relocation calls. Because the rest of the script will still execute before the relocation header call is run, so you need to tell the script to stop executing as soon as you reach the header(location: ) point.
Be consistent and have all single ' or all double " quotes in your array key identifiers.
Remove session_start() from inside your HTML, this function call MUST be at the very start/ top of the page, and nowhere else. You can replace this session_Start with the print_r referenced above, for debugging purposes.
Debugging
First step, you need to enable errors on your page, so whatever page you're working on add this code to the top:
error_reporting(E_ALL);
ini_set('display_errors', 1);
This will output any errors the code fines to your browser when you run the page. Extremely useful and informative.
Next, I will show you the process you need to establish where in the logic chain the data is being "lost".
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
print_r($result) <== should return something like "this is a type 4 element". False shows your DB is empty or your MySQL code is bad.
$row = mysql_fetch_array($result);
var_dump($row) <== should return the values from the DB. It should also tell you what data type this variable is, as you demand an array, below:
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
}
else {
die("This will display if the IF statement does not show TRUE.");
}
The die statement above would show you that the error is not in the session but more in your handling of the MySQL output,
I reaffirm you should use single quotes on all your array keys everywhere! Keep it consistent!!
Restructure your MySQL to be more this shape:
mysql_query($query) or print_r("line ".__LINE__.": ".mysql_error());
So that if there is any issue with your MySQL code it is found and shown to you. Much of programming is about finding where the error comes from, rather than the error itself.
Try something like this:
$db_result = mysql_fetch_array($result); $row = $db_result[0];
instead of :
$row = mysql_fetch_array($result);
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
if(mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if($_SESSION["fname"]=="") {// changed from $_SESSION['user_name'],checks if sesison is empty , will redirect to login page.
header('Location: login.php');
}
?>
You have to use session_start(); in the start of the profile.php
When the user correctly inserts his information in the login form it redirects to the home page which is what i want but i'm having a problem when the user inputs wrong info. It just shows connected successfully and database successfully selected. It stops on the page checklogin.php. As if it doesn't even read the session part. Please go through my code.
Here's my code for the register form:
<?php
$con=mysql_connect("localhost","root","");
if(!$con){
die('Could not connect:' .mysql_error());
}
echo "Connected successfully.";
$database=mysql_select_db('90210store');
if(!$database){
die('<br>Could not select database:' .mysql_error());
}
echo "<br>Database successfully selected";
$FirstName=$_POST['FirstName']; //to get the information written in the form
$LastName=$_POST['LastName'];
$EmailAdd=$_POST['EmailAdd'];
$check_list=$_POST['check_list'];
$dob=$_POST['dob'];
$Gender=$_POST['gender'];
$Password=$_POST['Password'];
$first= "INSERT INTO login
(FirstName,LastName,EmailAdd,Newsletter,DOB,Gender,Password)
VALUES
('$FirstName','$LastName','$EmailAdd','$check_list','$dob','$Gender','$Password')";
$result=mysql_query($first);
if($result){
echo('<br>Data enterred successfully');
}
else{
echo('<br>Fail');
}
if($result)
{
header('Location: phpredirectlogin.php');
}
mysql_close($con);
?>
Then this is the page it redirects to(phpredirectlogin.php):
<?php
echo "<script>alert('Redirecting you to the login page');</script>";
echo "<script>window.location = 'account.html';</script>";
?>
This is the php page which checks the login(checklogin.php):
<?php
$Email=$_POST['email'];
$Pwd=$_POST['pwd'];
$con=mysql_connect("localhost","root","");
if(!$con){
die('Could not connect:' .mysql_error());
}
echo "Connected successfully.";
$database=mysql_select_db('90210store');
if(!$database){
die('<br>Could not select database:' .mysql_error());
}
echo "<br>Database successfully selected";
$result = mysql_query("SELECT * FROM login
WHERE EmailAdd='$Email' AND Password='$Pwd'") or die('QueryFailed:'.mysql_error());
while($row=mysql_fetch_array($result))
{
session_start();
$_SESSION['ID']=1234;
header('Location:checklogin1.php');
}
mysql_close($con);
?>
Then this page redirects the user to checklogin1.php.The code is:
<?php
session_start();
if(!isset($_SESSION['ID']))
{
header('Location:account.html');
}
else
{
header('Location:90210.html');
}
?>
There has to be some error somewhere but i can't seem to figure it out. Any help will be appreciated. Thank you.
Change this
$result = mysql_query("SELECT * FROM login
WHERE EmailAdd='$Email' AND Password='$Pwd'") or die('QueryFailed:'.mysql_error());
while($row=mysql_fetch_array($result))
{
session_start();
$_SESSION['ID']=1234;
header('Location:checklogin1.php');
}
to this
$result = mysql_query("SELECT * FROM login
WHERE EmailAdd='$Email' AND Password='$Pwd' LIMIT 1") or die('QueryFailed:'.mysql_error());
if (mysql_num_rows($result) == 1 ) {
$_SESSION['ID']=1234;
header('Location:checklogin1.php');
}
And get the session_start() right to the beginning of the code.
Moreover, you could redirect to the respective pages from here itself so that you have only one redirect instead of two and get rid of checklogin1.php. Thus you may edit the above condition to the following:
if(mysql_num_rows($result) == 1) {
$_SESSION['ID']=1234;
header('Location:90210.html');
} else {
header('Location:account.html');
}
At first remove all statuses: ex. echo "<br>Database successfully selected";
session_start();
should be at in each page on first line.
In checklogin.php add checking mysql result count:
$res_count = mysql_num_rows($result);
if($res_count != 0) {
$_SESSION['ID']=1234;
header('Location:checklogin1.php');
}
I have created an html form for registering and when a user has successfully registered I want them to be automatically redirected back to my index.html page and for an alert to pop up tell them they have Registered Successfully. Currently my alert works but it just opens up in a blank page. I have tried putting in header ("location:../index.html") but that has not worked, it just directs me straight to the page without giving me the alert i want. Can anyone help with this?
<?php
$con = mysql_connect("localhost","root","") or die(mysql_error());
$select_db = mysql_select_db("mayan",$con);
if(isset($_POST['register']))
{
$firstname=$_POST['first_name'];
$lastname=$_POST['last_name'];
$address=$_POST['address'];
$postcode=$_POST['postcode'];
$emailaddress=$_POST['emailaddress'];
$password=$_POST['password'];
$query = "select emailaddress FROM mayan_users where emailaddress='$emailaddress'";
$link = mysql_query($query)or die(mysql_error());
$num = mysql_num_rows($link);
if ($num>0){
echo 'Email already exists'; //email already taken
}
else {
$insert_query = "insert into `mayan_users`(`firstname`,`lastname`,`address`,`postcode`,`emailaddress`,`password`) values('$firstname','$lastname','$address','$postcode','$emailaddress','$password')";
$result = mysql_query($insert_query)or die(mysql_error());
if(success)
{
echo "<script type=\"text/javascript\">".
"alert('success');".
"</script>";
}
}
}
?>
I use this code to redirect someone back to the homepage after filling in a form on a website.
if(empty($errors))
{
//send the email
echo '
<script type="text/javascript">
alert("YOUR MESSAGE");
window.location.href = "http://www.yoursite.com";</script>';
}
Use this function when redirecting:
function redirect($url) {
if(!headers_sent()) {
//If headers not sent yet... then do php redirect
header('Location: '.$url);
exit;
} else {
//If headers are sent... do javascript redirect... if javascript disabled, do html redirect.
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>';
exit;
}
}
So you want to redirect to the same page but with a ?=XXX Get value
Your code would look something like this:
<?php
if ($_GET['success'] == 1){
echo "<script type=\"text/javascript\">".
"alert('success');".
"</script>";
}
$con = mysql_connect("localhost","root","") or die(mysql_error());
$select_db = mysql_select_db("mayan",$con);
if(isset($_POST['register']))
{
$firstname=$_POST['first_name'];
$lastname=$_POST['last_name'];
$address=$_POST['address'];
$postcode=$_POST['postcode'];
$emailaddress=$_POST['emailaddress'];
$password=$_POST['password'];
$query = "select emailaddress FROM mayan_users where emailaddress='$emailaddress'";
$link = mysql_query($query)or die(mysql_error());
$num = mysql_num_rows($link);
if ($num>0){
echo 'Email already exists'; //email already taken
}
else {
$insert_query = "insert into `mayan_users`(`firstname`,`lastname`,`address`,`postcode`,`emailaddress`,`password`) values('$firstname','$lastname','$address','$postcode','$emailaddress','$password')";
$result = mysql_query($insert_query)or die(mysql_error());
if(success)
{
redirect('index.php?sucess=1');
}
}
}
?>
To redirect by JavaScript use:
window.location = "http://www.google.com/";
But I would suggest adding a link for the user to click on as well as some users might have JavaScript disabled. And I'd put a timeout on the redirection, so the user has a few seconds to read the page. E.g.:
if (success) {
echo "<script type=\"text/javascript\">" .
"setTimeOut(function() {" .
" window.location = 'http://www.google.com';" .
"}, 2500);" .
"</script>";
}
You can do a variable in the index page like "index.php?success". Then just check for this request by if(isset($_GET['success']). And add some login to that IF.
1) First of all change your index.html into a php file: index.php
2) On the top of the index.php file write
<?php
session_start();
?>
3) In the body of the index.php file you can:
either print a message
<?php
if(isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
or alert with javascript
<?php
if(isset($_SESSION['message'])) {
echo '<script> alert(\'Success\'); </script>';
unset($_SESSION['message']);
}
?>
4) On this action file you gave us
<?php
// START THE SESSION
session_start();
$con = mysql_connect("localhost","root","") or die(mysql_error());
$select_db = mysql_select_db("mayan",$con);
if(isset($_POST['register']))
{
$firstname=$_POST['first_name'];
$lastname=$_POST['last_name'];
$address=$_POST['address'];
$postcode=$_POST['postcode'];
$emailaddress=$_POST['emailaddress'];
$password=$_POST['password'];
$query = "select emailaddress FROM mayan_users where emailaddress='$emailaddress'";
$link = mysql_query($query)or die(mysql_error());
$num = mysql_num_rows($link);
if ($num>0){
$_SESSION['message'] = 'Email already exists'; //email already taken
}
else {
$insert_query = "insert into `mayan_users`(`firstname`,`lastname`,`address`,`postcode`,`emailaddress`,`password`) values('$firstname','$lastname','$address','$postcode','$emailaddress','$password')";
$result = mysql_query($insert_query)or die(mysql_error());
if($result)
{
$_SESSION['message'] = 'Success';
}
}
}
// redirect to main page
header("Location: /");
?>