PHP cannot show tables from MySqli Query - php

I am trying to figure out why I can connect to a database, but cannot access the data in it.
Here's my configuration:
//config.php
<?php
define("HOST", "MYSERVERNAMEISHERE");
define("DATABASE", "users");
?>
My user logs in, and their information is passed to be checked:
//login.php
<?php
if ($_POST) {
if ($_POST["user"] && $_POST["password"]) {
include_once "config.php";
define("USER", $_POST["user"]);
define("PASSWORD", $_POST["password"]);
$link = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($link) {
$link->close();
if ($_SESSION) {
session_destroy();
}
session_start();
$_SESSION["user"] = $_POST["user"];
$_SESSION["password"] = $_POST["password"];
}
}
}
if ($_SESSION) {
header('Location: profile.php');
}
else {
header('Location: login.html');
}
?>
When they pass, they get to see their profile page.
//profile.php
<?php
session_start();
if (!$_SESSION["user"] || !$_SESSION["password"]) {
session_destroy();
header("Location: login.html");
}
else {
include_once "config.php";
}
$link = new mysqli(HOST, USER, PASSWORD, DATABASE) or die("Unable to connect to database");
$result = $link->query("SHOW TABLES") or die("Unable to show tables");
...
ADDITIONAL PHP AND HTML CODE AFTER THIS POINT
The problem is that the process dies when I try to query the mysqli link. (I get Unable to show tables) Right now, the SHOW TABLES is just filler for debugging; I will actually have useful mysqli queries when I figure out the issue.
Please help me determine where my bug is. If you find a typo or a reference link for me, sorry for wasting your time. I've been researching and debugging for hours now.
Thanks very much in advance.
PS: If you have some good advice for changes I should make, I appreciate those too. It's my first time making a user login.

Your query in profile.php is failing because USER and PASSWORD are not defined. When the person logs in, they are defined in login.php. When redirected to profile.php, USER AND PASSWORD do not have values since they are not in config.php.
In profile.php, change
$link = new mysqli(HOST, USER, PASSWORD, DATABASE) or die("Unable to connect to database");
to
$link = new mysqli(HOST, $_SESSION["user"], $_SESSION["password"], DATABASE) or die("Unable to connect to database");

Related

session_start() causing problems

I am having problems with my code. This is a login/register script I've made by following a tutorial.
The problem I have is that I want the script to echo "logged in" ONLY when the user has entered correct login details, and yet it still echoes "logged in" even if I don't enter any login details. I checked it and if I delete the "session_start()" function, it doesn't do the same thing, but it still doesn't give me access to the session when I want to login.
This is the init.php file, used to initiate the connection with the database and define some other functions:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
This is the connect.php file, used to connect to the database :
<?php
$connect_error = 'Sorry, we are experiencing connection issues. This will be solved as soon as possible.';
$con=mysqli_connect("localhost","root","","lr") or die ($connect_error);
mysqli_select_db($con,'lr') or die($connect_error);
mysqli_close($con);
?>
The general.php file is not important for this question.
This is the users.php file, where I keep some other functions.
function user_id_from_username ($username){
$username = sanitise($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
while($row=$result->fetch_row()){
if ($row[1]==$username){ //username == $username
return $row[0];//user_id;
}
}
}
function login ($username, $password){
$user_id= user_id_from_username($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$username = sanitise($username);
$password =md5 ($password);
$query = "SELECT * FROM users";
$result = $mysqli -> query($query);
while ($row =$result -> fetch_row()){
if($row[1]==$username && $row[2]==$password){
return TRUE;
}else {
return FALSE;
}
}
}
This is the file that calls the login function, presented above:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) ===TRUE || empty ($password) === TRUE) {
$errors[]='You need to enter a username and password!';
} else if (user_exists($username) ===FALSE) {
$errors[]="We can't find that username, have you registered?";
} else if (user_active($username)===FALSE){
$errors[]="You have not activated your account!";
} else{
$login = login($username, $password);
session_start();
if ($login ==false) {
$errors[] ='That username/password combination is incorrect!';
}else if ($login==true) {
//set the user session
$_SESSION['username'] = $login;
//redirect user to homepage
header('Location: index.php');
exit();
}
}
if ($errors){
print_r($errors);
}
}
?>
And now the index.php file, in which I have the if statement that echoes 'logged in' even if I am not logged in :
<?php
if (empty($_SESSION['username'])) {
echo 'not logged_in';
}else {
echo 'logged in';
}
?>
Now I think the problem is located somewhere either in the users.php, login.php or in the index.php file. I presented all of the files so you could get an idea of what I am trying to achieve. This code is spread over so many files because I have functions and interfaces that I have included and I want to be able to reuse the code, so I am using includes.
For you to get a better idea, if my files did not help you enough, I will leave the Youtube link of the tutorial I am following :
https://www.youtube.com/watch?v=JUk2e8oqOvI&list=PLE134D877783367C7&index=7#t=6.296979
Thank you,
Waiting for your answer,
Best regards,
If you don't use $_GET requests to include the pages, you need to put session_start() on top of each file where you are using the $_SESSION variable otherwise you can't use the sessions.
<?php
session_start();
// Rest of your script
I hope this will help you.

Login php/sql working but it is depracted... how to change?

I have 3 files to login
Can someone look through my code in checklogin... does it look OK. And hwo do I update it so it's not deprecated. mysql_select_db and sql select etc, how can I change the code to update version...
<?php
$host="localhost";
$username="root";
$password="";
$db_name="members";
$tbl_name="user";
$username=$_POST['username'];
$password=$_POST['password'];
$con= mysql_connect("localhost","root","","members");
if(!$con)
die("failed to connect");
mysql_select_db("members",$con);
$sql= "SELECT * FROM user WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
session_start();
$_SESSION['username']=$username;
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
Try this code and see if it does what you need. Also, when you post your form are you encrypting your password in anyway? You may need to decrypt the users password so that it matches what is in the DB?
<?php
define('DB_HOSTNAME','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_DATABASE','members');
$username = $_POST['username'];
$password = $_POST['password'];
//CONNECT TO DATABASE
$db = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$userExists = $db->query("SELECT * FROM user WHERE username='{$username}' and password='{$password}'");
$count = count($userExists);
$db->close();
if($count == 1){
session_start();
$_SESSION['username'] = $username;
header("location:login_success.php");
}else{
echo "Wrong Username or Password";
}
?>
You need to use PHP PDO.
PHP's mysql_* functions are deprecated and should not be used anymore!
All you need is to update your code to get rid of using deprecated functions.
What the posters failed to inform you of is that the functions for 'mysql..()' are deprecated by PHP. Meaning they will be taken out soon or will no longer be updated in the newer versions of PHP. Better description here Deprecated meaning?.
'mysqli' is the new standard for connecting with mysql through PHP. There are several ways you can connect to mysql through PHP as well. 'new mysqli', 'mysqli_connect', and even going the PDO route. http://php.net/manual/en/mysqli.quickstart.connections.php
php.net has a great set of documentation that will give you better insite into all of these methods.
Hope this helps you be not confused any longer.

unable to connect to mysql through php on new page

Super confused here. I've build a website that allows me to connect to mysql using php. I require common.php as you can see below, and have no issues connection, executing, etc.. to the database. What does not work is when I use this exact same code on a new page that I'm developing. I can login with a test user to the site, but the page will not run any SQL queries to pull information from my database. The error I get is:
"Access Denied for user 'ec2-user#localhost' (using password: NO)"
I do not understand why its trying to connect as ec2-user when thats obviously isn't what I'm asking the code to connect as.
Any help would be appreciated. I've been attempting to resolve this issue for a few days now and even with searching Father Google, I can't find a suitable answer.
Thanks!
Common.php Code
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
Code for common.php is below
<?php
// These variables define the connection information for your MySQL database
$username = "username";
$password = "password";
$host = "myhostnotyours";
$dbname = "thedatabase";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
Probably the bit "(using password: NO)" is the bit you should be looking into. Do the password thing!
Then again why not narrow down the problem a bit - instead of posting 100+ lines of code
set your password variable into null.
$password = '';

PHP : Must login twice until session variables are set

SOLUTION: after many hours of searching, it seems this problem was occurring when I access my website without adding the "www." before the domain. so what actually was happening is, I was logging in with example.com/login.php sets session somewhere, that my member control doesn't recognize, so it redirects me back to www.example.com/login.php, that when I login everything works Ok.
when I login from www.example.com/login.php (with the www.) it logs in correctly from first attemp.
So I added a code to make sure I always have the www in the URL:
if ($_SERVER['HTTP_HOST'] == "example.com")
{
$url = "http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
and everything works well now. Hope it helps someone.
So, I have built over 3 websites, and all have same problem, I don't know why, I have to login twice till I'm rly logged in.. (till the session variables are set). Help is really appreciated, been trying to fix this and looking for solution since a long time...
session_start();
if ((isset($_SESSION['UserName']))&&(isset($_SESSION['LastActivity'])))
{
header ('Location: http://www.example.com/Account.php');
}
if (isset($_POST['username']))
{
mysql_connect("localhost","DBuser","pass") or
die ("could not connect to mysql");
mysql_select_db("DBNAME") or die ("no database");
$inputUserName = $_POST['username'];
$inputPass = $_POST['password'];
$datausername = mysql_real_escape_string($inputUserName);
$password=md5($inputPass);
$sqlCommand = "SELECT * FROM Members
WHERE UserName='$datausername' AND
Password='$password'";
$result = mysql_query($sqlCommand);
if (mysql_num_rows($result) > 0)
{
$_SESSION['UserName'] = $datausername;
$_SESSION['LastActivity']= time();
sleep(2);
$LoginDate = date('Y-m-d H:i:s');
mysql_connect("localhost","DBUPDATEusername","DBuserPass") or
die ("could not connect to mysql");
mysql_select_db("databaseName") or die ("no database");
mysql_query("Update Members SET LastLogin='$LoginDate' WHERE
UserName='$datausername'");
mysql_close();
echo '<meta http-equiv="Refresh" content="0;url=http://www.example.com/Account.php?p=Login_Success"/>';
}
else {
mysql_close();
echo '<div id="error_msg">Error: Information entered are not correct. Please check and try again.</div>';}
}
}
?>
<form...
login form (with action=""), and method post).
Note: I use the html refresh tag, because I can't use the header redirect.. (I get error that header is already sent).
and in the example.com/Account.php I do this check at the top of the code:
session_start();
if ((!isset($_SESSION['UserName']))||(!isset($_SESSION['LastActivity'])))
{
header('Location: http://www.example.com/?p=Must_Login');
}
And and it seems that first time I login and am redirected to account.php panel.. the session values are not set, and redirects me back to Must_Login page. I login again (same login page I use at first time. But the second time when I login, it does set the session values, and everything is OK.
Thank you very much for your help in advance!
SOLUTION: after many hours of searching, it seems this problem was occurring when I access my website without adding the "www." before the domain. so what actually was happening is, I was logging in with mydomain.com/login.php sets session somewhere, that my member control doesn't recognize, so it redirects me back to www.mydomain.com/login.php, that when I login everything works Ok.
when I login from www.mydomain.com/login.php (with the www.) it logs in correctly from first attemp.
So I added a code to make sure I always have the www in the URL:
if ($_SERVER['HTTP_HOST'] == "mydomain.com")
{
$url = "http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
and everything works well now. Hope it helps someone.
Connect to database before your Members select.
Start session if it has not been started yet.
Connect to the server and select the database before querying.
if (!isset($_SESSION)) {
session_start();
}
mysql_connect("localhost","DBusername","DBuserPass") or
die ("could not connect to mysql");
mysql_select_db("databaseName") or
die ("no database");
if ((isset($_SESSION['UserName']))&&(isset($_SESSION['LastActivity'])))
header ('Location: http://www.mysite.com/Account.php');
if (isset($_POST['username']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sqlCommand = sprintf( "SELECT * FROM Members
WHERE UserName = %s AND Password = %s", mysql_real_escape_string( $_POST['username'] ), md5( $_POST['password'] ) );
$result = mysql_query( $sqlCommand );
$rowsnr = mysql_num_rows( $result );
if (mysql_num_rows( $result ) > 0)
{
$_SESSION['UserName'] = mysql_real_escape_string( $_POST['username'] );
$_SESSION['LastActivity']= time();
sleep(2);
mysql_query(sprintf("UPDATE Members SET LastLogin = NOW() WHERE
UserName = %s", mysql_real_escape_string( $_POST['username'] )));
mysql_close();
echo '<meta http-equiv="Refresh" content="0;url=http://www.mysite.com/Account.php?p=Login_Success"/>';
}
else
{
mysql_close();
echo '<div id="error_msg">Error: Information entered are not correct. Please check and try again.</div>';
}
}
?>
Try putting following code AFTER you check for the login?
session_start();
if ((!isset($_SESSION['UserName']))||(!isset($_SESSION['LastActivity'])))
{
header('Location: http://www.mysite.com/?p=Must_Login');
}
PHP sessions are written to the session handler after the script which started the session finishes execution. In your case the first script started the session and updated session variables 'username' and 'lastactivity' then redirected to another page. But still the session values are in memory - not registered to be used in the second script.
One way to fix the problem is to call
session_write_close();
before (or after) sleep(2);
for more information see here
try session_set_cookie_params(0, '/', '.domain.com') before your session_start();
I had the exact same problem, in my case I was redirecting to the website address after login:
header('Location: http://mywebsite.com');
die();
Even manually closing the session before the redirect didn't help.
I fixed it by instead redirecting to a specific page:
header('Location: index.php');
die();

Password protect a page?(with db access)

Couple questions here: My end goal is to password protect the file logged_in.php.
Note: I'm only a beginner/intermediate programmer so i would like clear explanations, please.
First off, i have set a username and password within a database table.
I have two pages: login.php and logged_in.php(names are just for example purposes). How do i "require" a user to first go through login.php(the log in process) in order to gain access to logged_in.php(if the entered username/password are correct)?
Is this the best way to password protect a page?
What i've tried:
Login.php:
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
header("location:logged_in.php");
}
else
header("location:bad_login.html");
}
?>
The problem with my code at the moment is that, someone can directly type in the URL of logged_in.php and access the page without being "required" to go through login.php first(i'm sure this is obvious to everyone..).
I put require(login.php); at the top of logged_in.php; however, that didn't work out.
I've checked google for some good tutorials on this topic, unfortunately i couldn't find any that had clear explanations.
I also saw a few other questions regarding this topic on stackoverflow, but they didn't really help me out.
I'm also interested in being able to pass-protect my page using the method phpMyAdmin uses(when you type in the URL and press enter it drops down a menu from the top of the browser asking for a username/password). I don't know how that works. If someone can tell me how that works i'm willing to completely disregard the method i'm attempting to use at the moment(if the phpMyAdmin method is secure enough and is fairly easy to implement).
Thanks in advance!
Use $_SESSION variable:
<?php
session_start();
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $user;
header("location:logged_in.php");
exit();
}
else
header("location:bad_login.html");
exit();
}
?>
logged_in.php:
<?php
session_start();
// check if $_SESSION was setting before
if (!isset($_SESSION['username']))
{
header("Location: login.php?e=access_denied");
exit();
}
?>
The phpMyAdmin login is different because use the MySQL username and password to login, so phpMyAdmin does not need to create a database and table to login like your code
Also you need the logout:
logout.php
<?php
session_start(); // <-- Oops!!
// unset all $_SESSION variables
session_unset();
session_destroy();
header("Location: logged_in.php?m=logout_success");
exit;
?>

Categories