0

我在下面显示的代码中使用 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。有什么想法吗?

4

2 回答 2

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'];
于 2013-10-25T13:21:46.277 回答
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 ;
于 2013-10-25T13:34:06.573 回答