You are viewing our Forum Archives. To view or take place in current topics click here.
Need help with PhP script
Posted:

Need help with PhP scriptPosted:

tmrxdubstep
  • New Member
Status: Offline
Joined: Jun 07, 201311Year Member
Posts: 36
Reputation Power: 1
Status: Offline
Joined: Jun 07, 201311Year Member
Posts: 36
Reputation Power: 1
First off im a complete noob with SQL & PhP but i hoping someone will tell me (and explain maybe :smile:) where im going wrong.

So I'm trying to get this login script to work i have the SQl database set up correctly as it connects to it fine but when i try to login from my program it gives me this error >

mysql_num_rows() expects parameter 1 to be resource boolean given, line 32 which is $result = mysql_num_rows($query1);


So i spent a hour or so googling that error and came to think its because of the prefix that the database uses, the prefix is "smf_2" but the table is called "smf_2members" so im not sure if this is the problem or not?

Any help will be really appreciated!

<?php
if($_POST['task'] != "")
{
    $task = $_POST['task'];
    $member_name = $_POST['user'];
    $passwd = $_POST['pass'];
}

$service = "*****"; //the address of the sql server (MySQL Hostname)
$serviceUsername= "******"; //the username to log in to the server (MySQL Username)
$servicePassword = "*******"; //the password to log into the server
$database = "*******"; //the name of the database to connect to
$table = "smf_2members"; //the name of the table you created
$hash = "secretsalt"; //adds to the password before hashing
$pageLocation = "C:\xampp\htdocs\login.php"; //the location of this page

//connect to the msql server
mysql_connect($service,$serviceUsername,$servicePassword);
//select the database, and if it fails give the error
mysql_select_db($database) or die("Unable to select database");


$umember_name = mysql_real_escape_string($member_name);
$passwd = mysql_real_escape_string($passwd);

//if the task is to log in
if($task == "login")
{
    //select all the users with the posted name from the table
    $query1 = mysql_query("SELECT * FROM $table WHERE name='$member_name'");
    //set the result to the number of rows
    $result = mysql_num_rows($query1);
    //if there aren't any rows with the username, then the username hasn't been created
    if($result == 0)
    {
        echo 'Error! The username you specified does not exist!';
    }
    else //if there is one row (or more which will never happen because the account won't be made)
    {

            $row = mysql_fetch_array($query1); //get the row
                            $password2 = $row['passwd']; //get the password from that row
                            $passwordHashed = substr(sha1($hash.$password), 0, 40);
                if ($passwordHashed == $password2) //if the posted password and the database password match
                    {
                        if($row['is_activated'] == 1) //if the account has been verified
                        {
                            echo 'successful'; //success
                        }
                        else if($row['is_activated'] == 0) //if the account hasn't been verified
                        {
                                echo "Error! Account not activated!";
                             
                        }
                        else //if the account is disabled
                        {
                            echo "Your account has been disabled";
                        }
                    }
                else //if they don't match
                    {
                        echo "Error! Incorrect password!"; //error
                    }

    }
}
?>
#2. Posted:
Nic
  • Retired Staff
Status: Offline
Joined: Jun 08, 201014Year Member
Posts: 2,466
Reputation Power: 1070
Motto: I've been watching you all day.
Motto: I've been watching you all day.
Status: Offline
Joined: Jun 08, 201014Year Member
Posts: 2,466
Reputation Power: 1070
Motto: I've been watching you all day.
$umember_name = mysql_real_escape_string($member_name);


^ First of all, there is a typo in the variable (umember).

The database name and table can have a prefix, just make sure you have the correct data in the respective variables.

Before trying to get the rows, first check if "$query1" contains anything to begin with (check if it is an array and if it isn't empty, for example). By the looks of things, you simply aren't getting any results from the database.

Try running the actual SQL in phpMyAdmin until you get the desired result. Then, put it in your PHP code, and slowly replace parts of the query with your variables. This way you'll figure out what's wrong when it suddenly stops working after, for example, you try using the database variable.

Also, ditch mysql_* functions. I'm all for learning a language by messing around with dodgy code, but mysql_* is deprecated for good reasons, and even removed all together in PHP 7. Before continuing with your current issue, I'd suggest switching to mysqli_* functions (and when you feel comfortable with that, switch to mysqli/PDO class). Mysql_* is just something you don't want to learn.
#3. Posted:
tmrxdubstep
  • New Member
Status: Offline
Joined: Jun 07, 201311Year Member
Posts: 36
Reputation Power: 1
Status: Offline
Joined: Jun 07, 201311Year Member
Posts: 36
Reputation Power: 1
Ahh didn't see that typo..

Thing is if i make a new database it works fine, It just refuses to work with an existing one.

I'll look into the mysqli_* functions

Thank you!
#4. Posted:
Cyimking
  • 2 Million
Status: Offline
Joined: May 02, 201212Year Member
Posts: 1,129
Reputation Power: 34
Status: Offline
Joined: May 02, 201212Year Member
Posts: 1,129
Reputation Power: 34
Few things:

1. Learn mysqli_ functions then go directly into PDO. After PDO go DIRECTLY to DAL.

2. Validate your data and clean your data. ALWAYS! Even if you are learning, it's best to learn the proper way of handling data. You clean your data but didn't validate your data. Of course, you will have to do this at some point but always practice this. At some point, you will either write your own validation library or find a good one online!

3. Use ini files for configuration. In the real world you will have different configurations for your application. On your local machine, your database username will be root (for the most part) but on the development server it may be something else. Additionally, you will use git at some point to manage your application and having an ini config file will come in handy for configuration management.

Example

config.ini

; Configuration File
; Contains database credentials for local machine, development server and production server

; Database credentials for local machine
[local]
host = localhost
user = root
password = password
database = project

; Database credentials for development server
[development]
host = 125.215.42.256
user = dev_5212
password = jack_rabbit
database = dev_project

; Database credentials for production server
[production]
host = [ Register or Signin to view external links. ]
user = mysite_2525
password = cyimking_rule
database = prod_project





global.php

//This file contains all your global settings for your application.
// You will have one at some point but this is an example to just show you how to use ini files :-)

....
// Which server are you on? We assume local so we comment out the development / production lines
define('database', 'local');
// define('database', 'development');
// define('database', 'production');
...




database.php

// Again just an example. Professionally you will use bootstrap to load classes.
// However we need to load the global file to get the settings, so we must include it.
require_once 'global.php';

// Parse the ini config file into an array!
$config = parse_ini_file(__DIR__ . 'config.ini', true);

// No need to reassign variables.. so... just connect to the DB
// Since you are not using OOP, I will not use OOP for this example...
$connection = mysqli_connect($config[database]['host'],$config[database]['user'], $config[database]['password'], $config[database]['database']);

// Check the connection
// Check the connection
if(mysqli_connect_errno()){
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}



login.php

/*
* @author - You
* @description - Login the user?
*/


/*
* So...
* 1. If someone access this file directly then either show a form OR redirect them to the proper form
*     Else you will get an error.
*     Why? Well the variable $_POST will be empty thus you will get an error on this line:
*    $umember_name = mysql_real_escape_string($member_name);
*    In this example, we will redirect them to the HTML file that contains the proper form.
*
* 2. Someone CAN submit an empty form. How?
*    Well one could use cURL to directly pass values to this file. Really? Yay really. Most API's use cURL (like instagram)
*    Thus you will have to check if the REQUEST METHOD is POST
*
* 3. If the user is not trying to login then do not require any files. Think about optimization and load speed!
*    Why load a bunch of files when the user SHOULD be on another file?
*/

if($_SERVER['REQUEST_METHOD'] == 'POST') {
   
   // Get the database connection
   require_once ("database.php");
   
   // Set the variables
   $table = 'smf_2members';
   $hash = 'secretsalt';
   
   // Check if the variable exist AND clean them. You never know...
   // I used the shorthand method. ( $var = (condition) ? true : false; )
   //
   // Refer to this: https://davidwalsh.name/php-ternary-examples
   //
   // Example...
   // if($x == 5) $foo = "bar";
   // else $foo = "car";
   //
   // Can be written as:
   // $foo = ($x == 5) ? "bar" : "car";
   
   $task = (isset($_POST['task'])) ? mysqli_real_escape_string($connection, $_POST['task']) : false;
   $member_name = (isset($_POST['user'])) ? mysqli_real_escape_string($connection, $_POST['user']) : false;
   $passwd = (isset($_POST['user'])) ? mysqli_real_escape_string($connection, $_POST['pass']) : false;
   
   // One of these are not set which means someone was trying to hack you! I guess?
   // Normally you will display an error message.
   if(!$task || !$member_name || !$passwrd){
      header("location: task.html");   
      die();
   }
   
   // Check if the task if login. Best to use a switch case then based on the value run a function..
   // But we are not using OOP so you will have to handle that when there are multiple "tasks"
   if($task == 'login') {
      
      // Check if the user exist! Only select one row.
      // This is a basic example BUT you will ideally use PDO and a prepared statement
      
        // YOUR ISSUE IS HERE!
        // YOU MUST ESCAPE YOUR PHP VARIABLES OR ELSE YOU WILL GET AN ERROR.
        //
        // Let's say $member_name is set to "Cyimking"
        //
        // Your SQL look like this: SELECT * FROM $table WHERE name='cyimking'
        // See the problem?
        // Your SQL should look like this: SELECT * FROM smf_2members WHERE name='cyimking'
        // You are NOT escaping the table variable THUS you are trying to select * from the "$table" table.
        // '$table' is not a valid table thus your query will be false. Hence the error:
        // "mysql_num_rows() expects parameter 1 to be resource boolean given, line 32 which is $result = mysql_num_rows($query1);"
       
      $query = "SELECT COUNT(*) FROM {$table} WHERE name='{$member_name}' ";
      
      if(!$result = mysqli_query($connection, $query)) {
         printf("Error: %s\n", mysqli_error($link));
         die();
      }
      
      $num_rows = mysqli_num_rows($result);
         
      // Never tell someone what's wrong with it. Think like a hacker!
      if($num_rows != 1) {
         echo "Invalid username + password credentials";
         
         // Free the result set
         mysqli_free_result($result);
         
         die();
      }
      
      // Okay so we have a valid account, let's check the passwords!
      // Let's get the whole row as an associative array.
      // Refer to here - http://php.net/manual/en/mysqli-result.fetch-array.php
      $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
      
      // Free the result set!
      mysqli_free_result($result);
      
      $passwordHashed = substr(sha1($hash.$password), 0, 40);
      
      // Compare the hashed password with the one in the database
      // In the real world, you will use a salt. Google some best practices for password hashing / storing
      // Some may even store passwords on different databases.
      
      // Check if the passwords match
      if($passwordHashed != $row['passwd']) {
         echo "Invalid username + password credentials";         
         die();
      }
      
      // Check if the account is activated
      // For checking if the account is disabled, add a new column to your table!
      else {
         
         // In PHP, the value of 1 is the same as TRUE while the value of 0 is false.
         // So... let's keep this short!
         
         // Check if the account is disabled!
         // If the column is 1 then it is disabled! Duh?
         if($row['disabled']) {
            echo "Your account has been disabled!";         
            die();
         }
         
         $message = ($row['is_activated']) ? "successful" : "Account is not activated!";
         echo $message;
         die();
      }
      
   }
   
   else {
      header("location: task.html");   
      die();
   }
   
   
}

else {
   header("location: task.html");   
   die(); // Must kill the application after a redirect to avoid the program from trying to continue the script!
}




4. That is just an example. I hope it helps! Oh the error was your first query. You didn't escape your variables so your query was coming back false which is why you got the error :-)



References
[ Register or Signin to view external links. ]
[ Register or Signin to view external links. ]
[ Register or Signin to view external links. ]
Jump to:
You are viewing our Forum Archives. To view or take place in current topics click here.