PHP dynamical duplicate Mysqli results set - php

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;
}
}

Related

In PHP and MySQL, my code only prints one row of the table's column

I'm a begginer with php, and I have some troubles with it. My question is about PHP and MySQL. The purpose of the code is that I have a parameter called $sql in which I will write the SQL query. The problem is that my code only prints one row of the consult. I mean, if I have a table with 4 columns (the attributes) and in that table I have 4 rows, the code only prints one row of each column.
The method consult code:
public function makeConsult($sql){
$result = mysqli_query($this->conn, $sql);
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
for($i = 0;$i<count($nrows);$i++) {
$row= mysqli_fetch_array($result,MYSQLI_NUM);
for ($j=0; $j < count($row) ; $j++) {
array_push($this->results, $row[$j]);
}
}
} else {
echo "No matches found";
}
}
The following method is where I print all the consults:
public function printResult(){
foreach ($this->results as $key => $value) {
echo $key . ": " . $value . "<br>";
}
$this->results = array();
}
The variable $conn is the variable where I have my sql connection.
My execution code:
$db = new dbConnection("localhost","root","","sportsweb");
$db->connect();
echo "Database name: " . $db->getDBname();
$consult = $db->makeConsult("SELECT * FROM articles A");
$db->printResult();
$db->closeConnection();
The columns (attributes) of the table "articles" are the following ones: Id,Name,Units,BranchOffice.
Thank you! :)
You have two mistakes here
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
for($i = 0;$i<count($nrows);$i++) {
$row= mysqli_fetch_array($result,MYSQLI_NUM);
for ($j=0; $j < count($row) ; $j++) {
array_push($this->results, $row[$j]);
}
}
}
So $nrows will be a count of how many rows you got back. So count($nrows) is useless because it's not an array
Second, I don't know where you got the idea to iterate rows like that, but you're doing it wrong. Use a while loop instead. I also removed the inner for loop and switched to a simpler foreach
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
while($row = mysqli_fetch_array($result,MYSQLI_NUM)) {
foreach($row as $val) $this->results[] = $val;
}
}

Distinguish between elements and last element of array

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
}

Echo out SQL result to create a timetable

I am having problems printing out a timetable using the results from a SQL statement and some HTML layout with PHP.
I have the times of the classes along the top of the page.
I am trying to put the days of the week along the side of the page and then check if the result of the SQL statement (containing a module) should be printed in the specific day and time.
//Print out the top of the array to display the times
echo "<div><table class='table table-bordered'><thead><tr><th></th><th>9-10</th><th>10-11</th><th>11-12</th><th>12-13</th><th>13-14</th><th>14-15</th><th>15-16</th><th>16-17</th></tr></thead><tbody>'";
//Now loop through the result of the SQL statement that contains the modules associated with the selected course
while($row = mysqli_fetch_array($result1)) {
for($d = 1; $d < 6; $d++){
$printday = $days[$d];
echo "$printday";
for($t = 9; $t < 17; $t++) {
if($row['Day'] == $d && $row['Time'] == $t){ //fix this area so that it moves along
echo "<td>" . $row['ModuleName'] . "<br/>\n " .$row['Location'] . "</td>";
} //if
else {
echo "<td></td>";
} //else
} //for 2
echo "</tr>";
} //for 1
} //while
The problem is that I am printing out Monday-Friday 3 times as there are 3 $row results. Any idea how I could get this to work.
Your looping through your data in the wrong spot, you first need to put that in an array so you can loop through it for each day/time.
//Print out the top of the array to display the times
echo "<div><table class='table table-bordered'><thead><tr><th>Day</th><th>9-10</th><th>10-11</th><th>11-12</th><th>12-13</th><th>13-14</th><th>14-15</th><th>15-16</th><th>16-17</th></tr></thead><tbody>'";
//Now loop through the result of the SQL statement that contains the modules associated with the selected course
$courses = array();
while($row = mysqli_fetch_array($result1)) {
$courses[] = $row;
} //while
for($d = 1; $d < 6; $d++){
$printday = $days[$d];
echo "<tr><td>" . $printday . "</td>";
for($t = 9; $t < 17; $t++) {
unset($course_row);
foreach($courses as $course){
if($course['Day'] == $d && $course['Time'] == $t){ //fix this area so that it moves along
$course_row .= $course['ModuleName'] . "<br/>\n " .$course['Location'] . "<br/>\n<br/>\n";
} //if
}
if(isset($course_row)){
echo "<td>" . $course_row . "</td>";
} else {
echo "<td> </td>";
} //else
} //for 2
echo "</tr>";
} //for 1

how can I higlight the correct cell in PHP

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>';
}

PHP: Echo Result Number

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.

Categories