I am fetching a number of results from my database using a mysql_query. What I need to do is echo the result number, along with the result itself.
In other words, if my query fetches 3 results, I would like the first result to have a 1 beside it, and the second result a 2 and so on. I need the numbers to start at 1, not 0.
note: I do not mean mysql_num_rows as that only tells me how many results, not the result number itself.
Here is my query information:
$primary_img_query = "SELECT imgURL, imgTitle FROM primary_images WHERE primaryId=16";
$primary_img_data = mysql_query($primary_img_query) or die('MySql Error' . mysql_error());
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>";//this is where I want the result number echoed
}
Make a counter:
$count = 1;
while(...){
echo $count++;
}
In your case:
$count = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo $count++;
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>";
}
One other solution I don't see mentioned here is using an ordered list:
$result = mysql_query(...);
echo "<ol>\n";
while ($row = mysql_fetch_array($result))
{
echo "<li><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></li>";
}
echo "</ol>\n";
This gives you more "correct" HTML, if you don't particularly care about the result number in your PHP code. (Nothing stops you from using both, either: use an ordered list to output the number, but keep a counter for other things, like rel attributes or alternating CSS classes.)
Just do:
$counter = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>";//this is where I want the result number echoed
echo $counter++;
}
$i = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>" . $i;
$i ++;
}
$i = 1;
while($row = mysql_fetch_assoc($primary_img_data)) {
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>" . $i;//this is where I want the result number echoed
$i++;
}
A little bit brutish, but why not just keep a counter?
$primary_img_query = "SELECT imgURL, imgTitle FROM primary_images WHERE primaryId=16";
$primary_img_data = mysql_query($primary_img_query) or die('MySql Error' . mysql_error());
$n=0;
while($row = mysql_fetch_assoc($primary_img_data)) {
$n++;
echo "<img src='new_arrivals_img/thumbnails/".$row['imgURL']."'>" . $n;
}
Inline counters, for the win.
$i = 0;
while($row = mysql_fetch_assoc($primary_img_data))
{
echo ++$i . "<img src='new_arrivals_img/thumbnails/" . $row['imgURL'] . "'><br>";
}
This is not materially different than any other answer here, other than it's 1 line shorter and actually leverages the fact that you can use incrementors inline.
Related
I'm trying to make a website that displays all userprofiles. I want to wrap every two users in a <div>, until there is no left. So say we have 19 arrays consisting of userprofileinfo in $info - the following code will work fine, but will print out the 20th out as an empty div, which I want to prevent. What to do here?
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= mysqli_num_rows($result) - 1; $count += 2) {
echo <div class="row">
echo "<div>".print_r($info[$count])."</div>";
echo "<div>".print_r($info[$count+1])."</div>";ยจ
echo </div>
}
I think you might overthinking this. Why not simply use array_chunk()?
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach (array_chunk($info, 2) as $chunk) {
echo '<div class="row">';
foreach ($chunk as $element) {
echo "<div>".$element['name']."</div>";
}
echo '</div>';
}
The way array_chunk() works is that it will group the array elements into chunks of a given size. You can have a double loop. The inner loop will iterate on each chunk and display both elements.
Just to provide a slightly cleaner version of Yvan1263's answer using OPs updated code (having fixed quotes).
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= count($info) - 1; $count += 2) {
echo '<div class="row">';
echo "<div>".print_r($info[$count])."</div>";
if (isset($info[$count+1])) {
echo "<div>".print_r($info[$count+1])."</div>";
}
echo </div>
}
You can just do this:
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= mysqli_num_rows($result); $count += 2) {
if($count+1 >= mysqli_num_rows($result)) {
/* IF MAX IS MORE THAN ENTRIES NUMBER */
echo "<div>".print_r($info[$count])."</div";
}
else {
echo "<div>".print_r($info[$count])."</div";
echo "<div>".print_r($info[$count+1])."</div";
}
}
NB: Use PDO instead of MySQLi.
Im creating tablerows based on the number of the array colours:
$query = mysql_query("SELECT * FROM things);
$num = mysql_num_rows($query );
$colours = array ();
if($num)
{
for ($i = 0; ($row = mysql_fetch_assoc($query)); ++$i)
{
$colours[$i] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; ($i < ($arrlength)); ++$i){
echo "
<tr class='border_bottom'><td>".$colours[$i]."</td></tr>
";
}
So, if colours is, lets say, equal to 8, 8 table rows with the class border_bottom are created.
border_bottom is used by CSS to add a border to the bottom of each tablerow.
What I need is some PHP help: I need code which checks the array colours. The last element of the array has to go with an empty id since I dont want a border-bottom added to that very last tablerow. All other tablerows have to go with the border_bottom class, tho.
I was thinking of starting the code like that:
echo"
<tr class='
";
-->PHP code goes here<--
echo"
'>
<td>".$colours[$i]."</td></tr>
Try this:
<?php
$query = mysql_query("SELECT * FROM things");
$num = mysql_num_rows($query);
$colours = array();
if($num)
{
while($row = mysql_fetch_assoc($query))
{
$colours[] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; $i < $arrlength; ++$i){
if($i < $arrlength - 1){
echo "<tr class='border_bottom'><td>{$colours[$i]}</td></tr>";
}else{
echo "<tr><td>{$someColor}</td></tr>";
}
}
Try the following code in your table row echo
echo "<tr"
.($i < $arrlength - 1 ? " class='border_bottom'" : "")
.">"
."<td>{$colours[$i]}</td></tr>";
You can actually do this while fetching the rows without needing to count how many there are, by reading ahead one row.
$previous_row = mysql_fetch_array(); // fetch the first row (if there is one)
while ($previous_row) {
if ($row = mysql_fetch_array()) {
// if another row is fetched, then the previous row was NOT the last row
echo '<tr class="border_bottom"><td>' . $previous_row['colours'] . '</td></tr>';
} else {
// otherwise, the previous row WAS the last row, and does not get the class
echo '<tr><td>' . $previous_row['colours'] . '</td></tr>';
}
$previous_row = $row; // Set the previous row to the current row
}
I am attempting to populate 0 to many drop downs with the same results from a database table depending on a previous selection. it is working fine when 0 and 1 are selected but not when i am attempting to insert the result set into subsequent select elements. i am assuming it is a problem with the $row array position.
$homePlayers = "SELECT first_name, last_name, player_id FROM players WHERE team_name LIKE '$homeTeam%'";
$homePlayersQuery = mysqli_query($dbc, $homePlayers);
if (!$homePlayersQuery) {
echo 'err';
} else {
for ($i = 1; $i <= $homeTeamScore; $i++) {
echo "<select name='select-home-scorer-$i'>";
while ($row = mysqli_fetch_array($homePlayersQuery)) {
echo current($row);
echo "<option value='" . $row['player_id'] . "'>" . $row['first_name'] . " " . $row['last_name'] . "</option>";
}
echo "<option value='og'>Own Goal</option></select><br/>";
}
}
}
The problem you experience is that mysqli_fetch_array() reads data of the result set once. When you have read the last record, subsequent calls to mysqli_fetch_array() will return false.
You have 2 choices.
Firstly, you can read the records into an array and repeatedly parse the array.
while ($row = mysqli_fetch_array($homePlayersQuery)) {
$resultsArray[] = $row;
}
for ($i = 1; $i <= $homeTeamScore; $i++) {
foreach($resultsArray as $resultItem) {
do_something_here();
}
}
}
As a second option, you could rewind the pointer to the mysql result set so that you can start reading the results again.
for ($i = 1; $i <= $homeTeamScore; $i++) {
// Rewind the pointer to the start of the results
mysqli_data_seek($result, 0);
while ($row = mysqli_fetch_array($homePlayersQuery)) {
$resultsArray[] = $row;
}
}
I am trying to make a function in PHP which writes out a table, and looks in the database to find what cells should have info. the grid will always be the same size, but the content may be in different places.
I've gotten it to be able to look in the database, though it seems to only highlight the first cell, rather than the correct coordinates.
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
$xobj = array();
$yobj = array();
while($row = $result->fetch_assoc()){
//echo $row['x'] . $row['y'] . $row['object'] . '<br />';
$xobj[] += $row['x'];
$yobj[] += $row['y'];
}// get the rows
//find whether the row is obstructed
for($a=0; $a<=20-1; $a++) //rows (y)
{
for($i=0; $i<=25-1; $i++) //cols (x)
{
echo "<td>"; //between these write the apt content
// if (empty($xobj[$i]) || empty($yobj[$a]) ){
// echo '0';
//} //detect whether there is even a record for this space
if(!empty($xobj[$i]))
{
if(!empty($yobj[$a]))
{
echo $xobj[$i]; //debug
if($xobj[$i] == $i)
{
//echo $xobj[$i];
echo "A";
}
}
}
//echo "<td><img src='emptysym.png'></img></td>";
echo "</td>"; //add textual descriptions for now, add icons later
}
echo "</tr>";
}
this is my current(though rather messy) code.
if there is a row with the column x saying 2, and the column y saying 3, then it should put a letter at (2,3.
is it possible to fix this, or is there a better method for this?
Use a 2-dimensional array whose indexes are the x and y values from the database:
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
}
Then your output loop should be:
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo '<td>';
if (isset($xyobj[$x][$y])) {
echo 'A';
}
echo '</td>';
}
echo '</tr>';
}
I am trying to use a for loop to select an incremental value with a MySQL query. I have included sample code below:
<?php
$day_1="sep_28";
$day_2="sep_29";
$day_3="sep_30";
$query = mysql_query("SELECT * FROM table WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
//$dayVarCount = $dayVar."_count"; // Don't really need this anymore, so removed.
$dayVarCount = $row[$$dayVar];
echo "$$dayVar.': '.$dayVarCount<p>"; // Edited.
}
}
?>
I think I am getting close, but when I run the code my page is showing this:
$day_1.': '.0
$day_2.': '.2
$day_3.': '.5
Any additional recommendations? Thanks for the great help!
Try a variable variable:
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
$dayVarCount = $dayVar."_count";
$$dayVarCount = $row[$$dayVar];
echo $$dayVar.': '.$$dayVarCount.'<p>'; // Edited.
}
This basically uses a string to reference a variable by its name.
Just think of it this way:
$variable = 'hello';
$string = 'variable';
echo $$string;
// Is the same thing as:
echo $variable;
// Because you can thing of $$string as ${$string} ---> $variable when {$string} is interpreted into 'variable'
http://php.net/manual/en/language.variables.variable.php
Replace this line:
echo "$$dayVar.': '.$dayVarCount<p>";
with this:
echo $$dayVar . ': ' . $dayVarCount . '<br>';
<?php
$day_1="January 1";
$day_2="January 2";
$day_3="January 3";
$query = mysql_query("SELECT * FROM dates WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$var = $."day_".$i;
$day_$i_count=$row['$var'];
echo "$day_$i: $day_$i_count<p>";
}
}
?>
You can try this code too.
That all seems overly complicated, but possibly I don't understand the question adequately. Would this work?
$day[1]="sep_28";
$day[2]="sep_29";
$day[3]="sep_30";
$query = mysql_query("SELECT * FROM table WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
foreach ($day as $day_str)
{
echo $day_str . ':' . $row[$day_str] . '<p>';
}
}