Jump to content

can NOT get query to pull data based on WHERE clause


simcoweb

Recommended Posts

Ok, summary... I have login form asking for 'username' and 'password'...validates the fields... checks the db for existence..then forwards them onto the 'members.php' page where it SHOULD display their profile information based upon this query:

[code]$sql = "SELECT * FROM plateau_pros WHERE username='$username'";
$result = mysql_query($sql, $conn) or die(mysql_error());[/code]

with this variable set:

[code]$username = $_POST['username'];[/code]

The login takes me to the 'members.php' page but nothing is displayed. Now, if I replace the $username in the WHERE clause with an actual registered username it pulls up fine.

I've been scratching my head alot on this one. Anyone?

Link to comment
Share on other sites

Try echo'ing $sql and see what you get, also, are you sure that your form name is "username"? Lastly, are you setting a SESSION variable to username also? In some version of php a session variable can be used as a regular variable, so if $_SESSION["username"] isnt set, then $username would be set to nothing.
Link to comment
Share on other sites

Thanks for the response. I've got this session info at the top of my script:

[code]session_start();
$_SESSION['loggedin'] = $_POST['username'];
$username = $_POST['username'];[/code]

I've been experimenting with several variations of this including just the first two lines as well as just $_SESSION['username'];

Still nothing. Also, I just tried your suggestion and echoed the $result = mysql_query($sql); statement and get this:

[quote]Resource id #45[/quote]

When I echo the $sql directly I get this:

[quote]SELECT * FROM plateau_pros WHERE username=''[/quote]

Not sure what to make of it.

Link to comment
Share on other sites

Here's the form tag:

[code]<form action"<? print $PHP_SELF ?>" id="Form1" style="WIDTH: 100%" name="Form1" method="post" >[/code]

and here's the field tags:

[code]<input id="Password1" style="WIDTH: 155px; HEIGHT: 22px" type="password" size="21" name="password"value="<?= @$_POST['password'] ?>">[/code]

[code]<input id="Text1" name="username" value="<?= @$_POST['username'] ?>">[/code]
Link to comment
Share on other sites

Ok, changed to this:

[code]<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="Form1" style="WIDTH: 100%" name="Form1" method="post" >[/code]

But still get this:

[quote]query = SELECT * FROM plateau_pros WHERE username=''
Heres your problem
[/quote]

I'd love to say the missing = sign fixed it...but. Still same problem. No username being passed.  :P
Link to comment
Share on other sites

your form tags should be like so
[code]<form action"<? print $PHP_SELF ?>" id="Form1" style="WIDTH: 100%" name="Form1" method="post" >
<input id="Password1" style="WIDTH: 155px; HEIGHT: 22px" type="password" size="21" name="password">
<input id="Text1" type=text name="username">
<input type=submit value=submit>
</form>[/code]

No need to put values in the form fields, since you are trying to get those in the first place. They are going to be blank anyway.

your page that checks the login should start with the session. After you query the database to check the credentials, then you should set your session values then.

Ray

Link to comment
Share on other sites

Ok, that's the way the form fields were previously. I will switch them back in the name of progress.

Also, not quite clear on the second part of your post. The page that 'checks' the login... the login is validated with some code in the login.php page as such:

[code]// Validate users input
if(!empty($_POST))
{
// Check username has a value
if(empty($_POST['username'])) $eg_error['username'] = "Please enter a user name!";
// Check password has a value
if(empty($_POST['password'])) $eg_error['password'] = "Please enter a password!";
// Check if any errors were returned and run relevant code
if(empty($eg_error))
{

// Get Record Set
$sql = ("SELECT * FROM plateau_pros  WHERE username = '$username' AND password = '$password'");
mysql_query($sql) or die(mysql_error());
$results = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($results) or die(mysql_error());

if ($num_rows == 1) {[/code]

There's no validation on the 'members.php' page at this time. Which after the 'if' statement it sets the session variables as so:

[code]session_start();
  session_register('memberid');
  $memberid = ($results['memberid']);
  header("Location: members.php");
  exit;
} else {
 
$loginError = "Your user name and password do not match any in our database! Please try again.";
}
}
}[/code]

Which [i]should[/i] pass this on to the 'members.php' page.... which opens with:

[code]session_start();[/code]

then runs the query for pulling the data based on the WHERE username='$username'

Am I missing a step or have a step out of order?
Link to comment
Share on other sites

Certainly:

[code]<?php
session_start();
include 'dbconfig.php';

$loginError = ""; // declare this so it is always available

// Turn on magic quotes to prevent SQL injection attacks
if(!get_magic_quotes_gpc())
set_magic_quotes_runtime(1);

// Connect to database
$eg_objConn1 = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname, $eg_objConn1) or die(mysql_error());

// Validate users input
if(!empty($_POST))
{
// Check username has a value
if(empty($_POST['username'])) $eg_error['username'] = "Please enter a user name!";
// Check password has a value
if(empty($_POST['password'])) $eg_error['password'] = "Please enter a password!";
// Check if any errors were returned and run relevant code
if(empty($eg_error))
{

// Get Record Set
$sql = ("SELECT * FROM plateau_pros  WHERE username = '$username' AND password = '$password'");
mysql_query($sql) or die(mysql_error());
$results = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($results) or die(mysql_error());

if ($num_rows == 1) {
      // Enable sessions
//if (isset($_SESSION['loggedin']))
//{
  session_start();
  session_register('memberid');
  $memberid = ($results['memberid']);
  header("Location: members.php");
  exit;
} else {
 
$loginError = "Your user name and password do not match any in our database! Please try again.";
}
}
}
include 'header.php';
?>
<div align="center">
<table id="table13" style="BORDER-COLLAPSE: collapse" bordercolor="#666666" cellpadding="4" width="530" border="0">
<tbody>
<tr>
<td>
&nbsp;
<h2 align="center">Login page
</h2>
<font color="red">
<div align="center">
<?
// Loop through all errors
if(!empty($eg_error))
{
?>
<ul>
<?
foreach($eg_error as $eg_message)
{
?>
<li id="validationError"><?= @$eg_message ?></li>
<?
}
?>
</ul>
<?
}
?>
</div>
</font>
<form action="<?php print PHP_SELF ?>" id="Form1" style="WIDTH: 100%" name="Form1" method="post" >
<table id="Table1" cellspacing="0" cols="2" cellpadding="0" align="center" border="0">
<tbody>
<tr>
<td>
User name:&nbsp;&nbsp;</td>
<td>
<input id="Text1" name="username" ></td>
</tr>
<tr>
<td>
Password:</td>
<td>
<input id="Password1"  type="password" size="21" name="password"></td>
</tr>
<tr>
<td>
</td>
<td align="right">
<br>
<input id="Submit1" type="submit" value="Login"></td>
</tr>
</tbody>
</table>
</form>
<strong><font color="red">
<p id="loginError" align="center"><?= $loginError ?></p>
</font></strong></td>
</tr>
</tbody>
</table>
</div>
<p>
<hr width="80%" height="1">
<form action="forgot.php" method="POST" name="forgot">
<table width="450" border="0" align="center">
<tr><td><h2>Forgot Your Password?</h2><br>
<font class='bodytext'>If you have forgotten your password complete the form below to have your information sent to you.</font><p>
<tr><td><font class="bodytext">Enter your username: <br><input type="text" size="20" name="username" id="username"></td></tr>
<tr><td><input type="submit" name="submit" value="Submit"></td></tr>
</table>
</form>
<?
include 'footer.php';
?>[/code]
Link to comment
Share on other sites

okay in your OP you said you had this:

$username = $_POST['username'];

but i do not see that in your code.

[code]
if(empty($eg_error))
{
$username = $_POST['username']; // need to add this
$password = $_POST['password']; // and this

// Get Record Set
$sql = ("SELECT * FROM plateau_pros  WHERE username = '$username' AND password = '$password'");
[/code]
Link to comment
Share on other sites

Perhaps i'm confused as usual. I have those variables being set on the members.php page... the landing page after they log in. Hmmm...now that I think about it...those variables would need to be on the page that parses the form..and not on the page that they are redirected to. Am I on track with that?

Also, this chunk of code... is this proper syntax?

[code]if ($num_rows == 1) {
      // Enable sessions
//if (isset($_SESSION['loggedin']))
//{
  session_start();
  session_register('memberid');
  $memberid = ($results['memberid']);
  header("Location: members.php");
  exit;[/code]

I was trying to set a session variable for 'memberid' so I can pass that onto the next page(s) and use it in some URL's pertaining to that particular member's profile.
Link to comment
Share on other sites

yes.  your posted variables go to the targeted script in your form action.  That's the only place they go to.  therefore, your targeted script already checks to see if they are there, etc.. just add those 2 lines of code afterwards, just like i showed you.

as far as your proper syntax thing... session_start() should only be used once, at the beginning of your script.  If you are already checking for $_SESSION['loggedin'], then you presumably should aready have session_start() some place near the top already. 

also, using session_register is a deprecated way of doing sessions.  instead, use

$_SESSION['memberid'] = $results['memberid'];

and then when your header redirects to members.php, you can do this:

[code]
<?php
  session_start();
  $memberid = (isset($_SESSION['memberid'])) ? $_SESSION['memberid'] : NULL;
?>
[/code]

that way you will have your $memberid variable as an easier variable to play with.  Just remember though, if you wanna do it that way, before you go to some other page, always go back and assign whatever you have in $memberid back to the session variable like so:

$_SESSION['memberid'] = $memberid;

presumably your memberid won't be changing, so this probably won't be necessary, but keep that in mind if you are going to have other session variables that will be changing.
Link to comment
Share on other sites

ARRRRGHH! Still not pulling the data based on the username. Here's the first chunk of code in the 'members.php' page that should be pulling the data and displaying it based upon the username:

[code]<?php
// Enable sessions
session_start();
$memberid = (isset($_SESSION['memberid'])) ? $_SESSION['memberid'] : NULL;
$username = $_POST['username'];
// Turn on magic quotes to prevent SQL injection attacks
if(!get_magic_quotes_gpc())
set_magic_quotes_runtime(1);
include 'header.php';
include 'dbconfig.php';
// Connect to database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());

//new sql query
$sql = "SELECT * FROM plateau_pros WHERE username='" . $username . "'";
$result = mysql_query($sql, $conn) or die(mysql_error());
?>[/code]

I inserted the variables as you specified as so:

[code]// Validate users input
if(!empty($_POST))
{
// Check username has a value
if(empty($_POST['username'])) $eg_error['username'] = "Please enter a user name!";
// Check password has a value
if(empty($_POST['password'])) $eg_error['password'] = "Please enter a password!";
// Check if any errors were returned and run relevant code
if(empty($eg_error))
{
$username = $_POST['username'];
$password = $_POST['password'];
// Get Record Set
$sql = ("SELECT * FROM plateau_pros  WHERE username = '$username' AND password = '$password'");[/code]

This is driving me whacky.
Link to comment
Share on other sites

This might help a bit, its as simple a way as i can think of.

//form
<form action="login.php" method="post">
<input type="text" name="username">
<input type="password" pass="password">
<input type="submit" value="Log In">
</form>

//log in
$sql = @mysql_query("SELECT * FROM plateau_pros WHERE username='$username'");

I promise that works, $username will be set properly and the query will work.  Of course there no form validation or anything else in there, but try to just build off of it.
Link to comment
Share on other sites

okay you seem to have 3 different scripts going here: your form, your target, and some other script called members.  And it seems that your form script's action targets your target script, but you are trying to access your form's posted variables in some other script called members.php .  My best guess is that you have a login form that asks for the username/password, and then a script to authenticate it, and then upon authentication, you get whisked away to another script called members.php and you are wanting to do another query based on the same information.  Is that even remotely right?

Okay to access the info from form.php in your target.php, you use the $_POST array.  To access info from target.php in your members.php you need to create a session variable.

Let's simplify this a bit, kinda start over. This is the basic principle of passing a variable from a  form to its target action script:

form.php
[code]
<form action='target.php' method = 'post'>
  <input type='text' name='username'>
  <input type='submit' value='submit'>
</form>
[/code]

target.php
[code]
<?php
  session_start();

  $username = $_POST['username'];
  $sql = "select * from blah where username = '$username'";
 
  $_SESSION['username'] = $username;
  header('location: members.php');
  exit();
?>
[/code]

members.php
[code]
<?php
  session_start();
  $username = (isset($_SESSION['username'])) ? $_SESSION['username'] : NULL;
?>
[/code]
Link to comment
Share on other sites

Ok, it's good to stop and clarify. You're pretty much on track with your assessment of what i've got working so far:

[quote]okay you seem to have 3 different scripts going here: your form, your target, and some other script called members.  And it seems that your form script's action targets your target script, but you are trying to access your form's posted variables in some other script called members.php .  My best guess is that you have a login form that asks for the username/password, and then a script to authenticate it, and then upon authentication, you get whisked away to another script called members.php and you are wanting to do another query based on the same information.  Is that even remotely right?[/quote]

[b]login.php:[/b]
Basic login form
Contains the session_start();
Form action = $PHP_SELF so it parses to itself instead of external script
Checks username/password against the database to validate existence
Forwards the person onto 'members.php' page via header() statement in IF no errors occur
[color=red]Passes the username variable 'username' via session[/color] or, at least I think it does

[b]members.php:[/b]
- continues session/validates existence of session
- posts $username variable as $username='$_POST['username'] which, now I understand, will not post to this page since it's not the page parsing the data
- runs mysql query to pull the data regarding that member with WHERE clause being $username
- Displays various data from the database throughout the page

So, basically it's two pages/scripts. The login.php contains the parsing script. The members.php page (the 'target page' after login) contains code for extracting the data to display.

The breakdown appears to be in passing the form value(s) 'username' to the members.php page so the query:

[code]$sql = "SELECT * FROM plateau_pros WHERE username='$username'";
$result = mysql_query($sql, $conn) or die(mysql_error());[/code]

can pull the required data. Right now after logging in the 'members.php' page is completely blank which means it's not passing that variable.

Now, not to confuse anything at this point, but i'd love to use the 'memberid' as the primary variable passed in order to utilize that in a variety of ways since it's always a unique number. So, passing that would be preferred. I was using 'username' since it was a form field that I felt would be passed in the $_POST method. By using the memberid field instead I can create url's pointing like:

[quote]referrals.php?memberid=$memberid[/quote]

Make sense?

Also, did I say THANKS FOR THE HELP? :)
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.