简体   繁体   English

如何正确使用PDO对象进行参数化SELECT查询

[英]How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this. 我已经尝试按照PHP.net的说明进行SELECT查询,但我不确定这样做的最佳方法。

I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. 我想使用参数化的SELECT查询,如果可能的话,在name字段与参数匹配的表中返回ID This should return one ID because it will be unique. 这应返回一个ID因为它将是唯一的。

I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not. 然后我想将该ID用于INSERT到另一个表中,因此我需要确定它是否成功。

I also read that you can prepare the queries for reuse but I wasn't sure how this helps. 我还读到您可以准备查询以供重用,但我不确定这有何帮助。

You select data like this: 您选择这样的数据:

$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator

You insert in the same way: 您以相同的方式插入:

$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));

I recommend that you configure PDO to throw exceptions upon error. 我建议您将PDO配置为在出错时抛出异常。 You would then get a PDOException if any of the queries fail - No need to check explicitly. 如果任何查询失败,您将获得PDOException - 无需显式检查。 To turn on exceptions, call this just after you've created the $db object: 要打开异常,请在创建$db对象后立即调用它:

$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well. 我最近一直在和PDO合作,上面的答案是完全正确的,但我只想记录以下内容。

$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();

You can use the bindParam or bindValue methods to help prepare your statement. 您可以使用bindParambindValue方法来帮助准备语句。 It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); 它使事情更清晰,而不是做$check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables. 特别是如果你绑定多个值/变量。

Check the clear, easy to read example below: 查看下面清晰易读的示例:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row_id = $check['id'];
    // do something
}

If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll : 如果您期望多行删除LIMIT 1并将fetch方法更改为fetchAll

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetchAll(PDO::FETCH_ASSOC);
    //$check will now hold an array of returned rows. 
    //let's say we need the second result, i.e. index of 1
    $row_id = $check[1]['id']; 
    // do something
}

A litle bit complete answer is here with all ready for use: 这里有一个完整的答案,随时可以使用:

    $sql = "SELECT `username` FROM `users` WHERE `id` = :id";
    $q = $dbh->prepare($sql);
    $q->execute(array(':id' => "4"));
    $done= $q->fetch();

 echo $done[0];

Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch(); 这里$dbh是PDO db connecter,基于来自表users id ,我们使用fetch(); username fetch();

I hope this help someone, Enjoy! 我希望这有助于某人,享受!

Method 1:USE PDO query method 方法1:USE PDO查询方法

$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

Getting Row Count 获取行数

$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';

Method 2: Statements With Parameters 方法2:带参数的语句

$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Method 3:Bind parameters 方法3:绑定参数

$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Want to know more look at this link 想了解更多关于此链接的信息

if you are using inline coding in single page and not using oops than go with this full example, it will sure help 如果你在单页中使用内联编码而不使用oops而不是使用这个完整的例子,它肯定会有所帮助

//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw); 

//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";

//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);

//view the entire array (for testing)
print_r($result);

//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM