• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

PHP problem

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

joshhua5

Member
Joined
Jan 29, 2010
Code:
<?php
    ini_set('display_errors', true);
    error_reporting(E_ALL);

     $username = $_POST["RGusername"];
     $password = md5($_POST["RGpassword"]);

     if($username&&$password)
     {
        mysql_connect('localhost','root','admin');
        mysql_select_db("database") or die("Couldn't find database");
        
        $Query = mysql_query("SELECT * FROM account WHERE Username='$username' LIMIT 1");
        print"<pre>Query: ".$Query."</pre>";
        $result = mysql_query("SELECT * FROM account WHERE Username='$username' LIMIT 1");
        print "<pre>Result: ".var_dump($result)."</pre>";
        $id = (mysql_insert_id() + 1);
        $rows = mysql_num_rows($Query);
        echo $rows ;
        if($rows == 0)
        {
          mysql_query("SELECT * FROM account");
          mysql_query("INSERT INTO `account` (Username, Password)
          VALUES($username, $password)");

          echo $password;  ?><html> <br />  </html> <?php
          echo $rows;      ?><html> <br />  </html> <?php
          echo $username;  ?><html> <br />  </html> <?php
          echo $id;        ?><html> <br />  </html> <?php
          echo mysql_error();   ?><html> <br />  </html> <?php
          if(mysql_num_rows($Query) == 1)
          {
            // Successful account creation
            echo("Account created");
          }
          else
              echo("Account not created, problem hit");
        }
        else
            echo("Username already exists");
     }
     else
         echo("Please enter all feilds");
?>


There's the code and what it's doing is inserting the username and password into a database then checking that it's there, can't fix it :3
 
Last edited:
I'm still learning PHP myself, but if it is always inserting an entry into the database, then "rows" is zero. Meaning, your search or variable assignment is wrong. Hope that gives you a starting point.

EDIT: Could the literal quotes (' ') be causing it?
 
Correct way (besides of obvious SQL injection possibility):

Code:
<?php
     $username = $_POST["RGusername"];
     $password = $_POST["RGpassword"];
     
     if($username&&$password)
     {
        mysql_connect('localhost','root','********');
        mysql_select_db("phplogin") or die("Couldn't find database");
        
        $Query = mysql_query("SELECT * FROM users WHERE 'user'='$username' LIMIT 1");
        $rows = mysql_num_rows($Query);
        if($rows == 0)
        {
          mysql_query("INSERT INTO users (user, password)
          VALUES($username, $password)");
          $id = mysql_insert_id();
          if($id)
          {
            // Successful account creation
            echo("Account created");
          }
          else
              die("Account not created, problem hit");
        }
        else
            die("Username already exists");
     }
     else
         die("Please enter all feilds");
?>

You have a lot to learn, my young padawan.
 
Aren't SQL injections fun?

Good start for 2 hours worth of work. I would strongly suggest reading up about injection attacks and how to minimise/eliminate them.
 
Code:
$Query = mysql_query("SELECT * FROM users WHERE 'user'='$username' LIMIT 1");

I think you're trying to look for $username in the `user` column on the table here, yeah? If that's the case you need to use backticks, not quotes, for `user`. Anything in single quotes in mysql is considered a literal string, so the above code will select 0 rows for any $username except 'user'.
 
Last edited:
Code:
$Query = mysql_query("SELECT * FROM users WHERE 'user'='$username' LIMIT 1");

I think you're trying to look for $username in the `user` column on the table here, yeah? If that's the case you need to use backticks, not quotes, for `user`. Anything in single quotes in mysql is considered a literal string, so the above code will select 0 rows for any $username except 'user'.

I would say this is correct! I would use:

Code:
$Query = mysql_query("SELECT * FROM users WHERE user='$username' LIMIT 1");
 
Here's how I might rewrite this, keeping the functionality (almost) the same as the original. I tend to strictly type-check while coding, and I'm a bit more cautious about using uninitialized variables:

PHP:
<?php
// When testing, ALWAYS make sure you can see all errors (incl. warnings)
// and FIX THEM. Once you put this into production you'd turn off display_errors.
// (And hopefully log them somewhere that you check often.)
ini_set('display_errors', true);
error_reporting(E_ALL);

$user = isset($_POST['RGusername') ? $_POST['RGusername'] : null;
$pass = isset($_POST['RGpassword') ? $_POST['RGpassword'] : null;

if( !is_null($user) && !is_null($pass) )
{
    // We hang onto the result of mysql_connect here ($db) because it will 
    // be useful later.
    if(false == ($db = mysql_connect('hostname', 'user', 'password')))
        die("Unable to connect to db.");
    if( !mysql_select_db('phplogin') )
        die("Couldn't find database.");
    
    // mysql_real_escape_string ensures that if some jerk should happen to use a "'" in 
    // the password the query won't break.
    $qry = sprintf("SELECT * FROM `users` WHERE `user`='%s'", mysql_real_escape_string($user, $db));
    $res = mysql_query($qry, $db);
    $num_rows = mysql_num_rows($res);
    
    if( 0 < $num_rows )
        die('Username already exists.');
    
    // Triple '=' here because mysql_num_rows returns false if it fails. false is considered 
    // to be == 0 but not === 0. 
    // If we use only double equals to compare, we can't tell the difference between
    // 0 rows returned (which returns the int 0) and an error with mysql_num_rows (which returns false).
    if( 0 === $num_rows )
    {
        // Again, careful with what we insert... 
        $qry = sprintf("INSERT INTO `users` (`user`,`password`) VALUES ('%s', '%s')", 
            mysql_real_escape_string($user, $db),
            mysql_real_escape_string($pass, $db)
        );
        // NOTE: On INSERT/UPDATE/DELETE/etc. statements, mysql_query returns true/false.
        //  No need to check num_rows or insert_id.
        if( mysql_query($qry, $db) )
            echo "Account created.";
        else
            die("Account not created. ;(");
    }
}
else
    die('Please enter all fields');

// Closing PHP tag intentionally left out (that can be a whole other issue ...)

Holy crap the PHP bbcode tag is ugly!
 
Last edited:
I think the new code looks good. Just to make sure all the bases are covered, have you logged in to the database with the username and password and tried to execute the statements you're trying to make under that account?

To debug it correctly you probably want to output stuff to the console all the way through your code. Then you can see where it's breaking.
 
mysql_query doesn't return the data from the query itself, it returns a PHP "resource" which you can then use to get the data returned (using mysql_fetch_assoc or similar). It can also return 'false' if there was a syntax error in the query.

Try this, where you're running the query:
PHP:
    $Query = "SELECT * FROM account WHERE Username='$username' LIMIT 1";
    print "<pre>Query: ".$Query."</pre>"; // Print out the query, so we can try this directly on the SQL command line to test...
    $result = mysql_query($Query);
    print "<pre>Result: ".var_dump($result)."</pre>";  // If this sez 'false' you've got a problem with the query.
    if( !$result ) 
        print "<pre>There was an error\n".mysql_error()."</pre>";
    else
    {
        $data = array();
        while($row = mysql_fetch_assoc($result))
            $data[] = $row;
        print "<pre>We have data from the DB: \n".print_r($data, true)."</pre>";
    }

EDIT: Oops, I misread your function above.. this code change (making the first line _NOT_ a mysql_query call) should work a little better.
 
thought I'd post everything that's printing out so far
it


Query: Resource id #4
resource(5) of type (mysql result)
Result:
032250170a0dca92d53ec9624f336ca24
0
josh
1
Unknown column 'josh' in 'field list'
Account not created, problem hit
 
I made a typo on my last code example... I want to see the actual query that's getting run, so change that first $Query = line to this:
$Query = "SELECT * FROM account WHERE Username='$username' LIMIT 1";

That way when you print it you'll see the actual query that you're trying to run.
 
PC i thank you for all the help, i just gave up on my method and used your code, but I'm now going though the syntax and trying to learn what's all going on and have a good understanding. SO I'm accually learning.
 
Back