PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?php
session_start();
if (isset($_POST['userid']) && isset($_POST['password'])) {
// User sent log in through form
// Connection to database:
@$db = mysqli_connect('localhost', 'authenticator', 'passAthenticator', 'authentication'); // authenticator with pass='passAuthenticator' has been granted select privilege on DB 'authentication'. It's not a real user, but just an automatic registrator.
// Connection error?:
if (mysqli_connect_errno()) {
// Error trying to acess database
echo 'There was an error trying to access database. Please try later.<br />';
exit;
}
// Short names for form superglobal vars:
$userid = $_POST['userid'];
$password = $_POST['password'];
// Query:
$myQuery = "select * from authorized_users where name=".$userid." and password=".$password;
$result = mysqli_query($db, $myQuery);
$num_results = mysqli_num_rows($result); // THIS LINE PRODUCES THE ERROR
// Did we get any record containing valid userid and password?
if ($num_results > 0) {
// We got one.
// Creating session var:
$_SESSION['valid_user'] = $userid;
}
// Finish database connection:
mysqli_free_result($result); // THIS LINE PRODUCES ERROR 'CAUSE USES VAR $result TOO
mysqli_close($db);
}
?>
// Query:
$myQuery = "select * from authorized_users where name=".$userid." and password=".$password;
if($result = mysqli_query($db, $myQuery))
$num_results = mysqli_num_rows($result); // THIS LINE PRODUCES THE ERROR
else
echo 'error!!';
However, may you please explain the use of mysqli_real_escape_string()?
, and why must I use simple quotes (or single quotes, what you call them) with $userid and $password inside the query string? If I'm not wrong '$password' in PHP is interpreted as a string itself, and "$password" (with double quotes) is interpreted as a variable containing a value.
I'm a little confused about this all. It would be great if you told me the explanation of this paradoxical use of single quotes.
$userid = "mike";
$password = "test";
$myQuery = "select * from authorized_users where name=".$userid." and password=".$password;
This results in the string: select * from authorized_users where name=mike and password=test
The problem is that you need to use quotes around the values of a string type..
-> select * from authorized_users where name='mike' and password='test'