PHP / MYSQL疑难解答我看不出什么错

时间:2013-07-26 16:00:38

标签: php mysql variables

这是我试验PHP我是新手。我正在尝试查看是否已在mysql数据库中找到给定的用户名,这是我当前的代码:

<?php
// $uname is the username I am trying to see if is the database
$uname = "djm";
//server info
$servuser = "root";
$servpass = "";
$db = "toob";
$server = "127.0.0.1";
//connecting to server
$db_handle = mysql_connect($server, $servuser, $servpass);
$db_found = mysql_select_db("toob", $db_handle);

//checking to see if ocnnected
if ($db_found) {
    print("connected");

//defining my sql statement
    $sql = "SELECT username FROM users WHERE username = $uname";
    $result = mysql_query($sql);


    if ($result) {
        print("Yes");
    } else {
        print("No");
    }
} else {
    print("Can't connect to server");
}

我总是打印不,我已经设法通过替换来打印是:

$sql="SELECT username FROM users WHERE username = $uname";
    $result=mysql_query($sql);

$sql="SELECT username FROM users WHERE username = 'djm'";
$result=mysql_query($sql);

但是我需要处理变量。

3 个答案:

答案 0 :(得分:4)

你错过了引号:

在将输入作为mysql查询传递之前转义输入是个好主意。 尝试:

$sql = "SELECT username FROM users 
WHERE username = '". mysql_real_escape_string($uname)."'";

目前,如果查询成功执行,它会说“是”。如果您要检查记录是否存在,请将if ($result)替换为if(mysql_num_rows($result) > 0)

不相关:mysql_*函数现已弃用,我建议您切换为mysqliPDO

答案 1 :(得分:1)

首先,您应该转义所有用户输入:

$username = mysql_real_escape_string($uname);

然后您需要将SQL值包装在引号中:

$sql="SELECT username FROM users WHERE username = '$username'";

离你的问题有点远;从php's website引用的mysql上的内容:“自PHP 5.5.0起,该扩展已弃用,不建议用于编写新代码,因为将来会删除它。”

最好使用mysqli

答案 2 :(得分:-1)

替换此

 if ($result) 

 if(mysql_num_rows($result) > 0)