For loop retrieves same mysql row - php

I’m trying to retrieve the first 4 entries with a for loop, but it seems to repeat 1 entry 4 times.
This is my code:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten");
while($row = mysqli_fetch_array($result)) {
for ($result = 1; $result <= 4; $result++) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
}
mysqli_close($con);

You don't need a for loop. I've modified code, to retrive only first 4 items.
Look at the cahnged query LIMIT 4.
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
?>

You have a for loop inside the while loop. You can remove the for loop and use LIMIT from MySQL (which is better as fetching all entries by PHP (better performance), if you need only the first 4 entries):
SELECT * FROM activiteiten LIMIT 4
If you still want to do it with php:
$results = 0;
while($row = mysqli_fetch_array($result) && $results < 4) {
echo "<div class='agenda_item' style='background-color:#F39'>";
...
$results++;
}

Your code—as presented—mixes things up in ways that behave the way you see. The for loop is not needed. And you should set a LIMIT in your MySQL query like this:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 0,4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
The problem with your original code is mixing for with while ends up in the scenario you showed as explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.
So you have a while iterating over the results, but then you also have for loop nested in there. 100% unnecessary.
The way I adjusted it is to just removed that for loop, but also add LIMIT 0,4 to the MySQL query. That basically tells MySQL to fetch 4 rows beginning from the first row which is referred to as 0.

Related

How to fix comment section in PHP and MySQL?

The problem is I think in function viewNews(), so I made that function to get the articles/news from database. Well, I tried to put function showCommentsArea() inside viewNews() function, but it shows me same comments in every article, I want like separated comments for every article, like on Facebook, I mean, when you enter someone's post (in this case article), you can publish a comment only for that post (article).
I tried putting showCommentsArea() function inside viewNews() function, right after displaying timestamp of that article.
# Function for viewing news. #
function viewNews()
{
global $db;
$query = "SELECT * FROM newsmodule ORDER BY timestamp";
$result = #mysqli_query($db, $query);
if (!$result)
{
echo "Error selecting headline from database.";
exit();
}
if (mysqli_num_rows($result) > 0)
{
echo "<div style='margin-left: 0; width: 100%;' class='jumbotron'>";
while ($row = mysqli_fetch_object($result))
{
echo "<h1><br>" . $row->headline . "</h1>";
echo "<hr>";
echo "<p>" . $row->storyline . "</p>";
echo "<hr>";
echo "<h5 class='pull-right'>" . $row->username . "</h5>";
echo "<p>" . $row->timestamp . "</p>";
echo "<hr>";
echo showCommentArea();
echo "<a data-target='#postComment' class='text-white dropdown-toggle btn btn-danger' data-toggle='modal' type='button'>";
echo "Publish a Comment";
echo "</a>";
}
echo "</div>";
}
else
{
echo "No headlines in database.";
}
}
function showCommentArea()
{
global $db, $errors, $username;
if(count($errors) == 0)
{
$query = "SELECT comment, name FROM comments
JOIN newsmodule ON comments.articlecID=newsmodule.id WHERE newsmodule.id=comments.articlecID";
$result = #mysqli_query($db, $query);
if(!$result)
{
echo "SQL Query ERROR: !ERR_SQL_QUERY_01";
exit();
}
if (mysqli_num_rows($result) > 0) {
echo "<div>";
echo "<h4>";
echo "Comments:";
echo "</h4>";
echo "<br>";
while ($row = mysqli_fetch_object($result)) {
echo "<p class='text-danger' style='font-weight: bold;'>" . $row->name . "</p>";
echo "<p>" . $row->comment . "</p>";
}
echo "</div>";
}
}
}
So, I expect to have one individual comments section for one individual post, you see I tried to add it with JOINING tables, but it shows me entire table 'comments'

Dynamic sort by header in PHP

I'm trying to create a dynamic header on Name which gives the user the ability to sort by ASC or DESC, the results is from the 'register'-table in MySQL. I have tried a couple of codings, but it hasn't given the correct result as of now. Hope anyone is able to help me :)
I have tried making another variable, but I couldn't manage to create the correct one.
<?php
$sql = "SELECT * FROM register";
if($sqlData = mysqli_query($db, $sql)) {
if(mysqli_num_rows($sqlData) > 0) {
echo "<table border ='1' bgcolor='#FFF' width='100%'>";
echo "<tr>";
echo "<th><a href='overview.php?order=name'>Name</a></th>";
echo "<th>Score</th>";
echo "</tr>";
while($row = mysqli_fetch_array($sqlData)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($sqlData);
} else{
echo "No results in DB";
}
} else{
echo "Error couldn't connect $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
Hm, that's not a good idea to sort table using MySQL each time user clicked on the table's header.
I suggest you to use javascript for it. Example

Panel List Php not showing all data

I am trying to create a panel list that shows certain rows from my database, however when I'm trying to call it, it only shows 1 data in the row even though i limit it by 5.
Here is my script:
<?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM updates order by id desc limit 5";
if($result = mysqli_query($link, $sql)){
if($list=mysqli_fetch_array($result)){
echo "<div class=\"container\">";
echo "<table>";
echo "<tr>";
echo "</tr>";
echo "<div class=\"col-md-4\">";
echo "<div class=\"panel panel-primary\">";
echo "<div class=\"panel-heading\">Updates";
echo "</div>";
echo "<ul class=\"list-group\">";
echo "<li class=\"list-group-item\">";
echo "<b><h4>{$list["updates"]}</b></h4>";
echo "</li>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
That's because you are fetching only once, here:
if ($list=mysqli_fetch_array($result) )
Instead wrap this up inside a loop like this:
$row_count = mysqli_num_rows($result);
if ($row_count <= 0) {
echo "No records matching your query were found.";
}
else {
// you have results
// panel starts here
while ($list = mysqli_fetch_array($result)) {
// do some magic with your results
}
// panel ends here
mysqli_free_result($result);
}
I think you got the idea, now you can do the rest. If not let us know again. Happy coding!
You use sql to get five data, but you use mysqli_fetch_array() function only took out a line.
error line 8;

Limiting column for fetched data in php

I am trying to put extracted mysql data into a table using php. The issue is that I am able to put the fetched data into either all rows or all columns. What I would like to do is put the fetched data into a column format and as soon as 4 columns are used, the next data should start on the next row and so on.
Currently I am using the logic below, however I am getting everything in a column.
The goal is to limit the data to a page size so the data can be printed.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
while($row = mysql_fetch_array($result))
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?></div>
If I understand your problem correctly you will want to do something like:
Keep a counter to see which number record you're looking at ($i)
$i = 0; // Your counter
while($row = mysql_fetch_array($result))
{
// ...
On every 4th iteration of the loop output something like </tr><tr>.
if ($i % 4 == 0 && $i > 0) // Will return true if `$i` is a multiple of 4 and greater than 0
{
echo "</tr><tr>"; // Output your HTML to start a new row
}
One final note: As others will be pointing out. You should avoid using the MySQL extension. You should use MySQLi or PDO instead.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
$i = 1;
while($row = mysql_fetch_array($result))
{
if($i == 4)
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
$i=0;
}
$i++;
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?>
</div>

Passing URL from MySql via PHP

I'm trying to work out how to pass a URL that's stored in a MySQL database and attach it to a image.
The script i have so far is this:
<?php
$con = mysqli_connect("**********","*********","******","********");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$selectedOption = $_POST["mySelect"];
$result = mysqli_query($con,
sprintf("SELECT * FROM `SouthYorkshire` WHERE `EstProv` = '%s'",
preg_replace("/[^A-Za-z ]/", '', $selectedOption)
)
); // pattern based on your html select options
echo "<div id=\"Results\">";
while($row = mysqli_fetch_array($result)) {
echo "<div class=\"ClubName\">";
echo $row['EstName'];
echo "</div><br>";
echo "<div class=\"Location\">";
echo $row['EstAddress2'];
echo "</div>";
echo "<br>";
echo "<div id=\"website\"><img src=\"photos/visit-website-button.png\" width=\"75\" height=\"25\" /></div>";
}
echo date("Y") . " " ."Search is Powered by PHP.";
echo "</div>";
mysqli_close($con);
the bit i'm trying to change is :
echo "<div id=\"website\"><img src=\"photos/visit-website-button.png\" width=\"75\" height=\"25\" /></div>"
I tried to use the same above with $row['EstWebsite']
But am not having any success, any suggestions would be great.
Many Thanks
Doesn't matter where the URL comes from, in the end it's just a string of data, and you're just going to be building some HTML with it, so
echo '<div id="website"><img blah blah blah>";
^^^^^^^^^^^^^^^^^^^^^^^-add this ^^^^--add this
You can use the following:
echo "<div id=\"website\"><img src=\"" . $row['ImageColumnName'] ."\" width=\"75\" height=\"25\" /></div>";

Categories