I am trying to figure out why my mysqli query is not returning all the rows. For some reason it returns 3 results when there are 4 in the database. It is completely skipping the first record in the database. Here is my query.
$results = "SELECT * FROM `results` LIMIT 10";
$result = $conn->query($results);
if ($result) {
?>
<div id="tableResults">
<div class="row1 bg">Predicted Sex</div>
<div class="row2 bg">Suggested Baby Boy Name</div>
<div class="row3 bg">Suggested Baby Girl Name</div>
<div class="breaker"></div>
<?php
/* fetch object array */
$i = 0;
$count = count($result->fetch_array());
while ($row = $result->fetch_array()) {
?>
<div class="row1 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['sex']; ?></div>
<div class="row2 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['boy_name']; ?></div>
<div class="row3 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['girl_name']; ?></div>
<?php
$i++;
}
}
$conn->close();
?>
As was stated in the comments $count = count($result->fetch_array()); this will not work as expected and makes you lose one row (as it has been fetched). Instead you can use num_rows like the following
$count = $result->num_rows;
while ($row= $result->fetch_array()) {
//...
}
To go into detail, when you read the manual on fetch_array(), you'll find this part
mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both
A result row (in words: one) will be fetched any time this function is called. So currently your code is similar to:
fetch one row -> do nothing with it
while:
fetch one row -> display it
Related
I want to get two results at a time when using while looping trough a associative array in PHP.
I need to echo two results per row, something like this:
<?
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
echo('
<div class="row">
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
</div>
');
}
}
?>
Right now it's giving me the same result twice rather than the next one.
You can use a counter to control the output of the outside div so that you get two inside div output for each outside one:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
if ($i % 2 == 0) echo '<div class="row">';
echo '<div><p>'.$client_name.'</p><p>'.$review.'</p></div>';
if ($i % 2 == 1) echo '</div>';
$i++;
}
I am fairly new to PHP and mySQL and have small issue I am busy trying to create a 4 column layout with using echo and currently I have managed to achieve this with with a mySQL database but the last column requires and additional style in the div class. With my Limited knowledge I thought of trying a count using one of the solutions I found on the forum, but I think I may be using it wrong. my idea is to echo the database array, then do a count and echo the same content block but the with additional css element in div class. Your help is greatly appreciated. if this question has been asked before please accept my apologies I am just under a lot of pressure to get it resolved.
SEE CURRENT PHP Code Below
<?php
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysql_error());
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysql_error());
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysql_error());
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
echo "
<div class='percent-one-fourth'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "
<div class='percent-one-fourth column-last'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
}
mysqli_close($conn);
?>
As you're new to PHP, it's really important that you understand why your code isn't working properly. So, let's step over it and describe it in brief, simple English:
Connect to MySQL
Run a database query which has multiple rows as its response
Whilst there are more rows to go..
Output every row
Whilst there are more rows to go.. [!] Always false - we already used them all up
Output every 4th result [!] Vars like $image also aren't defined here
So, because of the way how mysqli_fetch_array works, you can hopefully see that we need to loop using it only once. This is also great for you, because it fits with the DRY (don't repeat yourself) principle.
Edit: You were also mixing MySQL API's; mysql_error is very different from mysqli_error.
So instead, during our one loop, we'll check if we're on the 4th row, and react differently. That results in something like this:
<?php
// 1. Connect to MySQL
// (this should be in a separate file and included so you don't repeat it)
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysqli_error()); // <-- *mysqli*
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysqli_error());
// 2. Run the query which has multiple rows as its response:
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysqli_error());
// 3. Whilst there are more rows to go..
$i=0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
// Get easier references to various fields:
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
// Start outputting this row:
echo "<div class='percent-one-fourth";
// The important part! We check here in this single loop:
if($i++ % 4 == 0){
// Every 4th row - output that extra class now!
echo " column-last";
}
// Output everything else:
echo "'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
// Tidy up:
mysqli_close($conn);
?>
Your code is echoing only for the 4th column. For columns 1, 2, and 3, you need to add an else clause.
Optional: Besides instead of echoing you could close the php tag (?>) and write the html directly.
...
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "html for the 4th column";
}else{
echo "html for column 1, 2, and 3";
}
}
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.
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.
here's my code, there's something wrong, because when I put this in wamp (chrome), it returns me a duplicate "published by" (for any doubts, $conex = mysql_connect('localhost', 'root') )
<?php
mysql_select_db("spectrum-solaris",$conex);
$query = mysql_query("SELECT id,name,tittle,body FROM articles ORDER BY id DESC",$conex);
$row = mysql_num_rows($query);
if($row > 0 ){
do {
?>
<div class ="tematica" >
<p>
<small>Published by <b><?= $row['name'] ?></b></small>
</p>
<p>
<big><?= $row['tittle'] ?></big>
</p>
<p>
<b><?=$row['body']?></b>
</p>
</div>
<?php
}while($row = mysql_fetch_array($query));
}
mysql_free_result($query);
mysql_close($conex);
this is the result (the blue lines are made by me on PAINT):
(http://spectrum-solaris.meximas.com/stack2.PNG)
do { } while() is not appropriate for a DB loop. On your FIRST past through the do. $row isn't going to be a DB result. It's going to be a simple integer - the number of rows in the result.
You want this instead:
$numrows = mysql_num_rows($query);
while($row = mysql_fetch_array($query)) {
...
}
Can you try this, instead of do { } while()
if($row > 0 ){
while($rowData = mysql_fetch_array($query)){
?>
<div class ="tematica" >
<p>
<small>Published by <b><?= $rowData['name'] ?></b></small>
</p>
<p>
<big><?= $rowData['tittle'] ?></big>
</p>
<p>
<b><?=$rowData['body']?></b>
</p>
</div>
<?php
}
}
mysql_free_result($query);
mysql_close($conex);
You don't fetch a row of your resultset on the first iteration... so $row doesn't contain datas on this first iteration.
You could try something like :
while ($row = mysql_fetch_assoc($query)){ // or mysql_fetch_array or ...
// ...
}
If you really want to use do{}while despite it's unsuitable for your use :
do {
$row = mysql_fetch_assoc($query); // or mysql_fetch_array or ...
// ...
} while ($row);