Cant retrieve data from an SQL database using PHP and session variables - php

I have a website with the following code in the header - but the PHP echos in the body are returning anything:
<?php
session_start();
print_r($_SESSION);
$user = $_SESSION['email'];
$query = "SELECT * FROM first_page_data WHERE email_address= '$user' ";
$result = mysql_query($query);
$row_buyerdetails = mysql_fetch_assoc($result);
?>
The following returns nothing:
<?php echo $row_buyerdetails['phone_number'] ?>
I know the session variable named 'email' is receiving a value from the previous page from the print_r function on line 3. Variable $user is also getting the correct email address.
The database is set up correctly (ive been able to access successfully in other ways, but im trying to modify it to access the data related to a particular email address as shown).
If somebody could point me in the right direction id apprectiate it! Also as a side, how would people suggest debugging PHP other than littering the code with echos and print_r functions? Is there even a way to put breakpoints in for example?
EDITED FOR HELP IN THE ANSWER BELOW
As requested, this is the code with the alterations requested:
<?php
$hostname_first_data = "*****";
$database_first_data = "*****";
$username_first_data = "*****";
$password_first_data = "*****";
$first_data = mysql_pconnect($hostname_first_data, $username_first_data, $password_first_data) or trigger_error(mysql_error(),E_USER_ERROR);
echo mysql_errno($first_data) . ": " . mysql_error($first_data). "\n";
session_start();
print_r($_SESSION);
$user = $_SESSION['email'];
echo $user;
$query = "SELECT * FROM first_page_data WHERE email_address= '$user' ";
$result = mysql_query($query, $first_data);
$row_buyerdetails = mysql_fetch_assoc($result);
print_r($row_buyerdetails);
?>

Aren't you missing a mysql_connect call in your header or includes?
Try adding:
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
$link being the resource you get from mysql_connect.
To debug PHP you have to install or activate an extension that is called Xdebug and use a nice IDE like PHPStorm, then Bob's your uncle :)
You can also use the Zend Debugger but I have limited experience with it.
You can (and should) also have full error reporting on when you are developing. It would tell you for example that the mysql_* functions are deprecated.
If you do not want the errors to appear on your page, you can choose to write to a log file and keep a tail open on that file.
Update for code:
<?php
$hostname_first_data = "*****";
$database_first_data = "*****";
$username_first_data = "*****";
$password_first_data = "*****";
$first_data = mysql_pconnect($hostname_first_data, $username_first_data, $password_first_data) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_first_data, $first_data);
session_start();
print_r($_SESSION);
$user = $_SESSION['email'];
echo $user;
$query = "SELECT * FROM first_page_data WHERE email_address= '$user' ";
$result = mysql_query($query, $first_data);
echo mysql_errno($first_data) . ": " . mysql_error($first_data). "\n";
$row_buyerdetails = mysql_fetch_assoc($result);
print_r($row_buyerdetails);
?>
Tell me what that version outputs...

Related

How to retrieve information from a record in a database in PHP 5.5?

I am mostly confused about the new php 5.5, I apologize for any inconvenience.
I am trying to get information from whomever logs in, so for example if I log in with an email, I'd like the website to get my first name and do a "Welcome, Shinji!".
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn , 'session_start');
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysqli_query($conn , "SELECT * FROM `info_table` WHERE '$user' = `user` AND '$pass'=`password`") or die(mysqli_error($conn));
$rows = mysqli_num_rows($query);
if($rows == 1){
#$query2 = mysqli_query($conn , "INSERT INTO `who_logged` (`name`) VALUES ('$user')") or die(mysqli_error($conn));
#$rows = mysqli_num_rows($query);
session_start();
$_SESSION['username'] = $_POST['user']; // store username
$_SESSION['password'] = $_POST['pass']; // store password
$query2 = mysqli_query($conn ,"SELECT `name` FROM `info_table` WHERE '$user' = `user`") or die(mysqli_error($conn));
$result = mysqli_num_rows($query2);
while ($row = mysql_fetch_assoc($result)) {
$_SESSION['name'] = $row['name'];//I thought to try setting the name to the Session variable, but does not work
}
header('Location: next_page.php');
exit();
}else{
echo "Wrong username or password.";
}
I tried to set the name to a session variable, but if there is a more efficient way please say so! (This current code works, except the name setting to session.
You have your column(s) and values mixed up in order.
It's column first, then the value and not the other way around.
Change both:
WHERE '$user' = `user` AND '$pass'=`password`
to:
WHERE `user` = '$user' AND `password`='$pass'
Plus, you're mixing MySQL APIs. Those different APIs do not intermix with each other.
Change mysql_fetch_assoc to mysqli_fetch_assoc
I noticed you are using sessions; make sure session_start(); is indeed loaded.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Also, add or die(mysqli_error($conn)) to mysqli_query()
Your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.
EDIT:
Try the following instead and it will get you started. Please read my footnotes concerning the use/storage of plain text passwords.
Sidenote: I removed $_SESSION['password'] = $pass; // store password
do not do this, it's insecure.
Plus, do not put anything "above" the PHP below, such as HTML etc., otherwise, you will receive a warning about headers already sent.
<?php
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'session_start');
$user = stripslashes($_POST['user']);
$user = mysqli_real_escape_string($conn,$_POST['user']);
$pass = stripslashes($_POST['pass']);
$pass = mysqli_real_escape_string($conn,$_POST['pass']);
$query = mysqli_query($conn , "SELECT * FROM `info_table`
WHERE `user` = '$user' AND `password`='$pass'")
or die(mysqli_error($conn));
$num_rows = mysqli_num_rows($query);
if($num_rows > 0){
session_start();
// it's not really needed
// we are pulling it from $row['user'] in the while loop
// and setting it to $_SESSION['username']
// $_SESSION['username'] = $user; // store username
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['username'] = $row['user'];
}
// for testing only. Do not use with header
// echo $_SESSION['username'];
header('Location: next_page.php');
exit();
}
// do not place any echos here, only the else statement
else{
echo "Wrong username or password.";
}
next_page.php
<?php
session_start();
if(isset($_SESSION['username'])){
echo $_SESSION['username'];
}
else{
echo "Not logged in.";
}
Footnotes
It is highly recommended that you do not store passwords in plain text.
Visit the following Website:
http://daveismyname.com/login-and-registration-system-with-php-bp
It contains a full registration/login/verification system as well as using PDO with prepared statements and PHP's password_hash() function, which is highly recommended.
Since you are using PHP 5.5, then you will benefit from these features.

PHP mysql no error but keeps failing

I have no idea what's going on. I usually have simple sign in pages like this done very quickly but this one isn't working and I cannot spot the error.
<?php
$con=mysql_connect("db_server","db_user","db_pass","db");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$query="SELECT username FROM users ";
//$query.="WHERE `username`=".$username;
//$query.=" AND `password`=".$password;
echo "query=".$query."<br/>";
$result = mysql_query($query, $con);
echo "result=".$result."<br/>";
if($result){
$row = mysql_fetch_assoc($result);
$data = $row['username'];
echo "data=".$data;
}else{
echo "something went wrong:".mysql_error();
}
mysql_close($con);
?>
im using mysql_* instead of mysqli_* as the server im running it on is 5.2; not sure if that is relevant but I was getting an unrecognized function error originally.
There is only one entry in the database. As I said, I use the regular SQL code through phpmyadmin and i get the results i need.
Also not sure if relevant. I'm echoing $result and nothing comes out. Isnt it supposed to echo "false"?
You have a major error in your logic, for one. If there is an error connecting to MySQL, you print the error, but yet proceed to query the broken connection - you are also not selecting a database.
Also, this approach is for PHP4. Unless you are stuck in PHP4 on this project, moving into the PHP5 world would be a good idea.
I recommend looking into PDO:
http://www.php.net/manual/en/book.pdo.php
As for not getting errors, check your error_reporting and display_errors settings in your .ini
Try this one.
<?php
$con=mysql_connect("db_server","db_user","db_pass");
mysql_select_db("db");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$query=mysql_query("SELECT username FROM users");
if($query){
$row = mysql_fetch_assoc($query);
$data = $row['username'];
echo $data;
}else{
echo "something went wrong:".mysql_error();
}
mysql_close($con);
?>

Session Variables not Persisting

I have a few session variables that I am trying to use in my application, however, I am unable to get them to show up on the pages I need them to.
This is the code that sets them (I have manually assigned them values as well, so it isn't the database pull that is the problem):
if ($name != ""){
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;
}
I start that page with a session_start();, as I do on all the pages that will be using the session variables.
When I try to call the session variables on another page, they no longer exist, even if that is the page the one that assigns the values redirects to.
This is how I am trying to call the session variables:
$name = $_SESSION['name'];
$user_id = $_SESSION['id'];
why would it be doing this?
EDIT: To help I'm including the rest of my code for that page. The database connection portions work fine, they are identical to what I use eveyrwhere else.
<?php
session_start();
define('DB_SERVER', '<server>');
define('DB_USER','<db>');
define('DB_PASSWORD' , '<password>');
define('DB_NAME' , '<db-name>');
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database');
$stmt = "Select User.user_id, User.name from User where User.username = '" .
$_POST["username"] . "' AND User.password = '" . $_POST["pwd"] . "';";
if(!$result = $conn->query($stmt)){
die('there was an error retrieving the information');
}
$row = $result->fetch_assoc();
$name = $row['name'];
$user_id = $row['user_id'];
$_SESSION["name"] = $name;
$_SESSION["id"] = $user_id;
if ($name != ""){
$conn->close();
?>
<script type="text/javascript">
<!--
window.location = "store.php"
//-->
</script>
<?php
}
else{
?>
<script type="text/javascript">
<!--
window.location = "register.php"
//-->
</script>
<?php
}
?>
There is only two probabilities:
You did not started session before any output.
The $name is already empty or null.
You have to do the following to debug:
echo $name before the if conditional.
error_reporting(E_ALL); or checkout this question: How to get useful error messages in PHP?
As a debugging technique, try setting the session values ON the page that you're trying to call them. For example, set them on the top of the page and then try outputting them somewhere else below on the page and see if that works. If it does, then it's obvious that the variables aren't being set on the previous page(s).
In PHP you must need to start session using session_start() then only you can user session variables.
And also try to debug, Does your if condition satisfied or not. In your case if your if condition does not satisfied then it is not possible your below code will execute.
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;

How can I access a session variable set on page from a different page

I've tried looking for information on what I'm trying to do, but the results are not what I'm need to get done. I'm pretty sure there's an answer out there to my issue, but I have no idea how search for it with the correct wording. Anyways what I'm trying to do is: Here I have created a session variable
<?php
// Session started
session_start();
// Connecting to the database
$host = "localhost";
$username = "username";
$password = "password";
$db_name = "potholio";
$tbl_name = "userTbl";
$conn = mysql_connect( $host, $username, $password );
if (! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db( $db_name );
// Submitting query and retrieving result)
$myusername = $_GET['myusername'];
$mypassword = $_GET['mypassword'];
$sql = "SELECT * FROM $tbl_name WHERE usrName='". $myusername ."' and pwd='". $mypassword ."'";
$result = mysql_query( $sql );
// Checking results
$count = mysql_num_rows( $result );
// Directing user based on result
if ( $count == 1 )
{
Now down below is where I have actually set the session variable that I want to access later on.
$userID = mysql_fetch_assoc( $result );
$_SESSION['user'] = $userID['msgID'];
header('Location: http://potholio.csproject.org/map.html');
}
else
{
echo "<script>alert('Incorrect username or password');</script>";
header('Location: http://potholio.csproject.org/');
}
// Close Database Connection
mysql_close();
?>
Now what I'm trying to access that session variable that I have set in a different file called map.html using the following code:
<?php
// Initiate session
session_start();
// Store session data
echo $_SESSION['user'];
?>
The issue is that when I echo to see whether it was being set, the echo actually doesn't return anything, so I'm not sure what's going one since I know the variable is getting set in the other file, which is login.php. Any help with this probably would be great. I'm a complete beginner with Sessions and Session variables.
You are connecting in localhost , but your header redirect is header('Location: http://potholio.csproject.org/map.html');
It seems you are redirect to map.html from a different remote host, so how do you expect it keeps your localhost session?
Okay so I just figured out what my issue was. I found out that all the code I had was indeed correct and there was not any issues with what I had, except for how I was redirecting pages.
Thanks #Robert Rozas.
My problem was actually a really dumb and easy fix that I over looked. The PHP script on my map.html file was never being executed, because it was an HTML file and not a PHP file. Once I realized that and renamed the file so it had a .php file extension everything ran correctly. Sorry for the trouble guys, I should have seen that.
use var_dump($_SESSION['user']) instead of echo $_SESSION['user'] for better detailed output.

PHP seems to be refusing to connect to MySQL

<?php
function redirect_to_index_with_error(){
echo '<meta http-equiv="refresh" content="0;url=index.php">';
}
function go_to_home(){
echo '<meta http-equiv="refresh" content="0;url=home.php">';
}
$email = mysql_real_escape_string($_POST['username']); echo $email;
$pwd = mysql_real_escape_string($_POST['password']);
echo $pwd;
$query = "SELECT * FROM users WHERE email='$email' AND password=MD5('$pwd')";
echo "query variable created.";
mysql_connect("localhost","root","") or die(mysql_error());
echo "connected."; //nothing
mysql_select_db("mcp") or die(mysql_error());
$results = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($results) == 0){
redirect_to_index_with_error();
exit();
}
$userID = null;
$name = null;
$school = null;
$mod = null;
while($user = mysql_fetch_array($results)){
$userID = $user['ID'];
$name = $user['Name'];
$school = $user['School'];
if($user['Mod'] == '1')
$mod = true;
else
$mod = false;
}
if(!isset($_SESSION))
session_start();
//set session variables
$_SESSION["userID"] = $userID;
$_SESSION["name"] = $name;
$_SESSION["school"] = $school;
$_SESSION["mod?"] = $mod;
go_to_home();
exit();
?>
PHP echos everything up until "connected". It's not even showing a mysql error. I've had this code work flawlessly on Windows with WAMP, but not on Mac with MAMP. I've verified that the servers are running, so I can't tell what the problem is. I'm using PHP 5.3.6.
Your connection needs to be established before you call mysql_real_escape_string()
So move mysql_connect("localhost","root","") or die(mysql_error()); to the top.
Move the mysql_connect() statement above everything else.
// put this at the TOP
mysql_connect("localhost:3306","root","") or die(mysql_error());
Just as everyone else mentioned, see this note:
http://php.net/mysql_real_escape_string#refsect1-function.mysql-real-escape-string-notes
Also, you should see errors, in development, at least.
See: error_reporting()
you have to call mysql_real_escape_string() after connect.
otherwise this function returns an empty string and your query fails.
though it raises an error but it seems you haven't seen that.
So, you ought to either turn displaying errors on or peek error logs - it's impossible to program without ability to see error messages
Also, you have to improve your formal logic.
To make a statement like "PHP seems to be refusing to connect to MySQL" youi have to verify it first. Connect is just a single line and returns a value.
You can verify this value and make a certain conclusion.
But running whole code of several dozens of lines and making statements about just one makes no sense.

Categories