Carrousel in php and mysql

Asked

Viewed 3,255 times

5

I have an "upload of files" and I needed to show them on a Carousel. The image path is stored in the database and the images in a folder, of course. I have the following code:

<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
    <li data-target="#myCarousel" data-slide-to="2"></li>
    <li data-target="#myCarousel" data-slide-to="3"></li>
  </ol>

  <!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">

  <?php
  $con = mysqli_connect("localhost","root","","saber");
  mysqli_set_charset($con,"utf-8");
  $result = mysqli_query($con,"select * from banners");
  while($row = mysqli_fetch_array($result)){
    $img = $row['imagem'];
    echo "<div class='item active'>
      <img src='php/$img'>
    </div>";
    }
    ?>
  </div>

  <!-- Left and right controls -->
  <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

And when I go to test the images appear one below the other. And I can’t see what the error is!

I went to get the code for the crash here and Carousel should be as shown in the example of the link I mentioned above, but it is like this:

inserir a descrição da imagem aqui

I really need to get this done today and since I’ve never worked with Carousel in php and database. So I’ll put the whole page code.

And at Ricardo’s request here remains the html rendered

PS: I didn’t do this so I may not be able to answer all the questions they have.

  • What plugin generates this carrosel, post a page print like this and how it should be

  • @I’ve already edited and I think I’ve shown you everything you asked for

  • 1

    (off-topic) think it is not necessary to use the code display snippet in case of your question because when we run we do not see the actual result

  • Copy the rendered HTML code from the browser and paste it here

  • @As soon as rendered?

  • Managed to make @Brunogibellino ?

  • The html that appears in the browser

  • @I’ve already edited the question and added the rendered HTML

Show 3 more comments

5 answers

10

For the information available on source from where you extracted the Carousel, by parsing the code, the CSS class with the name active should only be present in a single element, the one you intend to have active when loading the page.

Then the Plug-in tries to change the class to the next element and so "create" the Carousel.

Your code prepared to handle a single active element, and an indicator for each image exist, also taking into account the absence of images and/or the presence of only one image would look as follows:

<?php

// Estabelecer ligação à base de dados
$con = mysqli_connect("localhost","root","","saber");

// Definir encoding
mysqli_set_charset($con,"utf-8");

// Recolher resultados
$result = mysqli_query($con,"select * from banners");

/* Por cada resultado, preparar a saída
 */
$imagesHtml = '';

$indicatorDotsHtml = '';

$i = 0;

while($row = mysqli_fetch_array($result)) {

    $filename = $row['imagem'];

    // classe "active" apenas no primeiro elemento
    $active = $i==0 ? 'active' : '';

    // criar HTML para a imagem
    $imagesHtml.= '
    <div class="item '.$active.'">
        <img src="php/'.$filename.'" alt="'.$filename.'" />
    </div>';

    // criar HTML para o indicador da imagem
    $indicatorDotsHtml.= '
    <li data-target="#myCarousel" data-slide-to="'.$i.'" class="'.$active.'"></li>';
    
    $i++;
}


/* Preparar a saída para o navegador
 */
if (!empty($imagesHtml)) {

    /* Verificar se precisamos de navegação
     */
    $navHtml = '';

    if ($i>1) {

        $indicatorsHtml = '
        <ol class="carousel-indicators">
            '.$indicatorDotsHtml.'
        </ol>';

        $navHtml = '
        <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>';
    }

    /* Enviar saída para o navegador
     */
    echo '
    <div id="myCarousel" class="carousel slide" data-ride="carousel">

        <!-- Indicators -->
        '.$indicatorsHtml.'

        <!-- Wrapper for slides -->
        <div class="carousel-inner" role="listbox">
            '.$imagesHtml.'
        </div>

        <!-- Left and right controls -->
        '.$navHtml.'

    </div>';
}
?>

Note:
It is always useful to consult the official documentation of the Plug-In for a better understanding of how it works and what options we have:

Bootstrap - Carousel

4

The subject is the subclass 'active' in the images. active can only be for an image (in this case it is the first image). In the first while iteration, div will have subclass active, the following Divs will only be created with class item. With this code here, it works correctly:

<?php 
$con = mysqli_connect("localhost","root","","saber");
mysqli_set_charset($con,"utf-8");
$result = mysqli_query($con,"select * from banners");
$subclass = 'active';
while($row = mysqli_fetch_array($result)){
$img = $row['imagem'];
echo "<div class='item $subclass'>
  <img src='php/$img'>
</div>";
$subclass='';
}
?>
  • That’s what I suggested in my reply. I used $counter++ to regulate this question, when it is the first one, it will be active :D

  • very good idea

3

<?php
$con = mysqli_connect("localhost","root","","saber");
mysqli_set_charset($con,"utf-8");
$result = mysqli_query($con,"select * from banners");
$classe = 'active';
while($row = mysqli_fetch_array($result)){
$img = $row['imagem'];
echo "<div class='item" . $classe.">".
"<img src='php/$img'>
</div>";
$classe = '';
}
?>

*Remember to add the libraries:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

*I simulated the code and it worked, uploaded the code to Dropbox for you to see the effect: Link

  • Now the images do not appear

  • @Brunogibellino Testa now

  • what’s the one in echo for?

  • @Brunogibellino I removed

  • It still doesn’t show. What is interfering?

  • @Brunogibellino you tested my answer? I made a test with images from the internet and it worked perfectly

  • @Brunogibellino you added the libraries?

  • No, Ricardo, I don’t have any libraries. And the images you placed were searched from the database?

  • @Brunogibellino you should add the three library links I posted in my reply (1 tag link and 2 script) between the head tags of the document, as well as in my test file I posted in my reply.

  • @Brunogibellino tested the example I uploaded to Dropbox?

  • @Brunogibellino let’s continue on chat: http://chat.stackexchange.com/rooms/25919/discussion-between-bruno-gibellino-and-ricardo

Show 6 more comments

2

Try this way:

$conexao = mysqli_connect("localhost","root","","saber");
mysqli_set_charset($conexao,"utf-8");
$result = mysqli_query($conexao,"select * from banners");

$contador = 0;
while($row=mysqli_fetch_array($result){

    $contador++;
    if($contador==0) $classe = ""; else $classe = "active";
    $img = "php/".$row['imagem'];

    echo "<div class='item {$classe}'>";
    echo "<img src='{$img}'>";
    echo "<div>";

}

Note the contact form of the variables {$var}.

Don’t forget to check if the CSS is up and running... jQuery can also interfere, the good thing is you put the whole code, including the top with jquery and css requests.

  • I couldn’t do it I don’t know why now the images appear on top of each other and does not Carousel effect

  • Have you checked that CSS and Jquery are being imported correctly? What link do I see your code working?

  • But the class is set to Active, for everyone. within while, and for this reason, they are all active and make no transition. I modified the code, try it this way.

  • @Brunogibellino Don’t forget that you need to import CSS and jQuery to work properly.

  • The error may be in both CSS and javascript (some conflict maybe). When you open the Chrome console you see some kind of error?

1


Well, this answer is for those who want to make a carousel but do not know how many and which images they will put, or in other words to make a carousel with images from the database.

I will explain in as much detail as possible. Because I also don’t know much about carousel.

First for the images to rotate, make appear an indication of how many images are (in my case are some balls) and for a arrows to appear, one to the left, one to the right, that change the image, we need some plugins:

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

You can see more details about this and everything I’m going to explain here.

Then for those balls mentioned above we need a list, but as we do not know how many images are we make a counter:

<ol class="carousel-indicators">
<?php 
    $con = mysqli_connect("localhost","root","","saber");
    mysqli_set_charset($con,"utf-8");
    $result = mysqli_query($con,"select * from banners");

    $ac = 0;
    $active = 'active';
    while($row = mysqli_fetch_array($result)){
        echo "<li data-target='#myCarousel' data-slide-to='$ac' class='$active'></li>";
        $ac++;
        $active = '';
    }
?>
</ol>

Now for the images, we decide which image appears first used class = "active" and the plugins above deal with running the images. However, we are using a carousel that we don’t even know what the images are, so, as on the site I have a form that inserts the path of the images in the database and stores the images in the file just go search them. And for that we use:

<?php
    $con = mysqli_connect("localhost","root","","saber");
    mysqli_set_charset($con,"utf-8");
    $result = mysqli_query($con,"select * from banners");

    $active = 'active';
    while($row = mysqli_fetch_array($result)){
        $img = $row['imagem'];
        echo "<div class='item $active'>
        <img src='php/$img' alt='Saber' width='460' height='345'>
      </div>";
      $active = '';
  }
?>

As said the active only serves to tell which image goes first so we create a variable to save "active" outside the while and inside it we put the empty variable.

Finally it remains only to define the arrows I spoke earlier for that we use:

<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
  <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
  <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
  <span class="sr-only">Next</span>
</a>

these classes come from the plugins just call them to make the arrows work.

And at the end to search, show and run the images from the database the code must be thus.

Thank you!

Browser other questions tagged

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