PHP / MySQL where子句返回空值

时间:2013-10-25 13:19:29

标签: php mysql where-clause

我在下面的代码中使用PHP / MySQL的Where子句有一个小问题:

<?php
$con=mysqli_connect("host","username","password","database");
//Note that I have replaced my parametres just for this question
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Request Session ID
$id = $_SESSION['uid'];
echo "Session ID = ' . $id;
echo "<br>";
//Request Username
echo "Username = " . mysqli_query($con,"SELECT username FROM 'users' WHERE id = 4");

?>

此输出是(登录我的单独登录页面后):

会话ID = 4

用户名=

很明显,where子句存在问题。 据我所知,连接参数没有问题。 当我在PHPmyadmin中运行MySQL命令时,我得到'Admin'的预期结果。 我的输入正确命名。

我不知道造成这种情况的原因是什么,我在论坛上找不到任何类似的问题。任何帮助,将不胜感激。感谢。

更新

我已经调整了以下答案来制作此代码:

<?php
// Only run this script if the sendRequest is from my flash application
if ($_POST['sendRequest'] == "parse") {
//conection:
$con=mysqli_connect("mysqlXX.000webhost.com","a4935911_***","***","a4935911_***");
$id = $_SESSION['uid'];
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = $id"));
$uname = $getuname ['username'];

// Print 1 var to flash
print "var1=The username of this user is $uname.";

}

?>

由我的Flash应用程序触发。如果我不使用会话ID变量并且仅使用例如,这可以正常工作4作为我的id值,但我需要使用会话ID。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您不应使用普通单引号(')包围表名称;改为使用反引号(或者,如果你不使用保留字,则不使用反引号)。所以:

SELECT username FROM `users` WHERE id = 4

SELECT username FROM users WHERE id = 4

此外,mysqli_query不会在字段中返回结果,而是返回mysqli_result个对象。您必须使用fetch命令来获取结果,例如

$result = mysqli_query($con,"SELECT username FROM 'users' WHERE id = 4");
$row = mysqli_fetch_assoc($result);
echo 'Username = ' . $row['username'];

答案 1 :(得分:0)

您应该使用以下代码: -

//conection:
$con=mysqli_connect("host","username","password","database");

if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = 4"));
$username = $getuname ['username'];

 //Request Username
 echo "Username = " .$username ;