Loop to show all news

Asked

Viewed 100 times

0

I’m trying to make a backoffice for my website so I can publish news! Does anyone know how to loop to show each of the Rows in my database? Thanks to those who help!

Note: I’m new to PHP and Mysql

date_default_timezone_set('Europe/Lisbon');
$date = date("Y-m-d H:i:s");

// Ligação
$conn = mysqli_connect($servername, $username,"",$dbname);


$querypesquisa= "select * from praticar where titulo=titulo and texto=texto 
 and nome=nome";
$querypesquisa_run = mysqli_query($conn,$querypesquisa);
  ?>
 <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <?php
    if(mysqli_num_rows($querypesquisa_run)>0)
    {
        // Loop vai ter a mesma quantidade que o nº de rows // 
          {
        echo '
    <h1>Titulo</h1>
    <div>Conteudo</div>
    <p></p>
    <footer>MOSTRAR AQUI A VARIÁVEL DE DATA</footer><footer>Nome</footer>'
         ; }
}
else
{
 echo 'Não existem noticias';
}

?>
</body>

  • A question.. In your query, I saw that you put name=name, title=title.. But where do these variables come from for the search?

  • These are the names of each column! I think if you run this query it will give all the right results? Then it serves to verify that the number of the same is greater than 0 because if it is not because no news was published and if it is greater than 0 needed now the loop to show each of the news that are published in the backoffice (already done)! Correct me if I’m wrong please

1 answer

0


First, there in your query, you don’t need the name=name, title=title.. For this is only applicable if you want to search for some specific data in the database, example:

$nome = "AlmostDone";
$query = "SELECT * FROM praticar WHERE nome = '$nome' ";

In the above example syntax, you are using WHERE to show you only data that the name equals the $name variable (in which we assign the Almostdone value), so basically the database reads like this:

"SELECT EVERYTHING FROM PRACTICE WHERE NAME IS EQUAL TO Almostdone"

But in your case, do not need to put name=name, just put:

$querypesquisa= "select * from praticar";

Because only this equals your search, it will list everything from your table, UNLESS you select a news equivalent to a category (for example: only list news involving sport), but for this you have one more sea of tasks before, and as you are beginner, advise to read a little more about the use of MYSQL and PHP.

A good channel for this is the Celke, has video didactic lessons that will make you increase your range of knowledge.

But let’s get to your problem, has numerous invalid things in your code, since the loop(which is done with while to fetch database data) and various items out of place (provided ";" out of his position).

I set your code to list news.. I left with because I imagine the user has to click it to open the news.. But if you are beginner, better start more calmly.. Simpler things and don’t involve so much game of variables and ids from one side to the other.

Now, there are several ways to delete a record, I’ll give you an easier one.. But for this you need the bootstrap for this method (I will show one that appears a confirmation modal).

Follow the code below with the delete button, modal and jquery all right for you.. Be careful, that the button is already in operation, register a test news if you want to test its operation:

<?php

date_default_timezone_set('Europe/Lisbon');

$date = date("Y-m-d H:i:s");

// Ligação
$conn = mysqli_connect($servername, $username,"",$dbname);

$querypesquisa= "select * from praticar";

$querypesquisa_run = mysqli_query($conn, $querypesquisa);
  ?>
 <!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
  <h1>Titulo</h1>
    <div>Conteudo</div>

    <?php
    while($row = mysqli_fetch_assoc($querypesquisa_run)){
    ?>
    <p>
      <?php echo $row['id'] ?>-
        <a href="#">
        <?php echo $row['nome'] ?>
        </a>
   </p>
    <footer><?php echo $row['data'] ?></footer>
<button type="button" class="btn btn-sm btn-danger" href="#"
    data-toggle="modal" data-target='#deleta_<?php echo $row['id'] ?>'>
    <i class="fas fa-trash-alt"></i> Apagar</button>

<!-- Modal para deletar o equipamento !-->
        <div class="container">
        <div class="modal fade" id='deleta_<?php echo $row['id'] ?>' role="dialog">
          <div class="modal-dialog modal-md">
            <div class="modal-content">
              <div class="modal-body">
                <p> Você tem certeza que deseja apagar o <?php echo $row['nome'] ?>?</p>
              </div>
              <div class="modal-footer">
                    <a href="teste2.php?id=<?php echo $row['id'] ?>"
                       class="btn btn-danger" id="delete">
                        <i class="fas fa-eraser"></i> Apagar Registro</a>
                    <button type="button" data-dismiss="modal" class="btn btn-primary">
                        <i class="fas fa-times"></i> Cancelar</button>
              </div>
            </div>

          </div>
        </div>
      </div>
  <?php }; ?>

 </body> 

</html>

Now, look at this line:

<a href="teste2.php?id=<?php echo $row['id'] ?>"..

You need to create another file to delete (if you want another name, put it in href by overwriting the teste2.php by another name you want to put on the exclusion page. (from ? onward, don’t erase anything!)

Follows the teste2.php:

<?php
// Ligação
$conn = mysqli_connect($servername, $username,"",$dbname);

$id = $_GET['id'];

$query_volta = "SELECT * FROM praticar";
$query = mysqli_query($conn, $query_volta);
$row_volta = mysqli_fetch_assoc($query);
$id_volta = $row_volta['id'];

  //Cadastro de equipamentos
  $query_deleta = "DELETE FROM praticar WHERE id=$id";
  $resultado_deleta = mysqli_query($conn, $query_deleta);
  $linhas = mysqli_affected_rows();

  if(mysqli_affected_rows() != 0){
    echo "<script type=\"text/javascript\">
            alert(\"Equipamento apagado com sucesso.\")";
    header("Location: index.php");
  }else{
    echo 'Erro ao apagar o registro!';
    header("Location: index.php");
  }
?>
  • Yes Conn is receiving these values I forgot to copy but yes connection to database is correct!

  • I have already tested this is exactly what I intended! Clarifying doubts what does mysqli fetch Assoc?

  • Another thing I have to date to pick up the current time! But I wanted each article to pick up the current time but the one that was published knows how to do it?

  • Already got the date now I want to create in the part of the backoffice something to delete a Row from the database! If it is necessary to delete some news

  • Okay, I’m going to cut first about your question about mysqli_fetch_assoc, basically it’s used with the result of mysqli_query. it creates an array representing the row of data returned from the database. You can read more about him and his "brother" mysqli_fetch_array here: http://php.net/manual/en/function.mysql-fetch-assoc.php

  • On deletion, I will edit the reply to add an delete button next to each news item.. Then you can take this button and put it where you prefer.

  • Friend but the button will be on another page also completes the button!! Now I just need you to send a message when it’s successfully deleted and when I can’t echo into a javascript Alert?

  • I get it. Normal, set an if for when it is deleted successfully, if yes put: Alert ("record deleted successfully"); window.location.href = 'index.php'; And on the if Else, put another Alert saying that it was not possible to delete.

  • Okay thanks so much for the help!!

  • Okay, thank you very much

Show 5 more comments

Browser other questions tagged

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