【问题标题】:PDO How to make a reusable code structure for return/echo commands?PDO 如何为返回/回显命令创建可重用的代码结构?
【发布时间】:2022-01-09 20:01:46
【问题描述】:

我是 PDO 的新人,所以如果你能提供帮助,我会很高兴。例如我有这张表:

| id   | text                |
| ---- | --------------      |
| 1    | Hello.              |
| 2    | Welcome to my       |
| 3    | website.            |

我使用 PDO 来获取这样的文本:

$query = $db->prepare("select * from texts where id = :id");

$query->execute([ 'id' => 1 ]);
$fetchquery = $query ->fetch(PDO::FETCH_ASSOC);
echo $fetchquery['text'];

$query->execute([ 'id' => 2 ]);
$fetchquery = $query ->fetch(PDO::FETCH_ASSOC);
echo $fetchquery['text'];

OUTPUT: Hello. Welcome to my...

很难为每个单词编写 3 段代码。有什么方法可以让我更容易做到吗?例如:

echo $fetchquery['1']; (only id)
echo $fetchquery['2'];
echo $fetchquery['3'];

OUTPUT: Hello. Welcome to my website.

有这种用法的结构吗?

【问题讨论】:

  • 为什么不能自己创建一个函数...比如echo fetchTextbyId(1);
  • 或者一开始就不要通过ID来限制选择,而是选择all它们 - 并将它们放入一个数组中,使用ID作为键,这样之后您可以直接通过它访问它们。
  • 只需选择所有行并遍历$query
  • 您知道足够多的 PHP 可以从数据库中提取数据,但您不知何故不了解函数?唔。 php.net/manual/en/functions.arguments.php

标签: php mysql pdo reusability


【解决方案1】:

感谢您的回答。写个函数就解决了。

function fetch($input) {
   global $db;
   $query = $db->prepare("select id,text from texts where id = :id");
   $query->execute([ 'id' => $input ]);
   $fetchquery= $query->fetch(PDO::FETCH_ASSOC);
   return $fetchquery['text']; 
}

echo fetch("1");

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    相关资源
    最近更新 更多