Search code examples
phpmysqlpdoreusability

PDO How to make a reusable code structure for return/echo commands?


I'm new for PDO so I would be glad if you help. For example I have this table:

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

I use PDO to fetch text like this:

$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...

It's hard to write 3 blocks of code for each word. Is there any way that I can do it easier? For example:

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

OUTPUT: Hello. Welcome to my website.

Is there a structure for that kind of usage?


Solution

  • Thanks for your answers. Writing a function solved it.

    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");