如何将其转换为使用PDO?

时间:2014-01-20 07:19:30

标签: sql select pdo

我想使用PDO来选择(搜索)数据库。 搜索“表单”具有可以使用的MULTIPLE字段。可以填写1个或多个字段以帮助优化搜索。 (或者可以有许多空白/空白)

这是我一直在使用的(本地):

//localhost details
$db_username="root"; //database user name
$db_password="";//database password
$db_database="test"; //database name
$db_host="localhost";

mysql_connect($db_host,$db_username,$db_password);
@mysql_select_db($db_database) or die("Unable to connect to database.");

if(isset($_POST['submit'])) {  
    // define the list of fields
    $fields = array('first', 'trialdate', 'wcity', 'wstate', 'plantif');
    $conditions = array();

    //loop through the defined fields
    foreach($fields as $field){
        // if the field is set and not empty
        if(isset($_POST[$field]) && $_POST[$field] != '') {
            // create a new condition while escaping the value inputed by the user (SQL Injection)
            $conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'";
        }
    }   
    //build the query
    $query = "SELECT * FROM myTable ";
    // if there are conditions defined
    if(count($conditions) > 0) {
    // append the conditions
        $query .= "WHERE " . implode (' OR ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
    }   
    $result = mysql_query($query);

    if(isset($_POST['submit'])) {
        while($row = mysql_fetch_array($result)) {
            echo $row['first'] . "<br />"; //individual value
            //build panels that displays everything from row..etc
        }
    }
}   

这一直很好......但我想转换为使用PDO方法。

我试了几下......但我在这里遗漏了一些东西..

继承人到目前为止我尝试过的事情......

//localhost details
$db_username="root"; //database user name
$db_password="";//database password
$db_database="test"; //database name
$db_host="localhost";

//PDO DB connection
$conn = new PDO('mysql:host='.$db_host.'dbname='.$db_database.'charset=utf8', $db_username, $db_password);

if(isset($_POST['submit'])) {

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE first LIKE :first OR trialdate LIKE :trialdate OR wcity LIKE :wcity OR wstate LIKE :wstate OR plantif LIKE :plantif');

//build query placeholders (*note: use bindValue for $_POST values) 
    $stmt->bindValue(':first', '%' . $_POST['first'] . '%'); 
    $stmt->bindValue(':trialdate',  '%' . $_POST['trialdate'] . '%');
    $stmt->bindValue(':wcity',  '%' . $_POST['wcity'] . '%');
    $stmt->bindValue(':wstate',  '%' . $_POST['wstate'] . '%');
    $stmt->bindValue(':plantif',  '%' . $_POST['plantif'] . '%');

    $stmt->execute();

    foreach ($stmt as $row) {
        // do something with $row
        echo $row['first'] . "<br />"; //individual value
    }
}

我可以使用帮助来让PDO示例使用显示的结果/行/值吗?

0 个答案:

没有答案