简体   繁体   中英

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: http://i.stack.imgur.com/0PUPG.jpg

Any suggestions about what's going wrong ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM