我正在尝试选择并回显单个字段。
这是我尝试时的代码
session_start();
$query = "select id from user where username = ".$_SESSION['username'];
$result = mysql_query($query);
$admin_id = mysql_fetch_array($result);
echo $admin_id['id'];
当我运行该代码时,会出现此警告文本
mysql_fetch_array() expects parameter 1 to be resource, boolean given in ......
我该怎么做?
答案 0 :(得分:1)
在sql查询中分配值时应使用引号。
$query = "select id from user where username = '{$_SESSION['username']}'";
或者
$query = "select id from user where username = '" . $_SESSION['username'] . "'";
但是,这不是一个好习惯,所以你最好提前准备一些语句来减少sql注入漏洞:http://ru2.php.net/pdo.prepared-statements
答案 1 :(得分:0)
试试这个:
$username = $_SESSION['username'];
$query = "select id from user where username = '$username'";