I'm a beginner in php & mysql. The num_rows
is not working in the below basic example.
The whole script is inspired by the example in w3schools.
w3schools example.
the browser shows an error message as follows.
Notice: Trying to get property of non-object in C:\wamp\www\test3\index.php on line 17
<?php
require 'connect.inc.php';
require 'core.inc.php';
//check username & password is set.
if(isset($_POST['username']) && isset($_POST['psw']))
{
$username = $_POST['username'];
$password = $_POST['psw'];
$pass_md5 = md5($password);
if(!empty($username) && !empty($password))
{
$queryy = "SELECT ID FROM user WHERE email= $username AND password= $pass_md5";
$result = $conn->query($queryy);
echo $result->num_rows; //<---------------NOT WORKING..! -----<<
}
else echo "incorrect username-password combination";
}
?>
<html>
<form action="<?php echo $current_file ?>" method="POST">
User name: <input type="text" name="username">
password: <input type="password" name="psw">
<input type="submit" value="Login"><br>
</form>
<html>
where connect.inc.php
has some simple codes to connect to localhost and database. it's as follows:
<?php
//this sript connects to DB->mytest.
$servername="localhost";
$username="root";
$password="";
$dbname="mytest";
//create connection
@$conn=new mysqli($servername, $username, $password, $dbname);
//check connection
if($conn->connect_error)
{
die("connection faild");
}
?>
and, core.inc.php
is returns the current file location. it's as follows:
<?php
$current_file = $_SERVER['SCRIPT_NAME'];
?>
please help..
The problem is that you're not quoting the strings in your query:
$queryy = "SELECT ID FROM user WHERE email= '$username' AND password= '$pass_md5'";
However, it would be best to use a prepared query and bind_param
instead of substituting variables.
$queryy = "SELECT ID FROM user where email = ? AND password = ?";
$stmt = $conn->prepare($queryy);
$stmt->bind_param("ss", $username, $pass_md5);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;