【发布时间】:2016-02-25 20:12:00
【问题描述】:
我的选择查询有点问题。如果我输入一串数字 (int) 并且具有该“用户名”的用户存在,我会得到一个名为 $resultw 的结果。但是,如果我在表单中输入一个带有字母(varchar)的字符串,并且用户在我的数据库中有这个用户名,它就不起作用,我也没有收到任何(错误)消息。那会发生什么?
我的 php:
if(isset($_POST["submit"])){
$hostname='localhost';
$user='root';
$password='';
$uinput = $_POST['username'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=game",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT id, email, username
FROM user
WHERE username = $uinput"; //
if ($resi = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$resultw = $resi->fetchAll();
}
if($resultw >= 0) {
//do something
}
else {
echo "The user you are searching for does not exist.\nPlease check your input.";
}
}
catch(PDOException $e) {
//
}
}
不知道是否需要,但 这就是我的表格:
<form style="width:100%" data-ajax="false" action="./username.php" method="post">
<div style="width:100%" class="ui-grid-a">
<div style="width:75%;padding-left:5%" class="ui-block-a">
<div>
<input data-inline="true" type="text" name="username" id="username"/></div></div>
<div style="width:20%" class="ui-block-b"><div>
<input data-inline="true" type="submit" name="submit" value="Go" class="ui-btn"/>
</div></div>
</div>
</form>
我的 foreach 循环:
<?php foreach ($resultw as $keyres => $rowres): ?>
<li>
<a href="ime.php"><?php echo $rowres['username']; ?></a>
</li>
<?php endforeach; ?>
【问题讨论】:
-
您很容易受到sql injection attacks 的攻击,并且您的查询中的
$uinput周围没有引号,这意味着您有语法错误。但是,您应该会遇到错误,因为您已启用异常。您的错误是username=123和username=foo之间的区别。一个是字段到整数的比较,另一个是字段到字段的比较,您几乎可以肯定没有名为foo的字段。