-1

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?

  • Why can't you create a function of your own... like `echo fetchTextbyId(1);` – Salman A Dec 03 '21 at 12:48
  • 3
    Or don't limit the selection by ID in the first place, but select _all_ of them - and put them into an array, using the ID as key, so that you can access them via that directly afterwards. – CBroe Dec 03 '21 at 12:48
  • Just select all rows and iterate over `$query` – Dharman Dec 03 '21 at 12:52
  • You know enough PHP to pull data from a DB, but you somehow don't know about functions? Hmm. https://www.php.net/manual/en/functions.arguments.php – B. Shea Dec 03 '21 at 13:17

1 Answers1

0

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