koz koz - 5 months ago 23
PHP Question

Mysql_num_rows expects parameter 1 to be mysqli_result when only letters typed into input text field

Really weirdly... whenever I type only letters in the html 'username' text input field for log in, it comes up with the error: "mysqli_num_rows() expects parameter 1 to be mysqli_result..." , even if the username exists. But it works fine when I type only numbers in. Anyone had this really odd error...thnx

Here is my php file...

<?php

//start a session
//unset session variables, expire session cookie, destroy session
//start a new session
session_start();
$_SESSION = array();
setcookie('PHPSESSID', '', time() + 1);
session_destroy();
session_start();

//require template_functions.php file
//call function that renders layout with content file: home.php
require $_SERVER['DOCUMENT_ROOT'] .
'/practice2/resources/library/template_functions.php';
layout('/practice2/public_html/php/home.php');

//if 'login' btn clicked
if (isset($_POST['login'])) {

//assign variable to user's typed username
$name = mysqli_real_escape_string($link, $_POST['name']);

//assign variable to user's typed pw
$pw = mysqli_real_escape_string($link, $_POST['pw']);

//if user typed name
if ($name){

//number of matches to user's name
$result = mysqli_num_rows(
mysqli_query($link, 'SELECT * FROM user WHERE name = ' .$name));
echo $result;

//if name doesn't match
if ($result == 0) {

echo 'The username that you\'ve entered doesn\'t match any account.';

//if name matches
} else if ($result == 1) {

//if user typed pw
if ($pw) {

//number of matches to user's pw
$result = mysqli_num_rows(
mysqli_query($link, 'SELECT * FROM user WHERE pw =' .$pw));

//if pw doesn't match
if ($result == 0) {

echo 'The password that you\'ve entered is incorrect. Forgetten password?';

//if pw match
} else

//assign session variables
//$_SESSION['loggedin'] = true;
//$_SESSION['name'] = $name;
echo 'signed in';

} else echo '<br> Log in as ' .$name. '. Not you?';
}

}


}

?>


here is my html file that performs the action on the php file...

html>

<body>
<form action = '/practice2/public_html/php/index.php' method = 'POST'>
<input type = 'text' placeholder = 'Username' name = 'name'>
<input type = 'password' placeholder = 'Password' name = 'pw'>
<input type = 'submit' value = 'Log In' name = 'login'>
</form>
</body>

</html>

Answer

SQL will let you search numbers without quotes around them, but not text.

SELECT * FROM user WHERE name = 1234 is fine.

SELECT * FROM user WHERE name = fred is not.

If you surround your searched parameters with quotes, you should be better off.

i.e. mysqli_query($link, 'SELECT * FROM user WHERE name = "' . $name . '"'));

Please be aware that whilst you are escaping your parameters to prevent SQL injection using mysqli_real_escape_string(), I recommend also taking a look at a tutorial to Prepared Statements in PHP