Avatar of hidrau
hidrau
Flag for Brazil asked on

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
PHPWeb Development

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
hidrau

ASKER
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
hidrau

ASKER
line 39 I have this:       $conn = new mysqli($servername, $username, $password, $dbname);
Julian Hansen

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

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
hidrau

ASKER
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

hidrau

ASKER
I figured out the error,

I made this change:

$row = $rs->fetch_object();

and not

$row = $cnx->fetch_object();
hidrau

ASKER
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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
hidrau

ASKER
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

Ray Paseur

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.
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
hidrau

ASKER
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
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Ray Paseur

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!
SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
hidrau

ASKER
WOW,

this doesn't work

work $row("SENHA")

and it works fine

work $row->SENHA

:)
Ray Paseur

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!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
hidrau

ASKER
Thanks very much  for all your helps.
I learnt a lot with all of you.
Julian Hansen

$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?