H
H
hello world2015-10-24 18:53:56
PHP
hello world, 2015-10-24 18:53:56

How to output data from pdo function?

Good evening. I started to study pdo and I'm interested in the following question:
I created a function.php file and I want to prescribe functions in it, and then display it on request.
I also have an index.php file, where the actual layout is located. I do not want to write anything extra from php into this layout, but I need to display a list of all students. Tell me how to do it right?
The following code is written in function.php

function get_student_list() {
  $stmt = $pdo->query('SELECT studentFROM kafedra');
  $stmt->execute();
  foreach ($stmt as $row)
  {
      echo $row['name'] . "\n";
  }  
  
}

And the following layout is written in index.php (we display a list of checkboxes for selection):
<div class="checkbox">
  <input type="checkbox" id="c1" name="cc" />
  <label for="c1">
    <span class="filter_name">Петров</span>
  </label>
</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dk-web, 2015-10-24
@hello

I will not load you with frameworks, mvc, etc. - there are more experienced specialists here ...
But in short it is not entirely true ...
After execute, you need to do the following:
If you want to iterate, then it's done like this:

while ($row=$stmt->fetch()) {
   $students[$row['id']]=$row;
}

the main thing at the end of the function write the return of values ​​- return $students;
I would make three files:
<?php
include('function.php');
$students=get_student_list();
include('form_element.php');
<div class="checkbox">
 <?php foreach ($students as $id => $student): ?>
<input type="checkbox" id="student_<?php echo $id;?>" value="<?php echo $id; ?>" name="students[]" />
  <label for="student_<?php echo $id; ?>">
    <span class="filter_name"><?php echo $student['surname']; ?></span>
  </label>
<?php endforeach; ?>
</div>

and the third one is your functions...
just don't forget to return
Something like this.... but this is just the beginning)

M
Max, 2015-10-24
@MaxDukov

return an array from the function - and in index.php already go through it with foreach, forming a list with checkboxes. Although IMHO the function is contrived here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question