<?php session_start();
include ('connection.php');?>
<?php
$username='pablorex192';
$consulta=mysql_query("SELECT question FROM users WHERE user = $username") or die ('This is the error: '.mysql_error());
echo $consulta
?>
这是错误:“where 子句”中的未知列“pablorex192”
它给了我那个错误,我真的不知道为什么,这里是我的数据库的一些屏幕截图。 http://puu.sh/iMFy3/d23d9b0942.png http://puu.sh/iMFyQ/8343a4876c.png
最佳答案
首先,不应再使用 mysql_*() 函数。它们已被弃用,并将很快被删除。请改用 MySQLi 或 PDO。
其次,我怀疑您是从输入表单中获取用户名,这意味着您无法控制那里写入的内容。这意味着简单地将它连接到查询中会使您打开 SQL 注入(inject),这不好。 使用准备好的语句,或者至少为数据库使用适当的转义函数。
第三,也是我的一个小毛病:如果您将粘贴的行粘贴到同一个文件中,则不应在它们之间退出 PHP 模式。
将以上所有内容结合起来,我们得到了以下代码:
// Start the session and SQL connection, assuming PDO.
session_start ();
include ("connection.php");
// Check for posted content here. If none, show the input form and exit.
if (!submitted ()) {
return;
}
// Validate that we actually have something that could be a username.
if (!ctype_alnum ($_POST['username'])) {
// Input contained illegal characters, add error to output.
return;
}
// Create the prepared statement to fetch the (security?) question from the database.
$stmt = $DB->prepare ("SELECT question FROM users WHERE user = ?");
if (!$stmt->exec (array ($_POST['username']))) {
// Failed, add error to output.
return;
}
// Now we've got the question.
$question = $stmt->fetch()[0];
您还会注意到我删除了“echo mysql_error()”,因为这是不应该向用户显示的内容。它允许潜在的攻击者了解有关您系统的大量有用信息。
PS:您还会注意到,通过使用准备好的语句,您不必费力地引用字符串。数据库驱动程序会为你做这件事。 ;)
关于mysql - 帮助 PHP 代码,从数据库中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31239961/