Thursday, 30 August 2018

Simple PHP connection does not connect to the database

Below is the code for a member to login and connect to database. I have set up the database, the database owner user and password, the database "members" table, and a database member user. The first bit of code is just the html form to log in [it is the index file], the second is the PHP file [checklogin.php] that is supposed to connect said user to the database. The problem is that whatever is typed into html form will let the user to the next page saying "hey, user, you are signed in" even if that user is not in the members table. I have a feeling they are not REALLY connecting at all, it's just echoing that out. - All db info is keyed out with ++++++

    <html>
    <form action='checklogin.php' method='POST'
    <strong>username:</strong><br />
    <input name="myusername" type="text" id="myusername"><br />
    <strong>password:</strong><br />
    <input name="mypassword" type="password" id="mypassword"><br />
    <input type="submit" name="Submit" value="Login">
    </form>
    </html> 

    <?php
    $host="localhost";
    $username="++++++";
    $password="++++++";
    $db_name="++++++";
    $tbl_name="members"; 

    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");
    $myusername=$_POST['myusername'];
    $mypassword=$_POST['mypassword'];
    echo "hey, " . $myusername . ", you are correctly signed in."
    ?>

Thank you. I am going to add elements of security after I get this going. It is going to eventually log the user in and have have them go right to their profile.

mysql_connect() returns a connection resource that you need to pass to a call to mysql_query(), along with a SQL query to determine if the credentials match a user in the database.
$con = mysql_connect($server, $dbuser, $dbpass);
mysql_select_db($db_name)

Your query needs to check the DB to see if $myusername exists, and that the password for $myusername equals $mypassword. You mentioned the table name was members.
$user = mysql_query("select password from members where username = '" .
    mysql_real_escape_string($_POST['myusername']) . "'", $con);

if(mysql_num_rows($user) == 0) {
    // Username not found
}

$user = mysql_fetch_assoc($user);
if($_POST['password'] != $user['password']) {
    // Password does not match
}

The actual query depends on the schema of your database.

0 comments:

Post a Comment