SQL注入证明SELECT与LIKE和通配符到关联数组


SQL injection proof SELECT with LIKE and wildcard into associative array

计划创建一个面向公众的互联网服务,可以自动完成数据库中的单词。我使用常规的mysql查询成功地工作了,但我很担心,因为我将把这个连接包含在wordpress插件中,这会使我的服务器容易受到攻击。

我在MYSQL中创建了一个新用户,在这个表上只有选择权限,所以我不担心在脚本中泄露密码,因为我相信这无论如何都有助于调试。有各种各样的回声等,我放在那里调试的目的。最终,它的输出将进入Json文件,并由Jquery UI自动完成检索。

从本质上讲,我遇到的问题是无法使查询工作。我试着逐行添加代码,但连接不起作用。请随意在mysql工作台上测试凭据,IP地址为46.101.8.220。更难调试的是,当从web浏览器查看时,代码中有人阻止任何内容出现在页面输出上。任何帮助都将不胜感激,因为我已经花了很多时间尝试Mysqli、PDO、面向对象和过程化,试图让它发挥作用。

$term = isset($_GET['term']) ? $_GET['term'] . '%': 'test%';
echo $term;
$conn = new mysqli('localhost', 'search-words','','admin_soup');
print ($conn ? 'connected' : 'cant con');
$query = 'SELECT id as value, word as label FROM word where word LIKE ?;';
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $term)
    if ($stmt->execute()){
        $result = $stmt->get_result();
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            $row_set[] = $row;
        }
    }
echo json_encode($row_set);//format the array into json data
$stmt->close();
$conn->close();
print_r($row_set);

在第一次建议代码更改为并工作后。谢谢

$term = isset($_GET['term']) ? $_GET['term'] . '%': 'test%';
echo $term;
$conn = new mysqli('localhost', 'search-words','','admin_soup');
print ($conn ? 'connected' : 'cant con');
$query = 'SELECT id as value, word as label FROM word where word LIKE ?;';
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $term);
    if ($stmt->execute()){
        $stmt->bind_result($value,$label);
        while($row = $stmt->fetch()){
            $row_set[] = array('value'=>$value, 'label'=>$label);
        }
    }
echo json_encode($row_set);//format the array into json data
$stmt->close();
$conn->close();

代码仍然没有返回任何内容。仔细检查了用户信息。当我测试sql语句时,我唯一需要改变的是,我需要在"test%"周围添加quoinations,但我认为bind_param不需要引号。如果我从$query下窗格中删除所有代码,如果我再次在下面添加,它将在屏幕上显示连接的消息。屏幕上什么也没显示。

我的服务器上可能有什么需要更新的东西吗?

$stmt->bind_param("s", $term)

缺少";"

$result = $stmt->get_result();

get_result()方法并不总是可用的。查看php.net:http://php.net/manual/en/mysqli-stmt.get-result.php

仅适用于mysqlnd。

这就是pdo如此方便的原因之一。。。

但我想您可以使用bind_result(),然后使用fetch(),如示例中所示的数据http://php.net/manual/en/mysqli-stmt.fetch.php

if ($stmt->execute()){
    $stmt->bind_result($value, $label);
    while($row = $stmt->fetch()){
        $row_set[] = array('value' => $value, 'label' => $label);
    }
}

通过使用PDO,代码可以如下所示:

$stmt = $dbh->prepare('SELECT id as value, word as label FROM word where word LIKE ?');
$stmt->execute(array($term));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);