Ir para conteúdo
Fórum Script Brasil
  • 0

Loop com junção de tabelas


jamiel

Pergunta

<?php 

// Configurações do banco de dados
date_default_timezone_set("America/Recife");
if (!defined('SERVIDOR')) define('SERVIDOR', 'localhost');
if (!defined('USUARIO')) define('USUARIO', 'root');
if (!defined('SENHA')) define('SENHA', '');
if (!defined('BANCO')) define('BANCO', 'agenciawp2');
if (!defined('CHARSET')) define("CHARSET", "utf8");


// Definir URL BASE
define('URL_BASE',  'http://localhost/agenciawp2/');
define('URL_ADMIN', 'http://localhost/agenciawp2/admin/');

        $conexao = @mysqli_connect(SERVIDOR, USUARIO, SENHA, BANCO) or die (mysqli_connect_error());
        mysqli_set_charset($conexao, CHARSET);

?>

 

CREATE TABLE IF NOT EXISTS `categoria` (
  `cat_id` int(11) NOT NULL AUTO_INCREMENT,
  `cat_name` varchar(60) NOT NULL,
  `cat_slug` varchar(60) NOT NULL,
  PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

 

CREATE TABLE IF NOT EXISTS `post` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `post_cat_id` int(11) NOT NULL,
  `post_name` varchar(200) NOT NULL,
  `post_slug` varchar(220) NOT NULL,
  `post_img` varchar(100) NOT NULL,
  `post_text` text NOT NULL,
  `post_views` int(11) NOT NULL,
  `post_data` date NOT NULL,
  `post_author` varchar(200) NOT NULL,
  `post_ativo` int(1) NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

 

 

<div class="table-responsive">
    <table class="table">
        <thead>
          <tr>
            <th width="6%">id</th>
            <th width="30%">Título</th>
            <th width="30%">Categoria</th>            
            <th align="center">Ação</th>
          </tr>
        </thead>
        <?php 
      
           
              $sql = "SELECT * FROM post p, categoria c WHERE p.post_cat_id = c.cat_id ORDER BY post_id DESC ";
              $qry = mysqli_query($conexao, $sql);
              while ($linha = mysqli_fetch_array($qry)) {

        ?>
        <tbody>
          <tr>
            <td align="center"><?php echo $linha["post_id"] ?></td>
            <td align="left"><?php echo $linha["post_name"] ?></td>
             <td align="left"><?php echo $linha["cat_name"] ?></td>
            <td ><a class="btn btn-primary" href="index.php?link=3&id<?php echo $linha["post_id"]?>">Editar</a></td>
            <td ><a class="btn btn-danger" href="index.php?link=3&id<?php echo $linha["post_id"]?>">Deletar</a></td>
          </tr>
        </tbody>    
        <?php } ?>            
    </table>
</div>

 

Neste caso não está aparecendo nada. Já não sei mais o que fazer.

É algo simples. Porém, tá complicado solucionar.

 

===============================================

 

Segundo caso:

 

<?php
    
@$ordem  = isset($_GET["ordem"])  ? $_GET["ordem"]:"0";
@$campo  = isset($_GET["campo"])  ? $_GET["campo"]:"";
@$search = isset($_GET["search"]) ? $_GET["search"]:"";
  
?>


<!-- PESQUISAR -->
<style>
    .my-group .form-control{
    width:50%;
}
</style>
<form action="index.php" method="get" class="">
    <div class="input-group my-group"> 

            <input type="text" class="form-control" name="search" value="<?php //echo $search ?>" placeholder="Digite o nome do post...">
                    <select class="form-control" data-live-search="true" name="campo">
                        <option value="post_name">Postagem</option>
                       
                    </select> 
                    <span class="input-group-btn">
                       <input type="hidden" name="link" value="2"> 
                       <input class="btn btn-default" type="submit" value="Pesquisar" name="Submit">
                    </span>
    </div>                
        
</form>

<h4>Lista de Posts</h4>

<a href="index.php?link=4" class="btn btn-success">CADASTRAR POST</a>
<br><br>
<?php 

      

  

  if ($search =="") {
        $sql = "SELECT * FROM post p, categoria c WHERE p.post_cat_id = c.cat_id ORDER BY post_id DESC "; (se eu tirar essa parte em negrito, exibe tudo menos o cat_name que está na tabela categorias)
  } else {
        $sql = "SELECT * FROM post WHERE $campo LIKE '%$search%' ";
  } 
    
      
  $total = total($sql);

  if($total <= 0) {
     echo "Nenhum Registro Para Exibir";
  } else {
       echo "Há " . $total . " Posts cadastrados"; 
  } 

?>

<br><br>
<div class="table-responsive">
    <table class="table">
        <thead>
          <tr>
            <th width="6%">id</th>
            <th width="30%">Título</th>
            <th width="30%">Categoria</th>            
            <th align="center">Ação</th>
          </tr>
        </thead>
        <?php 
      
           $lpp    = 4; //linhas por páginas
           $inicio = $ordem * $lpp;
           $post   = selecionar($sql . " LIMIT $inicio, $lpp");

           foreach ($post as $posts) {  (linha 78 - CRUD) 
        

        ?>
        <tbody>
          <tr>
            <td align="center"><?php echo $posts["post_id"]; ?></td>
            <td align="left"><?php echo $posts["post_name"]; ?></td>
             <td align="left"><?php echo $posts["cat_name"]; ?></td>
            <td ><a class="btn btn-primary" href="index.php?link=3&id<?php echo $posts["post_id"];?>">Editar</a></td>
            <td ><a class="btn btn-danger" href="index.php?link=3&id<?php echo $posts["post_id"];?>">Deletar</a></td>
          </tr>
        </tbody>    
        <?php } ?>            
    </table>
</div>

 

Erro:

 

) Warning: Invalid argument supplied for foreach() in C:\wamp\www\agenciawp2\admin\lst\lst-post.php on line 78

 

A questão é como envolver a tabela categoria nesse loop. Quero listar os post e a categoria de cada post também.

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...