I have been trying to return a list of results from MySQL using PHP.
The basic query is simple and the output is multiple columns. I want to add a number so the array looks like this:
Club 1
Club 2
I have tried the below but it keeps breaking the script:
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
for($i=1; $i++){
$club = $row['club_name'];
echo '<p>' . $i . $club . '</p>';
}
}
}
I have then tried placing the for statement outside the while and inside it, changed it to foreach and used the format ($i=1; $i<100; $i++){} and it still doesn't work.
Sorry if this is an obvious one I've tried numerous different ways and it just isn't working for me.
Try creating a counter variable ($i) and incrementing it on every iteration of the while loop ($i++), like this:
if (mysqli_num_rows($result) > 0) {
$i = 1;
while($row = mysqli_fetch_assoc($result)) {
$club = $row['club_name'];
echo '<p>' . $i . $club . '</p>';
$i++;
}
}
Then, to change the format to match 1. Club Name, change
echo '<p>' . $i . $club . '</p>';
to
echo "<p>$i. $club</p>";
But, I'd personally recommend to use an <ol> instead and skip setting the counter altogether like this:
if (mysqli_num_rows($result) > 0) {
echo "<ol>";
while($row = mysqli_fetch_assoc($result)) {
$club = $row['club_name'];
echo "<li>$club</li>";
}
echo "</ol>";
}
Related
Wanted to get 2 values id and name but im confuse how get it, i wanted to show the id in the link. heres the sample code.
echo "<table width=\"100%\" border=\"1\" cellpadding=\"5\" cellspacing=\"2\" bordercolor=\"#FFFFFF\">";
$count = 1;
$id=$_GET['id'];
$col1 = $col2 = array();
$rowcount = round(mysqli_num_rows($nquery) / 2);
while($crow = mysqli_fetch_assoc($nquery)) {
if($count > $rowcount) $col2[] = $crow['title'];
else $col1[] = $crow['title'];
$count++;
}
$counter = 0; // Arrays start with 0
foreach($col1 as $crow) { // $col1 will always be >= $col2
$row2 = (isset($col2[$counter])) ? $col2[$counter] : "";
echo "<tr><td><a href='index.php?page=".$id."'>" . $crow . "</td><td>" . $row2 . "</td></tr>";
$counter++;
}
echo "</table>";
?>`
id wont show up on the link. Hope someone can help. Thanks
You're trying to get $id values from the query string (that's what the $_GET superglobal is) and not from the database.
If both elements (ID and name) are coming from the same database query, you may try something like this:
$crow = mysqli_fetch_assoc($nquery);
foreach ($crow as $row)
{
echo $row['id'].' is the ID and '.$row['title'].' is the title';
}
if you remain within the foreach loop, you can use $row['id'] and $row['title'] to build the table element and link you're trying to obtain.
I am working on a project to pull data from a sql database via PHP and create an HTML table from it. It is part of a form I am creating and the table will be a listing of what I am selling, costs, weights, etc. Anyway, I need to do this with PHP. So far I have the following in this section of my code to make this table:
<?php
$db=mysqli_connect(null,null,null,'weblab')
or die("Can't connect to DB: " .
mysqli_connect_error());
$query="SELECT fruit_item_no, fruit_name, fruit_price, fruit_weight FROM fruit_$
$result=mysqli_query($db, $query);
if (!$result) {
print "Error - The query could not be executed!" .
mysqli_error();
}
print "<table class = 'main'><caption> <h2> Fruit Purchasing Form </h2> </c$
print "<tr align = 'center'>";
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
}
else {
print "There were no such rows in the table <br />";
}
print "</table>";
?>
The problem I am running into is when I attempt the view the entire page in Chrome, all I see is:
I think the error is somewhere around this section of code:
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
If anyone can give me a little direction on what I might be missing, I would greatly appreciate it. I have been researching a while now and no clear fix has come up that i can see.
UPDATE:
Thought it would be best to just update my post instead of new question or comment somewhere. Thanks to all your suggestions I was able to correct my code to properly display my table and worked out all validation errors. I apologize for the code reading nightmare... I am still fairly new at this and I need to work more at it.
I did run into one issue I still cannot resolve though. I am trying to add an input box on the end of each row in the table I created. Problem is no matter what I try the boxes stay in a line above the table (pretty much at the top of the browser screen.
I placed this line in the sql query block to try to get the input box:
echo ("<input name='item[]' type='text' .=''/>");
and I also tried:
echo ("<input type='text' name ='item'/>");
Both did the same thing in giving me the line of boxes along the top. Any direction you could provide in getting these to be at the end of each row? I do not need it to put data back in the database or add to a table there. I just am trying to get input fields that will allow input that will submit with my form.
You can simplify the code by running and while loop on the result and iterating through the rows. And then using foreach loops since each row is an array of key value pairs. On the first iteration you could print the header.
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$i = 0;
// loop through each row in the result
while ($row=mysqli_fetch_assoc($result)) {
// if first then print the header
if ($i == 0) {
print "<tr>";
foreach ($row as $field => $value) {
print "<th class='a'>".$field."</th>";
}
print "</tr>";
}
// print the row
print "<tr>";
foreach ($row as $value) {
print "<td class='b'>".$value."</td>";
}
print "</tr>";
$i++;
}
}
else {
print "<tr></td>There were no such rows in the table</td></tr>";
}
As suggested in the comments it would be a good idea to separate your view from your code.
In your second for loop, you have this:
for($index=0; $index<$num_fields; $row_num++)
Well, the value of $index will remain 0 throughput your execution. Try changing it to
for($index=0; $index<$num_fields; $index++)
{
$row_num++;
//rest of code
}
Hope it helps.
This is unnecessarily complicated:
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
Something like this would be easier to read and should solve your problem, which was caused by incrementing the wrong index on one of the for loops:
$headers = false;
while($row=mysqli_fetch_assoc($result)) {
if (!$headers) {
echo "<thead><tr>";
foreach($row as $k=>$v) {
echo "<th>$k</th>";
}
echo "</tr></thead>";
$headers = true;
}
echo "<tr>";
foreach ($row as $k=>$v) {
$v=htmlspecialchars($v);
print "<td class='b'>$v</td>";
}
echo "</tr>";
}
But I would strongly recommend a) using a database abstraction layer like PDO, and b) separating your logic from your presentation. Debugging problems with HTML is made 100 times harder when it's jumbled all together with your PHP like this.
I've checked around google and in here and I am unable to find an answer specific to what I'm wanting to do.
Basically, I am trying to make a table with the database like this:
[0001][0002]
[0003][0004]
However, for some reason I am unable to do that.
This is what I've got down, and it's not even functioning. I would like to note that I am pretty new to php, although that may be obvious.
<table>
<?php
...
$x = 0;
while($info = mysql_fetch_array( $data ))
{
while($info['id'] <= 4)
{
if($x ==0){ // [I feel like the error is in here.]
Print "<tr>";
$x++;
}elseif($x == 2){
Print "</tr>";
}else(){
$x++;
}
Print '<td><img src="' .$info['img'] . '" width="210" height="157">';
Print "".$info['name'] . "</td>";
}
}
?>
</table>
Without the counter, the table is more of a single-column table going down.
You've got a few issues:
Syntax errors in your print lines, your concatenation (.) areas have inconsistencies with the type of quotes you're using to get back into the string e.g. ' or "
Identifying which column and where the break point is isn't really there
Try something like this (assume your database results are fine):
<table>
<?php
// ...
$i = 1;
$columns = 2;
while($info = mysql_fetch_array( $data )) {
if($i == 1) {
echo '<tr>';
}
echo '<td><img src="'.$info['img']. '" width="210" height="157">' . $info['name'] . '</td>';
if($i == $columns) {
echo '</tr>';
$i = 1;
} else {
$i++;
}
}
?>
</table>
Edit: Nico Parodi's answer is correct. I will eventually return to finding out why, but for now I will just take it as it is and hope nothing else fails.
I have a table with three fields: "date", "name", "location". I want to group all the records selected from this table based on their date.
By copy-pasting some code from php mysql group by date with yyyy-mm-dd format, I've managed to get this array, date -> name:
$result = mysqli_query($con,"SELECT date, name, location FROM events");
while($row = mysqli_fetch_array($result)) {
$foo[$row['date']][]=$row['name'];
}
Everything's great, I can iterate it without issues. Now I want to store all the row columns as a value for the date key, so I try to store the entire row as a value:
$result = mysqli_query($con,"SELECT date, name, location FROM events");
while($row = mysqli_fetch_array($result)) {
$foo[$row['date']][]=$row;
}
And now I can't iterate it. count($rowCol) seems to give me the nr of columns in all the array for either keys, not just for one. How can I iterate it?
foreach($foo as $date => $events) {
echo $date . ": "; // this is okay
foreach($events as $key => $rowCol){
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
}
}
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
$rowCol has the double of fields that you expect as mysqli_fetch_array() fetches as both associative and numeric array.
So,
for ($i = 0; $i<(count($rowCol)/2); $i++) {
echo $rowCol[$i] . " ";
}
should work.
Replace :
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
By
foreach($rowCol as $k =>$v) {
echo $v . " ";
}
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
this part of code doesn't work because rowCol is an associative array + numeric array. Try to replace mysqli_fetch_array with mysqli_fetch_row
Can you tell us what's the output of this code? (show plain text, no HTML):
foreach($foo as $date => $event) {
echo $date . ": ";
foreach($event as $key => $value){
print_r($value);
}
echo "\n";
}
Original answer:
$events contains a single event, your code should look more like this:
foreach($foo as $date => $event) {
echo $date . ": ";
foreach($event as $key => $value){
echo $value . " ";
}
echo "\n";
}
I have a search engine and because of the paralympics, I want people to be able to see a h1 countdown I have placed at the top of my site. Underneath will be the looped results from my database. Any ideas where I go wrong? because in this if, it won't echo the h1 tag at all. I would like to above my results.
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0) {
$query .= " OR ";
}
$query .= "keywords LIKE '%{$each}%'";
}
// Don't append the ORDER BY until after the loop
$query .= "ORDER BY rank";
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error($connect));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$rank = $row['rank'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p maxlength="10" class="kk">' . $description . '</p>' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords"></p>' . PHP_EOL;
}
} else {
echo "No results found for \"<b>{$k}</b>\"";
}
if ($k = "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
if ($k = "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
Will always print the <h1>. You're doing assignment rather than comparison. Try:
if ($k == "Paralympics 2012")
Also, verify that $k is what you expect it to be when debugging.
One equals (=) assigns, and two/three (==/===) compares. The line
if ($k = "Paralympics 2012") {
Assigns $k to a string, which always returns true, because any string other than an empty one ("") is truthy. Try this:
if ($k === "Paralympics 2012") {
First things first, the <h1> is always displaying, opposite of what you're question states. It's always displaying due to the fact that you're doing an assignment of a non-false value with:
if ($k = "Paralympics 2012") {
Update that to use a comparison to fix that logic issue.
if ($k == "Paralympics 2012") {
Next, to get it to display above your results, you need to actually move that if-statement above the loop that echos the results. Try placing it in the if ($numrows > 0) { block, like this:
if ($numrows > 0) {
if ($k == "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
while ($row = mysql_fetch_assoc($query)) {
...