使用 PHP 从 MySQL 数据库中获取价值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3047506/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get value from MySQL database with PHP
提问by Hristo
$from = $_POST['from'];
$to = $_POST['to'];
$message = $_POST['message'];
$query  = "SELECT * FROM Users WHERE `user_name` = '$from' LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $fromID = $row['user_id'];
} 
I'm trying to have $formID be the user_id for a user in my database. Each row in the Users table is like:
我试图让 $formID 成为我数据库中用户的 user_id 。用户表中的每一行都类似于:
user_id | user_name | user_type
   1    |  Hristo   |   Agent
So I want $from = 1but the above code isn't working. Any ideas why?
所以我想要,$from = 1但上面的代码不起作用。任何想法为什么?
回答by Sarfraz
Try this:
尝试这个:
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
$query  = "SELECT * FROM Users WHERE user_name = '$from' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
    $fromID = $row['user_id'];
}
Also, make sure that:
另外,请确保:
- You have connected to the database
- You do get data from the post, try var_dumpwith your vars egvar_dump($from)
- 您已连接到数据库
- 您确实从帖子中获取数据,请尝试var_dump使用您的变量,例如var_dump($from)
回答by CrossProduct
Use mysql_fetch_assoc instead
使用 mysql_fetch_assoc 代替
回答by Babiker
while($row =mysql_fetch_assoc($result)){ $fromID = $row['user_id'];
}
while($row =mysql_fetch_assoc($result)){ $fromID = $row['user_id'];
}
回答by Your Common Sense
though it should. try this code
虽然应该。试试这个代码
$from    = mysql_real_escape_string($_POST['from']);
$to      = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
$query  = "SELECT * FROM Users WHERE `user_name` = '$from' LIMIT 1";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$fromID = $row['user_id'];
echo $fromID;
if it will throw no errors but still print no id, add this line
如果它不会抛出任何错误但仍然没有打印 id,请添加这一行
var_dump($row);
and post here it's output
并在这里发布它的输出
not that you shouldn't use a user name but user id to address particular user.
并不是说您不应该使用用户名而是使用用户 ID 来称呼特定用户。

