I have the foillowing PHP code, but I can't get it to work?
This is the main PHP file:
function get_data() {
$query = 'SELECT title, article FROM submissions';
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
return $row; //perhaps because $row is not return all?
}
$data = get_data();
require('template/data.inc.php');
?>
and this is template/data.inc.php:
<?php
foreach ($data as $value):
echo $data['i'].'<br>';
echo $data['title'].'<br>';
echo $data['article'].'<br>';
endforeach;
?>
template/data.inc.php is meant to output something like:
1 How to get your site on Google?
Text...
2 Secrets of SEO Revealed
Text...
My guess is get_data() is not returning the array() in a form which is supported within the foreach? - as its currently giving an error.
Here is your problem:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
On every iteration, $row is being reset to current record, and in the end mysql_fetch_assoc will turn it to FALSE. You have to put each $row into auxiliary array and return it as whole resultset:
$i = 0;
$returnArray = array();
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
$returnArray[] = $row;
}
return $returnArray;
ANd in your template use $value to get details for each row:
foreach ($data as $value):
echo $value['i'].'<br>';
echo $value['title'].'<br>';
echo $value['article'].'<br>';
endforeach;
The way in which you're building $row and returning it
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
return $row;
}
You'll only EVER have the LAST iteration of $row set ... if that's what you want? In other words, $row will only continue a single value.
Your loop continues until $row has an value that is evaluated as false:
while ($row = mysql_fetch_assoc($result)) {
and then you return $row so you always return null or false!
replace
$row['title'] = limittext($row['title'], 15);
with
$row['title'] = limittext($row['title'], 15);
$result[]=$row;
and
return $row;
with
return $result;
Related
So I'm making this system where you can reserve a seat but when I'm doing a check if the seat is already reserved it screws up(Means that I'm too bad with loops). I have 3 test users in my database and it echoes the seats as many times as there are users. And it even gets the reserved seats correctly coloured.
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[] = $reserved;
}
echo '<div id="top-section">';
for($i = 0; $i < 44; $i++) {
$seatCount++;
foreach($list as $obj) {
if($seatCount == $obj) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
}
else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
}
echo '</div>';
And the result is this: http://i.gyazo.com/d10e787cea7028b46c716ac41766456a.png (I have three divs of seats and only done the loop on the top part so don't mind the 45 - 68 since they are correct). How do I make it so it only posts the seats once?
You don't need to have that inner foreach statement, if I think I know what you're going for.
There's two things wrong with your code, though.
Firstly, this statement is a little redundant
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[] = $reserved;
}
Change it to this, you know, for simplicity:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$list[] = $row["seat"];
}
Then, the loop can look a little something like this (which uses in_array instead of another loop):
for($i = 0; $i < 44; $i++) {
$seatCount++;
if(in_array($seatCount, $list)) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
} else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
Then, this way, the $seatCount variable will be looked for in the user seats and if it is, it will show the reserved seat and if not will just show a selectable seat.
Your foreach ($list as $obj) is inside the loop. You have three reservations, so it's printing the seat three times. You need to move this outside the loop.
Use in_array():
for ($i = 0; $i < 44; $i++) {
if (in_array($i, $list)) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
}
else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
Even better would be to make $list use the reserved seats as keys, not values:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[$reserved] = true;
}
Then your second loop could use:
if (isset($list[$i]))
You could make something like this:
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$reserved = $row["seat"];
$list[$reserved] = 1;
}
echo '<div id="top-section">';
for($i = 0; $i < 44; $i++) {
$seatCount++;
if(isset($list[$seatCount]) AND $list[$seatCount] == 1) {
echo '<div id="seat_'.$seatCount.'" class="seat reserved">'.$seatCount.'</div>';
}
else {
echo '<div id="seat_'.$seatCount.'" class="seat available" onclick="selectSeat('.$seatCount.');">'.$seatCount.'</div>';
}
}
echo '</div>';
You should use in_array() and remove one foreach loop.
<?php
$list = array(1,2,5);
echo '<div id="top-section">';
for($i = 0; $i < 44; $i++) {
if(in_array($i,$list)) {
echo '<div id="seat_'.($i+1).'" class="seat reserved">'.($i+1).'</div>';
}
else {
echo '<div id="seat_'.($i+1).'" class="seat available" onclick="selectSeat('.($i+1).');">'.($i+1).'</div>';
}
}
echo '</div>';
?>
Demo: https://eval.in/201702
I am trying to pull the image link for 10 different rows based on ids in an array. It seems to break when the query is in the loop..Any ideas how i can accomplish this?
$array = array(54, 319, 342, 298, 281, 190,178,158,138,7);
$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $array[$key];
}
for($i=0;$i<=count($newArray);$i++){
$query = "SELECT logoName,logoImageLink, logoImageLink2, countryImg, logoArtist, afterText, country FROM logos WHERE id = $array($i) ";
$result = mysql_query($query);
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
$imageLink = $row['logoImageLink'];
echo "<li class=\".$array($i).\" ><img src=\".$imageLink.\" /></li>";
}
You can use the MySQL IN clause and do this in a single select.
$ids = join(',',$newArray);
$query = "SELECT logoName,logoImageLink, logoImageLink2, countryImg, logoArtist, afterText, country FROM logos WHERE id IN ($ids)";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
$imageLink = $row['logoImageLink'];
echo "<li><img src=\"$imageLink\"/></li>";
}
I'm trying to display all the information in a msSQL table in an HTML table and have up with something that is not so great.
<table border="1">
<?
echo "<tr>";
for ($i = 0; $i < mssql_num_fields($result); ++$i){
echo "<th>" .$column_names[$i] . "</th>";
}
echo "</tr>";
$num_rows = mssql_num_rows($result);
for ($i = 0; $i < $num_rows; ++$i){
echo "<tr>";
foreach ($column_names as $key => $val){
$result_row = mssql_query("SELECT * FROM username WHERE id = '$i'");
$row = mssql_fetch_assoc($result_row);
echo "<td>";
echo $row[$val];
echo "</td>";
}
echo "</td>";
}
?>
</table>
This works. The first part prints out the column names successfully, but as for the rest:
1) I think it is sort of cumbersome to make a query for every time through the loop
2) it doesn't really work because the ids of the rows go much higher than the number of rows in the table, as some ids aren't used.
It seems like I should be able just make one query and pull everything from the database at one go, then build my HTML table from that, but I can't figure out how to access it row by row where I could go $row[next row][shifted value from $column_names. How can improve this query?
function table_cell($item, $header=false) {
if (!$item) return '';
$elemname = ($header) ? 'th' : 'td';
$escitem = htmlspecialchars($item, ENT_NOQUOTES, 'UTF-8');
return "<{$elemname}>{$escitem}</{$elemname}>";
}
function table_header_cell($item) {
return table_cell($item, true);
}
function table_row($items, $header=false) {
$func = ($header) ? 'table_header_cell' : 'table_cell';
return "<tr>\n\t".implode("\n\t", array_map($func, $items))."\n</tr>\n";
}
function echo_result_as_table($result) {
if ($result && $row = mssql_fetch_assoc($result)) {
$columnnames = array_keys($row);
echo "<table>\n", table_row($columnnames, true), "\n";
do {
echo table_row($row), "\n";
} while ($row = mssql_fetch_assoc($result));
echo "</table>\n";
}
}
$result = mssql_query("SELECT * FROM username");
echo_result_as_table($result);
if ($result) mssql_free_result($result);
If you have an array of associative arrays instead of a raw mssql result handle, you can use a function like this to produce a table string:
function array_to_table($arrayofassoc) {
if (!$arrayofassoc) return '';
$tablestr = '<table>';
$tablestr .= table_row(array_keys($arrayofassoc[0]), true);
$tablestr .= implode('', array_map('table_row', $arrayofassoc));
$tablestr .= '</table>';
return $tablestr;
}
try this:
while($row = mysql_fetch_results($result)){
echo '<td>'.$row['column_name'].'</td>';
}
with 'column_name' being the name of the column in mysql.
but some will say..."wait, but PDO"
I got previousRow of record using this code
<?php
$previousRow = array();
while ($temp = mysql_fetch_row($res2))
{
echo "<br>currentRow:".$temp[1];
echo "previousRow:".$previousRow[1];
$previousRow = $temp;
}
?>
oupout
currentRow:1previousRow:
currentRow:5previousRow:1
currentRow:6previousRow:5
currentRow:7previousRow:6
currentRow:8previousRow:7
How can I check the value of the next row replaced by Previous Row ?
Any help would be grateful.
If I get you correctly, then something like this would help?
$previousRow = array();
$currentRow = mysql_fetch_row($res2);
while ($currentRow) {
$nextRow = mysql_fetch_row($res2);
echo "<br>currentRow:".$currentRow[1];
echo "previousRow:".$previousRow[1];
echo "nextRow:".$nextRow[1];
$previousRow = $currentRow;
$currentRow = $nextRow;
}
Please try code given below.
$res = array();
while ($result = mysql_fetch_row($r)) {
$res[] = $result;
}
echo "<pre>";
foreach($res AS $index=>$res1){
echo "Current".$res1[1];
echo " Next" . $res[$index+1][1];
echo " Prev" . $res[$index-1][1]; echo "<br>";
}
thanks
I'd collect all the rows first, then walk through them with a for:
<?php
$rows = array();
while ($temp = mysql_fetch_row($res2))
{
$rows[] = $temp;
}
$rowCount = count($rows);
for ($i = 0; $i < $rowCount; $i++) {
echo "<br>currentRow:".$rows[$i][1];
if ($i > 0) {
echo "previousRow:".$rows[$i - 1][1];
}
if ($i + 1 < $rowCount - 1) {
echo "nextRow:".$rows[$i + 1][1];
}
}
?>
$output = "<loginsuccess>";
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
$output .= "</loginsuccess>";
I need now a simple condition where if the result is empty then i need to return no inside the xml [ login success ].
Is this a correct way....
if($row = mysql_fetch_array($result)) {
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
} } else {
$output.="no";
}
if (mysql_num_rows($result) == 0) {
$output .= '<loginsuccess>no</loginsuccess>';
} else {
// your code
}
Try this instead:
$i = 1;
while($row = mysql_fetch_array($result))
{
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
$i++;
}
if ($i == 1)
$output .= "no";
Just a quick note, I would do what Schnalle does, but in your code I would change the for loop to a while loop as you are not doing anything with the $i
while($row = mysql_fetch_row($result)){
In total I would write you code like this:
$output = '<loginsucces>';
if(mysql_num_rows($result)){
while($row = mysql_fetch_row($result)){
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
} else {
$output .= 'no';
}
$output .= '</loginsucces>';
Also It owuld be even better not to mix logic and output, but that would be overkill in this situation.
Wont the for-loop simply be skipped when there are no rows? Otherwise you might want to use mysql_num_rows to count the number of rows in your result set.