How to handle query results with PHP OO?

Asked

Viewed 212 times

3

I’m creating a simple, photographic website, and I’m doing all the object-oriented PHP. I know PHP procedural, but I would like to mix PHP with HTML as little as possible. My connection and my query are running perfectly, but 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 into the image names of 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">

Thank you !

1 answer

1


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 template dwoo

<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 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();      
}
?>

Link to download from Dwoo: http://dwoo.org/

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

  • Thanks for the help !

  • @anuseranother Dispo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.