Solved

Help to run a simple query in PHP

Posted on 2016-10-17
17
39 Views
Last Modified: 2016-10-17
Hello,

after almost two hours trying to understand where is the error, I am getting sick with the code and I hope someone here can help me.

I need to make a simple query and return the value, to check if user and password is ok. But my function only returns -1

I checked the table, fields, connections and all is ok. Where is the error:

this is my function

function login_sistema($uso, $senha){
	
    global $servername, $username, $password, $dbnome;
	
	// Create connection
	$conn = new mysqli($servername, $username, $password, $dbname);
	// Check connection
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	} 
		
	$sql = " SELECT * FROM CADUSO ";
	$sql = $sql . " WHERE NOME='" .$uso . "'";
		  
    $rs= $conn->query($sql);  
	

    if ($rs->num_rows > 0) {	
		if ($row("senha")==$senha){
			$id = 1;
		} else {
			$id = -2;
		}		 		
	} else {   
		$id = -1;		
	}		
   
    $conn->close();
    return $id;		
}	 

Open in new window


Thanks a lot
Alex
0
Comment
Question by:hidrau
  • 9
  • 5
  • 3
17 Comments
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 41847011
Please add error_reporting(E_ALL) to the top of the script.
At line 15:
$rs= $conn->query($sql); 

Open in new window

Please use var_dump($rs) and show us what is in the variable, thanks.

Detailed examples showing how to run MySQLi queries with error visualization are available in this article:
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
1
 
LVL 1

Author Comment

by:hidrau
ID: 41847044
Notice: Undefined variable: dbname in /home/storage/4/7e/b1/teachmenow1/public_html/funcoesDB.php on line 39
bool(false)
Notice: Trying to get property of non-object in /home/storage/4/7e/b1/teachmenow1/public_html/funcoesDB.php on line 52
0
 
LVL 1

Author Comment

by:hidrau
ID: 41847050
line 39 I have this:       $conn = new mysqli($servername, $username, $password, $dbname);
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41847052
global $servername, $username, $password, $dbnome;

Open in new window

Use of globals is not considered good programming practice. You are also not dumping error information when your query fails.

Try this reworked version of your code. It is provided as an illustration. Post back if you have questions
// Define your access parameters
$servername = 'localhost';
$username   = 'username';
$password   = 'password';
$database   = 'database';

// Inject the connection into the function
// rather than using global variables to
// create a new connection in the function

function login_sistema($uso, $senha, $conn)
{
  // NB: THIS IS NOT A SECURE WAY OF DOING THIS
  $query = <<< QUERY
    SELET * FROM CADUSO WHERE `NOME`='{$uso}'
QUERY;
      
    $rs= $conn->query($sql);  
  // The above retuns false on failure
  // no need to check number of rows
  
  // Assume we are not going to be authenticated
  $id = false;
  if ($rs) {
    // NB: Not secure - lookup password hashing and salting 
    // as well as santizing input and escaping input sent in a query
    
    // You need to fetch a row before you can use it
    $row = $conn->fetch_object();
    
    // Assuming you want the user id - assuming it is called 'id'
    // change as required
    $id = $row->id;
  }
  
    return $id;    
}   

// Create the connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 

// Change to whatever you are using to get these values
$uso = 'username';
$senah = 'userpassword';

if (login_istema($uso, $senha, $conn)) {
  echo "Welcome";
}
else {
  echo "You can't come in";
}

Open in new window

0
 
LVL 1

Author Comment

by:hidrau
ID: 41847106
Hello Julian Hansen,

I made the change and why I am getting this error:

object(mysqli_result)#2 (0) { }
Fatal error: Call to undefined method mysqli::fetch_object() in /home/storage/4/7e/b1/teachmenow1/public_html/funcoesDB.php on line 45

my function

function login_sistema($uso, $senha, $cnx){
	
	$sql = " SELECT * FROM CADUSO ";
	$sql = $sql . " WHERE NOME='" .$uso . "'";

	$rs= $cnx->query($sql);  
   
	var_dump($rs);
	
    if ($rs) {
		$row = $cnx->fetch_object();
	   
		if ($row->senha==$senha){
			$id = 1;
		} else {
			$id = -2;
		}		 		
	} else {   
		$id = -1;		
	}		  
    
    return $id;		
}	 

Open in new window

0
 
LVL 1

Author Comment

by:hidrau
ID: 41847116
I figured out the error,

I made this change:

$row = $rs->fetch_object();

and not

$row = $cnx->fetch_object();
0
 
LVL 1

Author Comment

by:hidrau
ID: 41847120
now, my problem is another. I am getting angry LOL

object(mysqli_result)#2 (0) { }
Fatal error: Function name must be a string in /home/storage/4/7e/b1/teachmenow1/public_html/funcoesDB.php on line 46

this line it complains:
alerta($row("senha"));

the field in my table is varchar and not int or whatever
0
 
LVL 1

Author Comment

by:hidrau
ID: 41847121
As far as I understood, it doens't matter each field :(


function login_sistema($uso, $senha, $cnx){
	
	$sql = " SELECT CADUSO_ID, NOME, SENHA FROM CADUSO ";
	$sql = $sql . " WHERE NOME='" .$uso . "'";

	$rs= $cnx->query($sql);  
   
	var_dump($rs);
	
    if ($rs) {
		$row = $rs->fetch_object();
		echo $row("nome");
	    echo $row("senha");
		if ($row("senha")==$senha){
			$id = $row("CADUSO_ID");
		} else {
			$id = -2;
		}		 		
	} else {   
		$id = -1;		
	}		  
    
    return $id;		
}	 

Open in new window

0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41847125
Please show us the function definition for alerta() -- this should be defined locally, since it's not a part of native PHP.

Check the spelling and the values: $dbname vs $dbnome and make sure you're using good values in these variables.

And please read the article so you can find the code examples showing how to check for errors and visualize the errors, if any, in your SQL function calls.

Please learn about var_dump() so you can use it on each and every variable that you're not 100% sure of.  It can be used on anything, and I often find myself using it many times in the same script, until I am sure that my code is generating sensible values from every  function call.

For example, you might want to use var_dump($row) to print out the selected columns.  You may find that the query column names are case-sensitive.
1
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 41847129
There were a few typos in my code - I did not test.

Firstly - in your orignal code you had this
global $servername, $username, $password, $dbnome;
$conn = new mysqli($servername, $username, $password, $dbname);

Open in new window

Note $dbnome vs $dbname

In my code there some errors
$cnx->fetch_object() won't exist because fetch_object is a method on the result object $rs in the above code

The errors have been fixed and the code below has been tested
<?php
$servername = 'localhost';
$username   = 'username';
$password   = 'password';
$dbnome   = 'ee';

// Inject the connection into the function
// rather than using global variables to
// create a new connection in the function

function login_sistema($uso, $senha, $cnx)
{
  // ESCAPE any strings sent in a SQL query
  $escuso = $cnx->real_escape_string($uso);
  $escsenha = $cnx->real_escape_string($senha);
  
  // PASSWORD stored in plain text not advisable
  // Encrypt and salted passwords prevent hackers
  // stealing and accessing your user accounts
  $sql = <<< QUERY
    SELECT * FROM CADUSO WHERE `NOME`='{$escuso}' AND senha = '{$escsenha}'
QUERY;
      
    $rs= $cnx->query($sql);  
  // The above retuns false on failure
  // no need to check number of rows
  
  // Assume we are not going to be authenticated
  $id = false;
  if ($rs) {
    // NB: Not secure - lookup password hashing and salting 
    // as well as santizing input and escaping input sent in a query
    
    // You need to fetch a row before you can use it
    $row = $rs->fetch_object();
    
    // Assuming you want the user id - assuming it is called 'id'
    // change as required
    $id = $row->id;
  }
  else {
	  echo "Error: " . $cnx->error . "<br/>";
  }
  
  return $id;    
}   

// Create the connection
$cnx = new mysqli($servername, $username, $password, $dbnome);
// Check connection
if ($cnx->connect_error) {
  die("Connection failed: " . $cnx->connect_error);
} 

// Change to whatever you are using to get these values
$uso = 'fred';
$senha = 'password';

if (login_sistema($uso, $senha, $cnx)) {
  echo "Welcome";
}
else {
  echo "You can't come in";
}

Open in new window


Note the change in the query that checks for NOMA and senha equality in the same query rather than testing the senha value after the query completes. This is a more efficient way of doing this - but note - this method of accessing a security database is still not safe. You should be storing passwords as encrypted and salted strings - not in plain text
1
 
LVL 1

Author Comment

by:hidrau
ID: 41847138
Ray,

I did this in my function

	var_dump($row);
	echo $row("NOME");
       echo $row("SENHA");

Open in new window


and I got this:

object(mysqli_result)#2 (0) { } object(stdClass)#3 (3) { ["CADUSO_ID"]=> string(1) "1" ["NOME"]=> string(4) "ALEX" ["SENHA"]=> string(3) "123" }
Fatal error: Function name must be a string in /home/storage/4/7e/b1/teachmenow1/public_html/funcoesDB.php on line 47

You can try here, use: ALEX  and PSW: 123
http://www.teachmenow.com.br/administrativo/adm.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41847142
storing passwords as encrypted and salted strings
That is true, and worth pursuing later, but for now it would be good just to get the query to work and return some data, or at least tell us what is wrong in the query!
1
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 41847144
OK, looks like $row is an object.  Try using the object notation like this to see if you can access the properties of the object:
echo $row->NOME;
echo $row->SENHA;

Open in new window

1
 
LVL 1

Author Comment

by:hidrau
ID: 41847147
WOW,

this doesn't work

work $row("SENHA")

and it works fine

work $row->SENHA

:)
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41847157
Yep - it's the object notation, and in PHP that's different from the array notation.  I actually like the object notation better - fewer fiddly punctuation marks, easier string substitution, less chance to make errors.  The more you use it, the better you will like it, too!
1
 
LVL 1

Author Closing Comment

by:hidrau
ID: 41847159
Thanks very much  for all your helps.
I learnt a lot with all of you.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41847161
$row = $rs->fetch_object();

Open in new window


$row is an object - which you access with the ->\
hence $row->SENHA

Even if it was not an object ($rs = $cnx->fetch_array) you would still not access it with ( ) but [ ] brackets.

What you are saying with $row("SENHA") is to call the function name that is stored in $row and pass it the string "SENHA" - which obviously is incorrect in this context.

Still not sure why you are doing the SENHA comparison in code and not in the query?
1

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now