New Posts  All Forums:Forum Nav:

Help with some PHP

post #1 of 9
Thread Starter 
Hey Guys

Currently building a login for my site, am going through and testing some stuff, and was wondering what was wrong. What should happen as I print_r this code is a display of the requested fields for the user. This is just a test for me as I am running. However, I get a

"Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /homepages/28/d413246400/htdocs/TheDarkMasons/userData/core/functions/users.php on line 14"

error.

Any suggestions

Here is the user_data function


function user_data($userID) {
$data = array();
$userID = (int)$userID;

$func_num_args = func_num_args();
$func_get_args = func_get_args();

if ($func_num_args >1) {
unset($func_get_args[0]);

$fields ='`' . implode('`, `',$func_get_args) . '`';
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `userData` WHERE `userID` = '$userID'"));
print_r($data);
die();
return $data;

}

}

And here is where $fields is picked up from

if (logged_in()===true) {
$session_user_id = $_SESSION;
$user_data = user_data($session_user_id, 'userID','displayName','firstName','secondName','emailAddress','passWord');
}


Thanks for any help.
post #2 of 9
which line is line 14? and can you use code tags around source code please
post #3 of 9
I'm a day late, but in case you're still working on this I'll take a stab at it.

I'm pretty much blindly speculating, but it sounds like you're not passing a valid SQL statement to msql_query().

Do you need some concat operators on either side of that $UserID in your query? I can never remember all the single quote / double quote rules for PHP. If you do, you'll probably need to build that first and then tuck it in a variable before passing it. (if that doesn't make sense, see example here)

If that's not the issue, I would start troubleshooting with the value of $fields.
post #4 of 9
Thread Starter 
Haven't totally fixed it, instead of picking up specific fields, I just picked up the entire database instead. Doesn't really make a difference as everything is encrypted and will only be shown to the user if they are able to login anyway.
post #5 of 9
Quote:
Originally Posted by Atrum Rgis View Post

Haven't totally fixed it, instead of picking up specific fields, I just picked up the entire database instead. Doesn't really make a difference as everything is encrypted and will only be shown to the user if they are able to login anyway.

I always have trouble when selecting specific columns - for small databases (<1GB) it doesn't make much of a difference to just select all, especially when there's so few columns in your case I imagine.

The problem, I would guess, is the function_get_args() function. Why not just pass the values to the function as an array?? Instead of doing it inside the function? I've never seen it done like that before...just have two inputs into the user_data function ($user_id and the $column_names) this is covered here, if you didn't feel comfortable with it: http://php.net/manual/en/functions.arguments.php

Some general advice though, split your SQL query into a couple different parts, i.e
Code:
function database($sql) {
  global $database;
  $connection=mysql_connect($database["host"],$database["username"],$database["password"]);
  if(!$connection) {
    die("Couldn't connect");
  }
  mysql_select_db($database["database"],$connection);
  $query=mysql_query($sql);
  return($query);
}

$SQL="SELECT $fields FROM `userData` WHERE `userID` = '$userID'";
echo $SQL;
$result=database($SQL);
while($row=mysql_fetch_array($result,MYSQL_ASSOC)){
  DoStuff();
}

That way, you can try copying and pasting the SQL generated into something like phpMyAdmin (or whatever) to see more explicitly where the errors are occuring and tweak it till you get it right. You can also put little echos and things in there to see where the code is breaking, for example, is it making it into that if block?

But yeah, as you say, getting every column isn't an issue really smile.gif
Edited by Manticorp - 5/21/12 at 5:28pm
My Current Setup
(15 items)
 
An excellent keyboard
Microsoft SideWinder X4 Keyboard
 
CPUMotherboardGraphicsRAM
Intel i7 860 Dell 0T568R Nvidia gtx 560 ti 448 Corsair Vengeance 
Hard DriveHard DriveOptical DriveCooling
Corsair force 3 120gb Western Digital Generic CD/DVD drive Stock 
OSMonitorMonitorKeyboard
Windows 7 ultimate Samsung Syncmaster p2450 Samsung Syncmaster p2450 Microsoft Sidewinder X4 
PowerCaseMouse
OCZ ModXStream Pro 600W Stock XPS8100 Logitech wireless MX 
  hide details  
Reply
My Current Setup
(15 items)
 
An excellent keyboard
Microsoft SideWinder X4 Keyboard
 
CPUMotherboardGraphicsRAM
Intel i7 860 Dell 0T568R Nvidia gtx 560 ti 448 Corsair Vengeance 
Hard DriveHard DriveOptical DriveCooling
Corsair force 3 120gb Western Digital Generic CD/DVD drive Stock 
OSMonitorMonitorKeyboard
Windows 7 ultimate Samsung Syncmaster p2450 Samsung Syncmaster p2450 Microsoft Sidewinder X4 
PowerCaseMouse
OCZ ModXStream Pro 600W Stock XPS8100 Logitech wireless MX 
  hide details  
Reply
post #6 of 9
Hello,

I'm a new member here, but I had to sign up to provide some useful information for you. First of all, please move away from using mysql functions to call your database. Instead, use PHP PDO or mysqli. This turns database queries into objects which you can pass throughout classes and other methods. Not only is it easier to read, it is way more secure. Here's a link to get you started: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/.

Below is a lot easier way of getting what you need from the database. It is a class, and if you do not know what classes or object-oriented programming is, I highly recommend you get into it. It makes your coding life so much easier. Save the top part of code as config.php and the rest of it as database.php. Once you have saved that, all you have to do is call include_once 'database.php' in your file that you have your code in, then instantiate it like so:

(Mind you, this code is untested so if there are errors I apologize)
Code:
 $database = new Database();
  $newUserID = $database->getUserID($userID);
 echo $newUserID;

Code:
config.php:
<?php
        //Save these 4 lines as config.php which we will include in our database.php file.
        //This is for security purposes.  Imagine a hacker getting into your database.php
        //file with the datbase password and username. Your users would be pissed!
        define('DB_HOST', 'localhost');
    define('DB_USER', 'username');
    define('DB_PASS', 'password');
    define('DB_NAME', 'db_name');
?>

database.php:
<?php

/* save this as database.php

then include the following in your original .php file that you had the code:
 include_once (database.php';
  $database = new Database();
  $userID = $database->getUserID();
  
*/
    include_once "includes/config.php";

        class Database
        {
                private $_userID;
                private $_db;
                
                private __construct()
                {
                        try {
                                $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
                                %this->_db = new PDO($dsn, DB_USER, DB_PASS);
                            } catch (PDOException $e) {
                                echo 'Connection failed: ' . $e->getMessage();
                                exit;
                            }
                }
                
                public function getUserID($userID)
                {
                        $this->_userID = $userID;
                        $sql = "SELECT field 
                                        FROM userData 
                                        WHERE userID = :userID";
                                      
                      try
                      {
                          $stmt = $this->_db->prepare($sql);
                          $stmt->bindParam(':userID', $this->_userID, PDO::PARAM_INT); //if userID is string, change to PARAM_STR
                          $stmt->execute();
                         return $stmt->fetch(); //can also return $stmt->fetchColumn() and $stmt->fetchAll();
                      }
                      catch(PDOException $e) { echo $e->getMessage(); }
                }

                public function anotherDatabaseCall($userID)
                {
                        $this->_userID = $userID;
                        $sql = "SELECT * 
                                     FROM userData 
                                    WHERE userID = :userID";
                                      
                      try
                      {
                          $stmt = $this->_db->prepare($sql);
                          $stmt->bindParam(':userID', $this->_userID, PDO::PARAM_INT); //if userID is string, change to PARAM_STR
                          $stmt->execute();
                         return $stmt->fetchAll();
                      }
                      catch(PDOException $e) { echo $e->getMessage(); }
                }
        }

?>

Edited by OneSneakyMofo - 5/28/12 at 5:20pm
post #7 of 9
Good post OneSneaky.

This is a bit of a tangent, but I've always been curious:

What is the upside to the dedicated config file for declaring constants for the database credentials?

I see this technique everywhere. I understand that implementing in this way makes the information easy to maintain, but beyond that, why not just include this data as private class properties in the Database class?
post #8 of 9
Quote:
Originally Posted by Warfarin88 View Post

Good post OneSneaky.
This is a bit of a tangent, but I've always been curious:
What is the upside to the dedicated config file for declaring constants for the database credentials?
I see this technique everywhere. I understand that implementing in this way makes the information easy to maintain, but beyond that, why not just include this data as private class properties in the Database class?

I explained this in the comments of the file that I posted, but I'll explain in better detail. Let's say your database. php file has your database username/password/table in a protected or private method. Yes, it is secure to outsiders, but what if, for whatever reason, your php is exploited, cracked, hacked, or a developer wants to destroy your system? The database credentials are exposed and can be used to gather username's personal information. This can range anywhere from emails, passwords to credit card information. Not only do they have it, they can then change it, manipulate it, destroy it, etc. Storing it in a separate file outside of web root directory and not touching any source code makes your database abundantly more secure.

Another good reason as you listed: easier access for system administrators that want to manipulate their system. Instead of mixing sysadmins with the developers, it keeps it separate and clean.

See more here:

http://stackoverflow.com/questions/97984/how-to-secure-database-passwords-in-php
post #9 of 9
I was tracking on keeping sensitive information out of the web root. I hadn't considered separating out logic for sysadmins though. That makes sense.

Thanks for the reply.
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Web Coding