Code is not displaying first result - php

About this code:
<?php
$result = mysqli_query($connect,"SELECT subcategories.subcat_name, subsubcategories.subsubcat_name FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subsubcategories.subcat_ID = 1");
$subcat_name = mysqli_fetch_array($result);
?>
<div class="grid_5 alpha omega" id="titlescontent"><p class="titlebar"><?php echo $subcat_name['subcat_name'];?></p></div>
<div class="clear"></div>
<div class="grid_5 alpha omega" id="content"><ul class="subcat">
<?php
while ($row=mysqli_fetch_array($result)){
?><li><?php echo $row['subsubcat_name'];?></li><?php
}
?>
</ul></div>
<div class="clear"></div>
For some reason it starts displaying the subsubcat_name from the 2nd result and not the first one which I also want to be displayed. Any idea how come and what I need to change in this code?

Actually, I see you need that first one for the title? In that case, try this alternate approach:
Replace your while loop with:
$row = $subcat_name;
do {
echo "<li>".$row['subsubcat_name']."</li>";
} while($row = mysqli_fetch_array($result));
What does this change? It basically means the loop body will run for your initial row, then for the rest.

you have extra mysqli_fetch_array call

Related

retrieving data from a specific column in php/MySql

I'm using WordPress with XAMPP. I'm trying to fetch the post title from a column called post_title from a table called ltport_posts by using mysqli_fetch_row() function. The connection with the database is working just fine. However, post titles don't seem to be written in the news ticker. Now I know that $row variable is an enumerated array, so we should write the offset number to access the column. It should be noted that the while loop is working since I have four rows in the ltport_posts and four <div>'s are generated (browser's inspect element is showing me that). But the whole tag is empty:
<div class="ticker-wrap">
<div class="ticker">
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
</div>
</div>
Here's the php/HTML code:
<div class="ticker">
<?php $query="SELECT post_title from ltport_posts";
if($result=mysqli_query($conn,$query))
{
while($row=mysqli_fetch_row($result))
{?>
<div class="ticker__item"><?php printf("%s", $row[5]); ?> </div>
<?php }
mysqli_free_result($result);
}
mysqli_close($conn);?>
</div>
mysqli_fetch_row
mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an
enumerated array
Your query is
$query="SELECT post_title from ltport_posts";
You just fetch one column from your query. So you will get only $row[0] .It's indexing start from 0
while($row=mysqli_fetch_row($result))
{?>
<div class="ticker__item"><?php printf("%s", $row[0]); ?> </div>
<?php }
For fetching multiple column
$query = "SELECT column1, column2,column3,column4 FROM City ORDER by ID DESC";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
printf ("%s (%s)\n", $row[0], $row[1],$row[3], $row[4]);
}
}
You can do the following:
// Prepare the query
$stmt = "select column FROM table";
// Execute it...
$result = mysqli_query($stmt);
// Fetch Results
$row = mysqli_fetch_assoc($result);
// Output single column
echo $row['column'];
And of course you can loop it through as well with multiple results. mysqli_fetch_assoc will return an array where the keys are the column names.

How to display 10 records per page and then how to use pagination?

One record
10 records loop
I have trouble with displaying properly records, end after that i need to use pagination.
v_news.php
<div class="news">
<a href="index.php?ogloszenie='<?php $row['id_article']; ?>'">
<div class="newstitle">
<?php echo $row['title'];?>
</div>
<div class="newsauthor">
<?php echo $row['username'];?>
</div>
<div class="newscomment">
comments: 56
</div>
<div class="newsdate">
<?php echo $row['timestamp'];?>
</div>
</a>
</div>
m_news.php
<?php
if(!isset($_SESSION['id'])){
header("Location: index.php");
exit();
}else{
$result = $Database->query("SELECT * FROM article LIMIT 0, 10");
if($result->num_rows != 0){
$rows = $result->fetch_assoc();
foreach ($rows as $row){
include("views/v_news.php");
}
}else{
echo "No results";
}
}
With foreach loop i have an error illegal string offset with $row['']. I don't know what to do with this.
First try to fix your 2nd line of code in v_news.php.
You forgot to use "echo".
<a href="index.php?ogloszenie='<?php $row['id_article']; ?>'">
change to:
<a href="index.php?ogloszenie='<?php echo $row['id_article']; ?>'">
fetch_assoc() fetches one row, not all.
You can use a while loop which will end once fetch_assoc() stops returning new rows.
while($row = $result->fetch_assoc()){
include("views/v_news.php");
}
For pagination, you only need to change LIMIT parameters
i.e. LIMIT 10,10 would be the second page data (10 total rows starting with row 10).
Also as bobiczeq pointed out you should ensure the echo statement appears in <?php $row['id_article']; ?> otherwise this is only empty.
I found correct answer.
$rows = mysqli_fetch_all($result, MYSQLI_BOTH);
Now it's working correctly.

Do - While loops in PHP

I have what is probably a ridiculously simple problem to solve in PHP, but my brain will not engage.
I have products divided into categories. I have performed a successful query which gives me an array containing the products joined to their respective categories. Now I want to display them by category, splitting each category up into its own div. I have the following code:
$current_category = 0;
do
{
if($current_category != $row['category_id']){
echo '<div class="block">
<div class="menu">
<h4>'.$row['category_name'].'</h4>
<ul>';
do
{
echo '<li><a>'.$row['product_name'].'</a></li>';
}
while ($row['category_id'] == $current_category);
$current_category++;
//close list and divs
echo '</ul>
</div>
</div>';
}
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
But this only outputs the first product in each category, rather than outputting them all then moving on to the next. What am I doing wrong?
You need to get the next row in the inner loop, not in the outer one:
do {
// no need to check we're in the right category - we always are
$current_category = $row['category_id'];
echo '<div class="block">
<div class="menu">
<h4>'.$row['category_name'].'</h4>
<ul>';
do {
echo '<li><a>'.$row['product_name'].'</a></li>';
// !!! get the next row here
$row = $stmt->fetch(PDO::FETCH_ASSOC);
}
while ($row['category_id'] == $current_category);
//close list and divs
echo '</ul>
</div>
</div>';
// !!! and don't get it again here
} while ($row);
You need to make sure that your SQL query sorts by category first

Limit characters of data to display on webpage with substr

I want to display data from my database but I have the following problem. I would like to display only the first 120 characters of the row 'text'. I know I can do this with the substr function.
I tried to implement substrin my code, but no text is shown when I reload the webpage ...
The whole code:
(connect to database)
$sql = "SELECT * FROM `table-example`";
// perform the query and store the result
$result = $conn->query($sql);
$text= $row['text'];
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = mysqli_fetch_array($result))
{?>
<div id="preview">
<div class="title">
<?php echo $row['title'];?>
</div>
<div class="subtitle">
<?php echo substr($text, 0, 120);?>
</div>
</div>
<?php
}// end while
}// end if
else {
echo '0 results';
}
?>
(close connection)
Can someone please explain to me how to solve this?
The solution is to place $text = $row['text'] within the while loop.
Since before that, you don't declare $row to anything, therefore $text doesn't get set. Because $text isn't set, the substr method will shorten nothing AKA the echo returns nothing.

WHILE loops can't be used twice? PHP

I am new to PHP , I hope someone can help me. I have a table which contains "id" , "img" , "link" and "desc" in mysql database . I want it to echo all out into something like this :
<div id="featured">
<a target='_blank' href='link'><img src='image link1' title='description'/></a>
<a target='_blank' href='link'><img src='image link2' title='description'/></a>
<a target='_blank' href='link'><img src='image link3' title='description'/></a>
<a target='_blank' href='link'><img src='image link4' title='description'/></a>
</div>
<div id="cap">
<span class='desc' id='idnumber'>Description1</span>
<span class='desc' id='idnumber'>Description2</span>
<span class='desc' id='idnumber'>Description3</span>
<span class='desc' id='idnumber'>Description4</span>
</div>
PHP CODE:
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Can WHILE being used twice or i am wrong? when i run this code , the second while loop is not working , the spans are not showing at all.
Please help.
The first loop consumes all data from mysql already, so there is nothing left in the second loop. You can store the rows data in the meanwhile however and then re-use that store.
<div id="featured">
<?php
$rows = array();
while($row = mysql_fetch_array( $query )){
$rows[] = $row;
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
foreach($rows as $row){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Use this before your second while loop
mysql_data_seek($query,0);
The DB reference ($query) acts as a pointer to the next unread record; when you call mysql_fetch_array(), it gets the record that is being pointed to, and moves the pointer to the next position.
Therefore, after looping through them all, the pointer will be pointing at the end of the record set, hence it returns false when you ask for the next record. Finishing the loop does not do anything else to the pointer; it remains pointing to the end of the record set.
So what you need to do is reset the pointer to the start of the data set before you can loop through it a second time.
The function to do this is mysql_data_seek();
Therefore you'd need the following line of code immediatly before your second loop:
mysql_data_seek($query, 0);
Hope that helps.
Fromt the docs for mysql_fetch_array
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
The internal data point is still at the end when you try to use your second while loop. You have done nothing to reset it.
You can move it back to the start with mysql_data_seek
You can use while twice, but see what it does:
It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.
Once mysql_fetch_array has no more rows to fetch, it will return false on every subsequent call - so your first while loop will stop looping, as the expression mysql_fetch_array( $query ) is false; and since it's the same expression in the second while, that loop will never execute (as the expression evaluates to false).
What to do: If you want to loop over the results multiple times, I'd suggest to store the result rows into an array first, then loop over them. Simplified example:
$results = Array();
while ($row = mysql_fetch_rows($query)) {
$results[] = $row;
}
foreach ($results as $row) {
echo $row['something'];
}
mysql_fetch_array will be empty because you have already fetched all of the rows from the database. You will need to reset the pointer using mysql_data_seek.
<?php
mysql_data_seek( $query, 0 );
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
... rest of code
With mysql_fetch_array() you are going through the results step by step, till you are at the end. Or as the PHP docs say:
Returns an array that corresponds to
the fetched row and moves the internal
data pointer ahead.
This means, you need to start from new. So, use this before your second while:
mysql_data_seek($query,0);
try this
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
$query2 = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]'
title='$row[desc]'/> </a>";
}
?>
</div>
<div id="cap">
<?php
while($row2 = mysql_fetch_array( $query2 )){
echo "<span class='desc' id='$row2[id]'>$row2[desc]</span>";
}
closedb();
?>
$str_res1 ='';
$str_res2 ='';
while($row = mysql_fetch_array( $query )){
$str_res1 .= " a target='_blank' href='$row[link]' img src='$row[img]' title='$row[desc]' a";
$str_res2 .= "span class='desc' id='$row[id]'> $row[desc] span>";
}
sorry i couldn't complete html tags in my answer as it disappears from post if i write "<" or "/>"
by this you can take all values in php strings and you can echo it any where you want to .
$stuff = mysql_query("SELECT * FROM tbl");
while($s = mysql_fetch_array($stuff)){
//ur code
}
// add this line
mysql_data_seek( $stuff, 0 );
while($r = mysql_fetch_array($stuff)){
//ur code
}
mysql_data_seek($query, 0); is deprecated since php 5.5 and removed from php 7.0
use mysqli_data_seek($query, 0); instead

Categories