2016-08-01 64 views
-1

计划是创建一个面向公众的互联网服务,可以从数据库中自动填充单词。我使用普通的mysql查询成功地工作,但我担心,因为我将把这个连接包含到一个wordpress插件中,这会使我的服务器容易受到攻击。SQL注入证明SELECT和LIKE以及通配符到关联数组中

我在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%'添加quoations,但是我认为bind_param不需要引号。如果我从$查询downwars中删除所有的代码,它会在屏幕上显示连接的消息,如果我再次添加下面。屏幕上什么都没显示。

有没有可能需要更新我的服务器或东西?

回答

0
$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); 
+0

我试过mysqli解决方案,stilll没什么,我用一些新的想法更新了这个问题。我开始怀疑这是否与代码无关。 –

+0

@StephenMclaughlin'$ row_set [] = array('value'=> $ value,'label'=> $ label)'Missing;再次。 – Philipp

+0

看不到树林:'( –