1

I have written a PHP script that I use for authentication with e-mail and password since e-mail is identified as unique.

I want to echo "true" as well as echo :: fname (First Name). how can I write it? Following is my PHP code.

include "db_config.php";

$email = $_POST['email'];
$password = $_POST['password'];

$sql = "select fname,e_mail,password from user where e_mail = '$email' and pwd = '$password'  ";

$result = mysql_query($sql);

if (mysql_num_rows($result) > 0){
    echo "true";
}
else{
    echo "Login Failed";
}

If you can suggest me some better way to write this code, please let me know.

4

3 回答 3

2

Consider the comments about mysql_* and mysql_real_escape_string, but after you get your result, you echo it like this, adapted from the manual:

$result = mysql_query($sql);
if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

$row = mysql_fetch_assoc($result); 
echo "true" . $row['fname'];
于 2012-07-14T17:06:06.507 回答
1
if (mysql_num_rows($result) > 0)
{
    echo mysql_result($result, 0);
}

-- or --

The code from Sankalp's or GDP's answers. (mysql_fetch_array)
mysql_result is not good if you want to display many results, it's good for just a few of them.


BTW, I'd like to point you to some omissions in your code:

  • you should check if every $_POST or $_GET variables are set by using isset or empty.

  • your code is so insecure! You should escape every variable before using it in a query. Use mysql_real_escape_string() for that. I also suggest you to use strip_tags() along with escaping.


Example of checking if variables are set:

Using isset():

if(isset($_POST['email'])) $email = $_POST['email'];
if(isset($_POST['password'])) $password = $_POST['password'];

Using empty():

if(!empty($_POST['email'])) $email = $_POST['email'];
if(!empty($_POST['password'])) $password = $_POST['password'];
于 2012-07-14T17:12:11.900 回答
0
$row = mysql_fetch_array($result, MYSQL_NUM)
echo $row[0];   //fname
echo $row[1];   //email 

or you can use MYSQL_ASSOC to get a named array and access values as

echo $row['fname'];
于 2012-07-14T17:12:54.503 回答