Jump to content

Archived

This topic is now archived and is closed to further replies.

dual_alliance

MySQL Error Has to do with PHP code. [Solved]

Recommended Posts

I am making a registration script using functions.  However its causing a MySQL error.  I found this code on a tutorial site but it won't even work :/.  Once it starts working l can edit it since l am new to PHP.

I get the following errors:

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\adminp\register.php on line 15

Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\adminp\register.php on line 16

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\adminp\register.php on line 27

I'm using localhost as well.

[code=php:0]<?php
session_start();
include("database.php");

/**
* Returns true if the username has been taken
* by another user, false otherwise.
*/
function usernameTaken($username){
  global $conn;
  if(!get_magic_quotes_gpc()){
  $username = addslashes($username);
  }
  $q = "SELECT 'username' FROM 'users' WHERE username = '$username'";
  $result = mysql_query($q, $conn);  <<<<<<<Line 15>>>>>>>
  return (mysql_numrows($result) > 0);
}

/**
* Inserts the given (username, password) pair
* into the database. Returns true on success,
* false otherwise.
*/
function addNewUser($username, $password){
  global $conn;
  $q = "INSERT INTO users VALUES ('$username', '$password')"; <<<<<<<Line 26>>>>>>>
  return mysql_query($q,$conn);
}

/**
* Displays the appropriate message to the user
* after the registration attempt. It displays a
* success or failure status depending on a
* session variable set during registration.
*/
function displayStatus(){
  $uname = $_SESSION['reguname'];
  if($_SESSION['regresult']){
?>

<h1>Registered!</h1>
<p>Thank you <b><? echo $uname; ?></b>, your information has been added to the database, you may now <a href="main.php" title="Login">log in</a>.</p>

<?php
  }
  else{
?>

<h1>Registration Failed</h1>
<p>We're sorry, but an error has occurred and your registration for the username <b><?php echo $uname; ?></b>, could not be completed.<br>
Please try again at a later time.</p>

<?php
  }
  unset($_SESSION['reguname']);
  unset($_SESSION['registered']);
  unset($_SESSION['regresult']);
}

if(isset($_SESSION['registered'])){
/**
* This is the page that will be displayed after the
* registration has been attempted.
*/
?>

<html>
<title>Registration Page</title>
<body>

<?php displayStatus(); ?>

</body>
</html>

<?php
  return;
}

/**
* Determines whether or not to show to sign-up form
* based on whether the form has been submitted, if it
* has, check the database for consistency and create
* the new account.
*/
if(isset($_POST['subjoin'])){
  /* Make sure all fields were entered */
  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.");
  }

  /* Check if username is already in use */
  if(usernameTaken($_POST['user'])){
      $use = $_POST['user'];
      die("Sorry, the username: <strong>$use</strong> is already taken, please pick another one.");
  }

  /* Add the new account to the database */
  $md5pass = md5($_POST['pass']);
  $_SESSION['reguname'] = $_POST['user'];
  $_SESSION['regresult'] = addNewUser($_POST['user'], $md5pass);
  $_SESSION['registered'] = true;
  echo "<meta http-equiv=\"Refresh\" content=\"0;url=$PHP_SELF\">";
  return;
}
else{
/**
* This is the page with the sign-up form, the names
* of the input fields are important and should not
* be changed.
*/
?>

<html>
<title>Registration Page</title>
<body>
<h1>Register</h1>
<form action="<?php echo $PHP_SELF; ?>" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="Join!"></td></tr>
</table>
</form>
</body>
</html>


<?php
}
?>[/code]

Share this post


Link to post
Share on other sites
see what the error is by uysing this code.

$result = mysql_query($q, $conn) or die(mysql_error()); 

I should produce and error to say what is wrong in the query..us

Share this post


Link to post
Share on other sites
Knowing why will help ... change

[code]$result = mysql_query($q, $conn);  <<<<<<<Line 15>>>>>>>[/code]

to

[code]$result = mysql_query($q, $conn) or die("Error: ". mysql_error(). " with query ". $q);[/code]

Share this post


Link to post
Share on other sites
try not single quoting things that are not values!!!

$q = "SELECT username FROM users WHERE username = '$username'";

I prefer:

$q = "SELECT `username` FROM `users` WHERE `username` = '$username'";

but thats just me....

Plus yoru insert statement could easilt be wrong.... I prefer to define my insert statmenets with all the fields of the table listed and the corresonding values. Unless your table only has 2 fields that query string will fail.

Buttom line its not yoru code but yoru queries that are wrong.

Share this post


Link to post
Share on other sites
Well like l said l got this code from a tutorial site.  And was hoping so modify it but l have to get it to work first.

king arthur you suggested that it might be $conn so l have included the database.php script.

[code=php:0]<?php

include("constants.php");
     
class MySQLDB
{
  var $connection;        //The MySQL database connection
  var $num_active_users;  //Number of active users viewing site
  var $num_active_guests;  //Number of active guests viewing site
  var $num_members;        //Number of signed-up users
  /* Note: call getNumMembers() to access $num_members! */

  /* Class constructor */
  function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
     
      /**
      * Only query database to find out number of members
      * when getNumMembers() is called for the first time,
      * until then, default value set.
      */
      $this->num_members = -1;
     
      if(TRACK_VISITORS){
        /* Calculate number of users at site */
        $this->calcNumActiveUsers();
     
        /* Calculate number of guests at site */
        $this->calcNumActiveGuests();
      }
  }

  /**
    * confirmUserPass - Checks whether or not the given
    * username is in the database, if so it checks if the
    * given password is the same password in the database
    * for that user. If the user doesn't exist or if the
    * passwords don't match up, it returns an error code
    * (1 or 2). On success it returns 0.
    */
  function confirmUserPass($username, $password){
      /* Add slashes if necessary (for query) */
      if(!get_magic_quotes_gpc()) {
      $username = addslashes($username);
      }

      /* Verify that user is in database */
      $q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      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
      }
  }
 
  /**
    * confirmUserID - Checks whether or not the given
    * username is in the database, if so it checks if the
    * given userid is the same userid in the database
    * for that user. If the user doesn't exist or if the
    * userids don't match up, it returns an error code
    * (1 or 2). On success it returns 0.
    */
  function confirmUserID($username, $userid){
      /* Add slashes if necessary (for query) */
      if(!get_magic_quotes_gpc()) {
      $username = addslashes($username);
      }

      /* Verify that user is in database */
      $q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      if(!$result || (mysql_numrows($result) < 1)){
        return 1; //Indicates username failure
      }

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

      /* Validate that userid is correct */
      if($userid == $dbarray['userid']){
        return 0; //Success! Username and userid confirmed
      }
      else{
        return 2; //Indicates userid invalid
      }
  }
 
  /**
    * usernameTaken - Returns true if the username has
    * been taken by another user, false otherwise.
    */
  function usernameTaken($username){
      if(!get_magic_quotes_gpc()){
        $username = addslashes($username);
      }
      $q = "SELECT username FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      return (mysql_numrows($result) > 0);
  }
 
  /**
    * usernameBanned - Returns true if the username has
    * been banned by the administrator.
    */
  function usernameBanned($username){
      if(!get_magic_quotes_gpc()){
        $username = addslashes($username);
      }
      $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      return (mysql_numrows($result) > 0);
  }
 
  /**
    * addNewUser - Inserts the given (username, password, email)
    * info into the database. Appropriate user level is set.
    * Returns true on success, false otherwise.
    */
  function addNewUser($username, $password, $email){
      $time = time();
      /* If admin sign up, give admin user level */
      if(strcasecmp($username, ADMIN_NAME) == 0){
        $ulevel = ADMIN_LEVEL;
      }else{
        $ulevel = USER_LEVEL;
      }
      $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', $time)";
      return mysql_query($q, $this->connection);
  }
 
  /**
    * updateUserField - Updates a field, specified by the field
    * parameter, in the user's row of the database.
    */
  function updateUserField($username, $field, $value){
      $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'";
      return mysql_query($q, $this->connection);
  }
 
  /**
    * getUserInfo - Returns the result array from a mysql
    * query asking for all information stored regarding
    * the given username. If query fails, NULL is returned.
    */
  function getUserInfo($username){
      $q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      /* Error occurred, return given name by default */
      if(!$result || (mysql_numrows($result) < 1)){
        return NULL;
      }
      /* Return result array */
      $dbarray = mysql_fetch_array($result);
      return $dbarray;
  }
 
  /**
    * getNumMembers - Returns the number of signed-up users
    * of the website, banned members not included. The first
    * time the function is called on page load, the database
    * is queried, on subsequent calls, the stored result
    * is returned. This is to improve efficiency, effectively
    * not querying the database when no call is made.
    */
  function getNumMembers(){
      if($this->num_members < 0){
        $q = "SELECT * FROM ".TBL_USERS;
        $result = mysql_query($q, $this->connection);
        $this->num_members = mysql_numrows($result);
      }
      return $this->num_members;
  }
 
  /**
    * calcNumActiveUsers - Finds out how many active users
    * are viewing site and sets class variable accordingly.
    */
  function calcNumActiveUsers(){
      /* Calculate number of users at site */
      $q = "SELECT * FROM ".TBL_ACTIVE_USERS;
      $result = mysql_query($q, $this->connection);
      $this->num_active_users = mysql_numrows($result);
  }
 
  /**
    * calcNumActiveGuests - Finds out how many active guests
    * are viewing site and sets class variable accordingly.
    */
  function calcNumActiveGuests(){
      /* Calculate number of guests at site */
      $q = "SELECT * FROM ".TBL_ACTIVE_GUESTS;
      $result = mysql_query($q, $this->connection);
      $this->num_active_guests = mysql_numrows($result);
  }
 
  /**
    * addActiveUser - Updates username's last active timestamp
    * in the database, and also adds him to the table of
    * active users, or updates timestamp if already there.
    */
  function addActiveUser($username, $time){
      $q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";
      mysql_query($q, $this->connection);
     
      if(!TRACK_VISITORS) return;
      $q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";
      mysql_query($q, $this->connection);
      $this->calcNumActiveUsers();
  }
 
  /* addActiveGuest - Adds guest to active guests table */
  function addActiveGuest($ip, $time){
      if(!TRACK_VISITORS) return;
      $q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')";
      mysql_query($q, $this->connection);
      $this->calcNumActiveGuests();
  }
 
  /* These functions are self explanatory, no need for comments */
 
  /* removeActiveUser */
  function removeActiveUser($username){
      if(!TRACK_VISITORS) return;
      $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'";
      mysql_query($q, $this->connection);
      $this->calcNumActiveUsers();
  }
 
  /* removeActiveGuest */
  function removeActiveGuest($ip){
      if(!TRACK_VISITORS) return;
      $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";
      mysql_query($q, $this->connection);
      $this->calcNumActiveGuests();
  }
 
  /* removeInactiveUsers */
  function removeInactiveUsers(){
      if(!TRACK_VISITORS) return;
      $timeout = time()-USER_TIMEOUT*60;
      $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";
      mysql_query($q, $this->connection);
      $this->calcNumActiveUsers();
  }

  /* removeInactiveGuests */
  function removeInactiveGuests(){
      if(!TRACK_VISITORS) return;
      $timeout = time()-GUEST_TIMEOUT*60;
      $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";
      mysql_query($q, $this->connection);
      $this->calcNumActiveGuests();
  }
 
  /**
    * query - Performs the given query on the database and
    * returns the result, which may be false, true or a
    * resource identifier.
    */
  function query($query){
      return mysql_query($query, $this->connection);
  }
};

/* Create database connection */
$database = new MySQLDB;

?>[/code]

AndyB thanks for your suggestion it comes up with a more specific error (as it should) and the error is :

[code]Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\adminp\register.php on line 15
Error: with query SELECT `username` FROM `users` WHERE `username` = 'hello'[/code]

I know that it is trying to see if the username is already in use but shouldn't the code be so that if it doesn't exist it continues on with the script?

Share this post


Link to post
Share on other sites
change $conn to $database in register.php or
add $conn = new MySQLD near the start of register.php or
change last line in database.php to $conn = new MySQLD

Share this post


Link to post
Share on other sites
Hi sasa,

Thanks for your help however it does not fix the problem :(.

If l have $conn = new MySQLD near the start of register.php l get(it is also the same if l do it in database.php):

Fatal error: Class 'MySQLD' not found in C:\wamp\www\adminp\register.php on line 5

And if l name $conn to $database l get the error l did before.

Share this post


Link to post
Share on other sites
i make mistake it musr be class MySQLDB

sorry

Share this post


Link to post
Share on other sites
Thats ok, still the error though....

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\adminp\register.php on line 19
Error: with query SELECT `username` FROM `users` WHERE `username` = 'hello'

Share this post


Link to post
Share on other sites
try to make new database.php
let be database1.php
[code]
<?php
$conn=mysql_connect('host','user','password'); // change 'host' to your host name etc.
mysql_select_db('database_name',$conn);
?>
[/code]
include database1.php not old database.php
use original, 1st code you made

Share this post


Link to post
Share on other sites
Hello sasa,

Thankyou for your help after doing that l got another error which l fixed up without any trouble.  And it now works :)

dual_alliance

Share this post


Link to post
Share on other sites

×

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.