Help to run a simple query in PHP

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
LVL 1
hidrauAsked:
Who is Participating?
 
Julian HansenConnect With a Mentor Commented:
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
 
Ray PaseurConnect With a Mentor Commented:
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
 
hidrauAuthor Commented:
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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
hidrauAuthor Commented:
line 39 I have this:       $conn = new mysqli($servername, $username, $password, $dbname);
0
 
Julian HansenCommented:
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
 
hidrauAuthor Commented:
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
 
hidrauAuthor Commented:
I figured out the error,

I made this change:

$row = $rs->fetch_object();

and not

$row = $cnx->fetch_object();
0
 
hidrauAuthor Commented:
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
 
hidrauAuthor Commented:
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
 
Ray PaseurCommented:
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
 
hidrauAuthor Commented:
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
 
Ray PaseurCommented:
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
 
Ray PaseurConnect With a Mentor Commented:
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
 
hidrauAuthor Commented:
WOW,

this doesn't work

work $row("SENHA")

and it works fine

work $row->SENHA

:)
0
 
Ray PaseurCommented:
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
 
hidrauAuthor Commented:
Thanks very much  for all your helps.
I learnt a lot with all of you.
0
 
Julian HansenCommented:
$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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.