Jump to content

Recommended Posts

I need to retrieve the variable "real_name" from my database to print it out and say

"Welcome real_name, please upload your file."

The username and password work fine, but I can't seem to figure out how to draw the associated real_name value from the database and print it out. Any help is muchly appreciated.
Link to comment
https://forums.phpfreaks.com/topic/3931-retrieving-a-variable-from-my-database/
Share on other sites

Need some of your query, post it and will fix it up for ya. But here is an example
[code]
$sql = "SELECT real_name FROM table WHERE is = 1";
  $result = mysql_query($sql) or die (mysql_error());
    $r = mysql_fetch_array($result);
$realname = $r['real_name'];
echo "Welcome $realname, please upload your file.<br />";[/code]

Hope that helps

Ray
Thanks... it didn't... I don't understand why not.

below: name is the variable where I store their real name; users is the name of the table that stores the info; username is the variable where their username is entered; $username is the username the user entered to log into the script with.

At the beginning of the script:

[code]
function confirmUser($username, $password){
   global $conn;    
    $sql = "SELECT name FROM users WHERE username = '$username'";
    $result = mysql_query($sql) or die (mysql_error());
    $r = mysql_fetch_array($result);
    $rname = $r['name'];
   /* Add slashes if necessary (for query) */
   if(!get_magic_quotes_gpc()) {
    $username = addslashes($username);
   }
[/code]

Where I print it:
[code]
  echo "<h1>Welcome, <b>$rname</b>.</h1>";
[/code]
In PHP a variable is only valid inside the function where it is created. Using global variables is a bad practice. Instead, return the name from your function:

[code]function confirmUser($username, $password){
   global $conn;    
   /* Add slashes if necessary (for query) */
   if(!get_magic_quotes_gpc()) {
    $username = addslashes($username);
   }
    $sql = "SELECT name FROM users WHERE username = '$username'";
    $result = mysql_query($sql) or die (mysql_error());
    $r = mysql_fetch_array($result);
    $rname = $r['name'];

   return $rname;
}[/code]
Then when you call the function you call it like this:
[code]$rname = confirmUser($username, $password);[/code]
Okay, let's try this again. I was feeling discouraged last time. I'll try to explain this clearly and the results I get.

I have a login script where I want to display the real name corresponding to the correct username and password.

The file, and first function, begins with:

[code]<?

function confirmUser($username, $password){
   global $conn;    
   /* Add slashes if necessary (for query) */
   if(!get_magic_quotes_gpc()) {
    $username = addslashes($username);
   }
    $sql = "SELECT name FROM users WHERE username = '$username'";
    $result2 = mysql_query($sql) or die (mysql_error());
    $r = mysql_fetch_array($result2);
    $testvalue = $r['name'];
    
echo $testvalue;

   return $testvalue;
}
[/code]

Other things occur after "return $testvalue", but I'm not sure if I should indicate them all here. Among them are other "return" functions.

Now, echo $testvalue is successful - above the header of my file, the real name corresponding to the username and password the person entered, is displayed as expected.

However, later on in the code, in the place where I try to display $testvalue, the name isn't showing up. It displays simply: "Welcome, ."

[code]
function displayLogin(){
   global $logged_in;
   if($logged_in){
$testvalue = confirmUser($username, $password);
echo $testvalue;
   echo "<h1>Welcome, <b>$testvalue</b>.</h1>";
       ?>
[/code]

Why is this happening? I ran some tests with the $testvalue, and it never works when the entire $sql, $result2 part of the funcion is placed anywhere in the file other than where it is, but when leaving it where it is, it doesn't return the value to the place I want it at.

Does this make sense? Any help is much appreciated.
[!--quoteo(post=352160:date=Mar 6 2006, 01:55 PM:name=tinuviel)--][div class=\'quotetop\']QUOTE(tinuviel @ Mar 6 2006, 01:55 PM) [snapback]352160[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Why is this happening? I ran some tests with the $testvalue, and it never works when the entire $sql, $result2 part of the funcion is placed anywhere in the file other than where it is, but when leaving it where it is, it doesn't return the value to the place I want it at.

Does this make sense? Any help is much appreciated.
[/quote]

The code you posted should work. I think there's something else going on here. If you can echo $testvalue before the return and it's correct, but it's no longer correct directly after the return, then something very wierd is happening. $testvalue is not a global, correct?

Can you post the whole script?
Yeah, it's not a global variable. Here is the whole script:

[code]<?

function confirmUser($username, $password){
   global $conn;    

   if(!get_magic_quotes_gpc()) {
    $username = addslashes($username);
   }

    $sql = "SELECT name FROM users WHERE username = '$username'";
    $result2 = mysql_query($sql) or die (mysql_error());
    $r = mysql_fetch_array($result2);
    $testvalue = $r['name'];
    echo $testvalue;
    return $testvalue;

   /* Verify that user is in database */
   $q = "select password from users where username = '$username'";
   $result = mysql_query($q,$conn);
   if(!$result || (mysql_numrows($result) < 1)){
      return 1; //Indicates username failure
   }

   /* Retrieve password from result, strip slashes */
   $dbarray = mysql_fetch_array($result);
   $dbarray['password']  = stripslashes($dbarray['password']);
   $password = stripslashes($password);


   /* Validate that password is correct */
   if($password == $dbarray['password']){
      return 0; //Success! Username and password confirmed
   }
   else{
      return 2; //Indicates password failure
   }

}

function checkLogin(){
   /* Check if user has been remembered */
   if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){
      $_SESSION['realname'] = $_COOKIE['cookrealname'];
      $_SESSION['username'] = $_COOKIE['cookname'];
      $_SESSION['password'] = $_COOKIE['cookpass'];
   }

   /* Username and password have been set */
   if(isset($_SESSION['username']) && isset($_SESSION['password'])){
      /* Confirm that username and password are valid */
      if(confirmUser($_SESSION['username'], $_SESSION['password']) != 0){
         /* Variables are incorrect, user not logged in */
         unset($_SESSION['realname']);        
     unset($_SESSION['username']);
         unset($_SESSION['password']);
         return false;
      }
      return true;

   }
   /* User not logged in */
   else{
      return false;
   }
}

function displayLogin(){
   global $logged_in;
   if($logged_in){
    $testvalue = confirmUser($username, $password);
    echo $testvalue;
    echo "<h1>Welcome, <b>$testvalue</b>.</h1>";
?>
    <p>
        Click "Browse" to select the file you wish to upload, then click "Upload" to proceed.
    </p>
    <p>
        <form name="upload" id="upload" action="upload.php" ENCTYPE="multipart/form-data" method="post">
            <input type="file" id="userfile" name="userfile" src="template_files/but_browse.gif" border="0">
    </p>
    <p>
            <input name="upload" src="template_files/but_upload.gif" alt="upload button" border="0" type="image" value="Upload">
        </form>
    </p>
<?
      echo "<br /><p><a href=\"logout.php\"><img src=\"template_files/but_logout.gif\" alt=\"logout\" border=\"0\"></a></p>";
?><center>
   <font color=red><?=$_REQUEST[message]?></font>
   <br>

<?   }
   else{
?>

<form action="" method="post">
                 <table border="0" cellpadding="0" cellspacing="5" width="100%">
                <tbody><tr>
                  <td class="textB" align="left" valign="top">Username:</td>
                </tr>
                <tr>
                  <td class="text" align="left" valign="top"><input type="text" name="user" maxlength="30"></td>
                </tr>
                <tr><td><img src="template_files/spacer.gif" alt="" border="0" height="10" width="10"></td></tr>
                <tr>
                  <td class="textB" align="left" valign="top">Password:</td>
                </tr>
                <tr>
                  <td class="text" align="left" valign="top"><input type="password" name="pass" maxlength="30"></td>
                </tr>
                <tr><td><img src="template_files/spacer.gif" alt="" border="0" height="10" width="10"></td></tr>
                <tr>
                  <td class="textLogin" align="left" valign="top"><input type="checkbox" name="remember">
<font size="2">Remember me next time</td>
                </tr>
                <tr><td><img src="template_files/spacer.gif" alt="" border="0" height="20" width="10"></td></tr>
                <tr><td align="left"><input name="sublogin" src="template_files/but_login.gif" alt="'login' button" border="0" type="image" value="Login">
                </td></tr>
                <tr><td><img src="template_files/spacer.gif" alt="" border="0" height="10" width="10"></td></tr>
                </tbody></table>
</form>

<?
   }
}


if(isset($_POST['sublogin'])){
   /* Check that all fields were typed in */
   if(!$_POST['user'] || !$_POST['pass']){
      die('You didn\'t fill in a required field.');
   }
   /* Spruce up username, check length */
   $_POST['user'] = trim($_POST['user']);
   if(strlen($_POST['user']) > 30){
      die("Sorry, the username is longer than 30 characters, please shorten it.");
   }

   /* Checks that username is in database and password is correct */
   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);

   /* Check error codes */
   if($result == 1){
      die('That username doesn\'t exist in our database.');
   }
   else if($result == 2){
      die('Incorrect password, please try again.');
   }

   /* Username and password correct, register session variables */

   $_POST['user'] = stripslashes($_POST['user']);
   $_SESSION['realname'] = $rname;
   $_SESSION['username'] = $_POST['user'];
   $_SESSION['password'] = $md5pass;

   if(isset($_POST['remember'])){
      setcookie("cookrealname", $_SESSION['realname'], time()+60*60*24*100, "/");
      setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
      setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
   }

   /* Quick self-redirect to avoid resending data on refresh */
   echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[PHP_SELF]\">";
   return;
}

/* Sets the value of the logged_in variable, which can be used in your code */
$logged_in = checkLogin();

?>[/code]
Ok, there are all sorts of issues here.

As it stands right now, that code shouldn't display much output at all as displayLogin() is never called. In fact, I don't believe it will display anything at all. I think something is missing here because $logged_in isn't even defined until the end of the code you posted, and that's needed to make displayLogin() work..

Is $testvalue intended to be temporary? If not, most of the confirmUser() code won't get run because you return a value towards the beginning. Once it hits a return, it jumps back to the calling function and continues execution.

Is this something I can get shell access to? I can provide much more assistance that way... If so, PM me with the info and I can take a look...
[!--quoteo(post=352976:date=Mar 8 2006, 03:49 PM:name=tinuviel)--][div class=\'quotetop\']QUOTE(tinuviel @ Mar 8 2006, 03:49 PM) [snapback]352976[/snapback][/div][div class=\'quotemain\'][!--quotec--]
So it has been determined that this code SHOULD work, it just doesn't. Anyone else want to take a stab at why this is being quirky?
[/quote]

I honestly think there's something environmental going on here. As I mentioned to you in email, I don't have access to the database, but if I comment out the database calls and hard code "pretend" values in there as returns, the code works flawlessly.

Can you elaborate on the environment? Linux? Windows? Apache? PHP Version?
  • 2 weeks later...
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.