slk
slk

Reputation: 77

Mysql database does not show query result in php

I am trying to run a beginner mysql program which checks two arguments against stored values in the database. I have one database named 'sl493' on the server, which has a table 'metauser' and 1 row of data. When i try to run the program, i only get "Connected successfully" and no 'login ok'

<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$username = 'fahad';
$password = '2';

   $dbhost = '*********.edu';
   $dbuser = '*******';
   $dbpass = '*******';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
   if(! $conn )
   {
     die('Could not connect: ' . mysql_error());
   }

   echo 'Connected successfully';
   mysql_select_db('sl493',$conn); //pick sl493 database

$result = mysql_query("SELECT * 
        FROM metauser 
        WHERE metauser.username = $username;
        AND metauser.password = $password") ; //select data from metauser table

        $row = mysql_fetch_assoc($result);

        if($row['username'] == $username)
{
    echo 'Login ok';
}
else
{
    'Login failed';
}
?>
</body>
</html>

Here's a snapshot of the database: https://i.sstatic.net/0PUPG.jpg

Any suggestions about what's going wrong ?

Upvotes: 1

Views: 197

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74216

You're not treating strings as they should be and require to be quoted.

You also have a semi-colon at the end of $username in your where clause which needs to be removed.

$result = mysql_query("SELECT * 
        FROM metauser 
        WHERE metauser.username = '$username'
        AND metauser.password = '$password'") ;

More on string literals:


Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.

For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.

  • You should store hashed passwords, instead of literal strings.

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Also add or die(mysql_error()) to mysql_query().

Sidenote: Error reporting should only be done in staging, and never production.

Upvotes: 1

jbiz
jbiz

Reputation: 414

According to php.net:

$query = sprintf("SELECT * FROM metauser 
    WHERE metauser.username='%s' AND metauser.password='%s'",
    mysql_real_escape_string($username),
    mysql_real_escape_string($password));

// Perform Query
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row['username'] == $username)
{
    echo 'Login ok';
}

FYI, that page also says that mysql_query and mysql_fetch_assoc are deprecated.

Upvotes: 0

Related Questions