S
S
Sasha Misnik2015-04-19 15:54:19
PHP
Sasha Misnik, 2015-04-19 15:54:19

The script is not working correctly, what am I doing wrong?

There is 1 record in the database, but it displays 7 identical ones.

<?php
  $query = mysqli_query($db,'SELECT * FROM news');
  $res = mysqli_fetch_assoc($query);	
  
  foreach($res as $result){
     echo "<div class='content-header'>";
      echo"<p> <span class='category'>Категория:<span>Гроверство</span></span>---><span class='post'>{$res['title']}</span> </p>";
        echo"</div>";
          echo"<div class='content-content'>";
              echo"<ul>";
                echo"<li>Аффтар:{$res['author']}</li>";
                echo"<li>Дата:{$res['date']}</li>";
                echo"<li>Просмотры:{$res['views']}</li>";
                echo"<li>Комментариев:13</li>";
              echo"</ul>";
            echo"<img src='images/poster.jpg' alt=''>";
              echo"<p>{$res['text']}</p>";
              echo"<div class='details'>";
                echo"<a href='#'>Читать подробнее...</a>";
              echo"</div>";
            
          echo"</div>";

  }
  ?>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kwolfy, 2015-04-19
@Razorvin

Listen to the advice from above, and to make it clear what your problem is

$query = mysqli_query($db,'SELECT * FROM news');  

  while($result = mysqli_fetch_assoc($query)){
     echo "<div class='content-header'>";
     ...
  }

F
FanatPHP, 2015-04-19
@FanatPHP

You have two problems
1. You use mysqli, but you should use PDO
2. The main problem is that you don't read the description of the function in the documentation. For this, in good places they beat the fingers with a ruler. That is, here you are inventing the purpose of a function for yourself, cramming it into your code, and then wondering why nothing works! Well, it's natural that it doesn't work - and it shouldn't.
In general, as you want, the fetchAll () function works in PDO. Therefore, you quickly switch to PDO. How to connect is written here , and you rewrite the code like this:

$data = $db->query('SELECT * FROM news');
foreach($data as $res){

A
Alexander Talalaev, 2015-04-19
@neuotq

1. Inside foreach, as it were, you need to use result, because it walks through the array, or add a key, which then can be used already in res.
2. What is res? Where does the data come from, what is the query to the database
/ In general, it’s better to tell us what task and data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question