How to handle query results with PHP OO?

Question:

I'm creating a simple, photography website, and I'm doing all the object-oriented PHP. I'm familiar with PHP procedurally, but I'd like to mix PHP with HTML as little as possible. My connection and my query are running perfectly, however I would like to know how to handle the query result in the best possible way.

My function for the query:

function consultarDados($query){
    $conexao = mysql_connect($this->host, $this->usuario, $this->senha);
    mysql_select_db($this->banco, $conexao);
    $rs = mysql_query($query, $conexao);
    return $rs;
    mysql_close($conexao);
}

And how I'm treating it on the index.php page:

include 'connectDB.php';
$conexao = new connectDb();
$retorno = $conexao->consultarDados('select * from slides');
    if(mysql_num_rows($retorno) > 0){
        while($row = mysql_fetch_assoc($retorno)){
            echo $row ['imagem'];//esta parte eu fiz apenas para verificar se os resultados da query estão sendo obtidos de maneira correta.
        }
    }

I need to insert the query result in the name of the images in this piece of HTML:

<img src="img/slide_1.jpg"  class="img-slide ativa">
<img src="img/slide_2.jpg"  class="img-slide">
<img src="img/slide_3.jpg"  class="img-slide">

Thanks !

Answer:

Simple form

while($row = mysql_fetch_assoc($retorno)){
            echo '<img src="img/'.$row ['imagem'].'"  class="img-slide">';
        }

Using Template in this case Dwoo

you create a dwoo template

<html>
  <head></head>
  <body>
   {loop $items}
     <img src="img/{escape($item)}"  class="img-slide">
   {/loop}
  </body>
</html>

and creates the php script that will create the array and pass it to the template:

<?php
include 'dwooAutoload.php';

try {
  $dwoo = new Dwoo();

  $tpl = new Dwoo_Template_File('tmpl/list.tpl');

  $data = new Dwoo_Data();
  $items = array();
  $items[] = array('item' => 'slide_1');
  $items[] = array('item' => 'slide_2');
  $items[] = array('item' => 'slide_3');
  $items[] = array('item' => 'slide_4');
  $data->assign('items', $items);

  // injeta os valores e exibe a pagina, note que o nome do indices são identicos as 
//variaveis dentro do template, o dwoo irá fazer a injeção paseado nos nomes identicos.
  $dwoo->output($tpl, $data);
} catch (Exception $e) {
  echo "Error: " . $e->getMessage();      
}
?>

Dwoo download link : http://dwoo.org/

Link to Dwoo in- depth tutorial: In- depth tutorial

Scroll to Top