使用PDO搜索表单

时间:2013-07-16 10:39:02

标签: php search pdo

以下代码现在有效,但如果找不到任何结果,我怎么能这样做呢?它回复了一条消息而不是空白。

我想我已经成功为我的数据库创建了一个搜索查询。它只是一个非常基本的搜索,但似乎由于某种原因不起作用。任何建议都会受到赞赏,我仍然是pdo的新手(很新!真好!)。

也没有用户提交的数据被插入数据库所以我想我可以排除xss假设它的SQL注入免费?根据我的理解PDO是什么?加上我使用一个没有写访问权限的独立数据库用户。

用xxx替换数据以确保安全性

文件名为search.php

*已更新以反映建议的更改 *第二次更新以反映所提供的帮助 *第3次更新

   <html>
<head>
</head>
<body>
<form name="frmSearch" method="post" action="search.php">
  <table width="599" border="1">
    <tr>
      <th>Keyword
      <input name="var1" type="text" id="var1">
      <input type="submit" value="Search"></th>
    </tr>
  </table>
</form>
<?php
$nameofdb = 'xxxxxx';
$dbusername = 'xxxxxxxxxxxxxx';
$dbpassword = 'xxxxxxxxxxxxx';



// Connect to MySQL via PDO
try {
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

$var1 = str_replace(array('%','_'),'',$_POST['var1']);
if (!$var1)
{
    exit('Invalid form value: '.$var1);
}


$query = "SELECT * FROM xxxxx WHERE xxxxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");


 $result = $stmt->fetchAll();

foreach( $result as $row ) {
    echo $row["id"];
    echo $row["title"];
}




?>

</body>
</html>

3 个答案:

答案 0 :(得分:4)

问题在于表格。方法是GET但是在你的php中你期望$_POST

所以这一行:

<form name="frmSearch" method="get" action="search.php">

应该是:

<form name="frmSearch" method="post" action="search.php">

<强>更新

改变这个:

// Connect to MySQL via PDO
try {
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

$var1 = $_POST['var1'];


$query = "SELECT * FROM xxxxx WHERE xxxx LIKE ? OR xxxxx LIKE ?";
$params = array("%$var1%");
$stmt = $handle->prepare($query);
$stmt->execute($params);

到此:

// Connect to MySQL via PDO
try {
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

$var1 = $_POST['var1'];


$query = "SELECT * FROM xxxxx WHERE xxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();

更新2

我只是看到您使用$handle进行连接,但您定义了$dbh。我想如果您将$handle更改为$dbh,则可以使用

更新3

更改此行:

$result = $sth->fetchAll();

到此:

$result = $stmt->fetchAll();

更新4

要检查是否没有行并发送消息,您可以这样做:

if ($stmt->rowCount() > 0) { 
$result = $stmt->fetchAll();

foreach( $result as $row ) {
echo $row["id"];
echo $row["title"];
}
} else {
echo 'There is nothing to show';
}

答案 1 :(得分:-1)

我写了这个方法,并在我工作的每个项目中使用。试试吧:))

public function searchForQueryString($queryString)
{
    $query = "SELECT * FROM `xxxx` WHERE (`xxxxxxx` like :queryString or `xxxxx` like :queryString) ";

    $sth = $this->prepare($query);
    $queryString = '%' . $queryString . '%';
    $sth->bindParam('queryString', $queryString, PDO::PARAM_STR);

    $sth->execute();

    $result = $sth->fetchAll(PDO::FETCH_OBJ);

    if(empty($result) or $result == false)
       return array();
    else
        return $result;
}

答案 2 :(得分:-1)

我修改了Amir的代码,并且可以正常工作:

protected $pdo;

public function __construct($pdo)
{
    $this->pdo = $pdo;
}

public function selectSearch($table, $search)

{
    $statement = $this->pdo->prepare("select * from {$table} WHERE post_tags LIKE '%$search%'");

    $statement->execute();

    $result = $statement->fetchAll();

    if(empty($result) or $result == false){
        echo "<h1> No Result</h1>";
        return array();
    } else{
        return $result;
  }}


if(isset($_POST['submit'])){
            $search = $_POST['search'];

            $data = $query->selectSearch('posts', $search);
        }