I am trying to echo $classname only once.
So it shows like this for example.
Puppy Dog
1st blah blah
2nd whoever
3rd extra
at present it shows like:
Puppy Dog
1st blah blah
Puppy Dog
2nd whoever
Puppy Dog
3rd extra
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<table>
<tr>
<td><strong><?php echo $classname ?></strong> </td><br>
</tr>
<tr>
<td><strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?></td>
</tr>
</table>
<?php }}} ?>
Use counter to check if it is already displayed:
$ctr = 0;
while{
$classname = $row['class_name'];
if($ctr == 0){
echo $classname;
$ctr++;
}
//display the rest
...
}
So, don't know why are you using <table> inside the while loop, this will print as per your no's of rows.
Here is the basic example, you can store the values in an array than use it with your HTML:
Example:
<?php
if ($result) {
$myarr = array();
while ($row = mysqli_fetch_assoc($result)) {
$myarr[$row['class_name']][] = $row; //store values into an array against each class in group
}
}
foreach ($myarr as $key => $value) {
echo "Class Name: ". $key."<br/>"; // will print class name
foreach ($value as $fvalue) {
echo "Placement: ".$row['placement']."<br/>";; // placement
echo "Dog Name: ".$row['dog_name']."<br/>"; // dog name
echo "Award: ".$row['award']."<br/>";; // award
}
}
?>
Other solution is using incremental variable in while loop as mentioned in other answers.
You can keep track record by index in while loop like :
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<table>
<tr>
<td><strong><?php if($i==1) { echo $classname; } ?></strong> </td><br>
</tr>
<tr>
<td><strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?></td>
</tr>
</table>
<?php $i++; }}} ?>
The Opening and Closing <Table> Tags should be outside your Loop if you expect to have just one Table. Even the <tr> Tags should encompass the <td> Tags if you wish to have rows containing 2 Cells like the Code below shows:
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query ($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ".
mysqli_error($connection), E_USER_ERROR);
?>
<table>
<?php
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<tr>
<td>
<strong><?php echo $classname ?></strong>
<!-- DO YOU NEED THIS <BR>TAG HERE? <br> -->
</td>
<td>
<strong><?php echo $placement, $award ?></strong><?php echo $dog_name ?>
</td>
</tr>
<!-- EXCEPT IF YOU WISH TO HAVE ONE COLUMN, THE ROW BELOW IS UNNECESSARY -->
<!--
<tr>
<td>
<strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?>
</td>
</tr>
-->
<?php
} // CLOSE THE WHILE LOOP;
} // CLOSE THE IF STATMENT;
?>
</table>
Related
I want to retrieve all mysql table data using this script:
<?php
//WHERE id_post = '$id_post'
$sq = mysql_query("SELECT * FROM article_comments ") or die(mysql_error());;
connect();
while($row = mysql_fetch_assoc($sq)){
$result[$row["parent_id"]][] = $row["id"];
}
$rowIsOpened = false; //Indicates whether a row is currently opened.
//I'm using $rowIsOpened because the row immediately after the rowspanned cell shouldn't be closed.
echo <<<HTML
<table style="border-color: black;border-style: solid;">
<thead>
<tr>
<th>Parent</th>
<th>Children</th>
</tr>
</thead>
<tbody>
HTML;
//Echo a bunch of HTML before actually looping
foreach ($result as $parent => $children) {
echo "<tr style='border-color: black;border-style: solid;vertical-align:top;'>";
echo "<td rowspan=";
echo count($children); //Span over <how many children are> rows
echo " style='border-color: black;border-style: solid;' >$parent</td>";
$rowIsOpened = true; //Row is opened
foreach ($children as $child) {
if (!$rowIsOpened) {
echo "<tr>";
} //Only open a row if row is not opened
echo "<td style='border-color: black;border-style: solid;'>$child</td>";
echo "</tr>";
$rowIsOpened = false; //Row is now closed. Ready for next iteration.
}
}
//Close the table tags etc.
echo <<<HTML
</tbody>
</table>
HTML;
?>
This script creates an output table like that
Parent Children
0 1
3
4
5
1 1
2
My problem is when i try to add the other data from the mysql table: comment, name, date etc.
I have to replace these numbers with:
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
I tried this but it does not work and i didn't got much about arrays....
A little explaining would help me understand the concept better :)
$id_post = "1";
$name = array();
$email = array();
$comment = array();
$date = array();
//WHERE id_post = '$id_post'
$sq = mysql_query("SELECT * FROM article_comments WHERE id_post = '$id_post' ") or die(mysql_error());;
connect();
while($row = mysql_fetch_assoc($sq)){
$result[$row["parent_id"]][] = $row["id"];
$comment[$row['id']] = $row['comment'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
// $grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
}
$rowIsOpened = false; //Indicates whether a row is currently opened.
//I'm using $rowIsOpened because the row immediately after the rowspanned cell shouldn't be closed.
echo <<<HTML
<table style="border-color: black;border-style: solid;">
<thead>
<tr>
<th>Parent</th>
<th>Children</th>
</tr>
</thead>
<tbody>
HTML;
//Echo a bunch of HTML before actually looping
foreach ($result as $parent => $children) {
echo "<tr style='border-color: black;border-style: solid;vertical-align: top;'>";
echo "<td rowspan=";
echo count($children); //Span over <how many children are> rows
echo " style='border-color: black;border-style: solid;width:400px;' >$parent
<div class='cmt-cnt'>
<img src='".$grav_url."' />
<div class='thecom'>
<h5>".$name."</h5><span data-utime='1371248446' class='com-dt'>".$date."</span>
<br/>
<p>
".$comment."
</p>
</div>
</div>
</td>";
$rowIsOpened = true; //Row is opened
foreach ($children as $child) {
if (!$rowIsOpened) {
echo "<tr>";
} //Only open a row if row is not opened
echo "<td style='border-color: black;border-style: solid;width:400px;'>$child</td>";
echo "</tr>";
$rowIsOpened = false; //Row is now closed. Ready for next iteration.
}
}
//Close the table tags etc.
echo <<<HTML
</tbody>
</table>
HTML;
?>
You can add the entire result array to your parent array like this:
// I like to declare my variables and arrays
$results = array();
while ($row = mysql_fetch_assoc($sq)){
// I don't like to assume that I can append to array indexes that don't exist
if (!array_key_exists($row['parent_id'], $results)){
$results[$row['parent_id']] = array();
}
$results[$row['parent_id']][] = $row;
}
Then when you output, you can do this:
foreach ($results as $parent_id => $children){
// I'm leaving out the table because this is just for an example
echo $parent_id . '<br>';
foreach ($children as $child){
echo ' - ' . $child['commment'] . '<br>';
echo ' - ' . $child['date'] . '<br>';
}
}
I need to select some data from mysql and echo them into a table,
I have 20 entries which I want to echo them into 5by4 table I can select them like this:
<?php
$sql = "SELECT player FROM `prize` WHERE inviter='$player'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
?>
<table style="width: 100%;border:1px">
<tr> <td class="auto-style3">
<?php
while($row = $result->fetch_assoc()) {
?>
<?php echo "<br>". $row["player"].""; ?>
<?php
}}
?>
</td> </tr> </table>
it gives me something like this:
but I want it like this:
Can anyone help?
try it like this, using $count to count your item in array. and after 5 items have been echoed, then you put <tr> to echo in new row
<?php
$count=0;
echo "<table>";
while($row = $result->fetch_assoc()) {
if($count==0) {
echo "<tr>";
}
$count++;
echo "<td>".$row["player"]."</td>";
if($count==5) {
echo "</tr>";
$count=0;
}
}
echo "</table>";
?>
I changed your code to add a counter and close the tag every five records, this is the result:
<?php
$sql = "SELECT player FROM `prize` WHERE inviter='$player'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
?>
<table style="width: 100%;border:1px">
<tr>
<?php
$counter=0;
while($row = $result->fetch_assoc()) {
if($counter == 4){
echo '</tr><tr>';
$counter=0;
}
?>
<td><?php echo $row["player"].""; ?></td>
<?php
$counter++;
}}
?>
</tr> </table>
I have several MySQL tables that are dynamically generated into a html table one table at a time through the code below. However, the tables don't have the same columns. i.e. One table has a description column, whereas the other does not.
Is the following code the best way to have all the possible MySQL columns among the various tables in the script but only show the MySQL columns that exist for the selected table? I feel like I'm redundant by writing "isset" for every column. Thanks!
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
?>
<table>
<tr>
<?php if(isset($row['name'])){ ?>
<td><?php echo $row['name'];?></td>
<?php } ?>
<?php if(isset($row['description'])){ ?>
<td><?php echo $row['description']?></td>
<?php } ?>
</tr>
</table>
You might want to make your code adapt to the fields in the result set:
<?php
$result = mysqli_query($con,$query);
$fields = mysqli_fetch_fields($result);
$myaliases = array(
'column_id' => 'id'
);
?>
<table>
<tr>
<?php foreach ($fields as $field): ?>
<th><?php echo $myaliases[$field->name] ?: $field->name; ?></th>
<?php endforeach; ?>
</tr>
<?php while($row = mysqli_fetch_array($result)): ?>
<tr>
<?php foreach ($fields as $field): ?>
<td><?php echo $row[$field->name]; ?></td>
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
Re comments:
I've added code above to print a table row for column headings.
I've also included an example of mapping a field name column_id to a table heading id in the output. If I define no alias for a given column, it defaults to the original field name by using the PHP 5.3 operator ?:
You could alternatively define column aliases in your SQL query like SELECT column_id AS id ...
See http://www.php.net/manual/en/mysqli-result.fetch-fields.php
You can foreach the array instead.
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
If you need to print labels you can also use an associative array and an additional iteration to do that as well.
<?php
$query = " SELECT * FROM $tablename ";
$keys = array('name' => 'Name Label', 'description' => 'Description Label');
$query_select = mysqli_query($con,$query);
$i = 0;
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<?php if($i == 0) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><b><?=$keys[$key]?></b></td>
<?php } //Endforeach ?>
</tr>
<?php } $i++; //Endif ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
You could just loop through the results. However, that would not perform any checks. Most likely, you'll have to do something like this, depending on what you're actually getting from the database.
<?php foreach ($row as $field): ?>
<?php if ($field): ?>
<td><?php echo $field; ?></td>
<?php endif; ?>
<?php endforeach; ?>
Edit: In keeping in line with the comment you added above, you could simply remove the if clause.
not sure if this is what you need,
but you can use indexes instead for the column instead of names:
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
echo $row[0] ." ".$row[1]." ".$row[2]
}
?>
mysql_fetch_array
possible formating:
<table>
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) { ?>
<tr>
<?php for(var $i=0; $i < count($row); $i++){
echo "<td>". $row[i] ."</td>";
} ?>
</tr>
<?php } ?>
</table>
I have a script that creates a basic table layout structure and I'm trying to use AJAX with jQuery to input the output of that script into a TinyMCE textarea. I wrote the script in PHP and it works perfectly well if I open up the script directly.
What I'm trying to do is let the user choose something from a dropdown (in this case, a product) and it return a table filled with the relevant data for that product. I use the following script to insert it into the textarea:
$('#product_id').change(function(e) {
product_id = $(this).val();
$.ajax({
url: 'http://<? echo $_SERVER['HTTP_HOST']; ?>/includes/ajax.php',
type: 'POST',
data: { product_choice: true, product_id: product_id },
success: function(data) {
$('#mce_1').val(data);
}
});
});
'data' does return but when it's placed in the tinyMCE textarea, it shows the following error(the script carries on and outputs the table):
Warning: Invalid argument supplied for foreach() in /home/sites/very-dev.co.uk/public_html/cms/includes/ajax.php on line 71Warning: Invalid argument supplied for foreach() in /home/sites/very-dev.co.uk/public_html/cms/includes/ajax.php on line 100
Those two foreachs which error are:
foreach($product_data as $key=>$product): and foreach($product_data as $product):
// Connect to database
$link = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
// check connection //
if (mysqli_connect_errno()):
return printf("Connect failed: %s\n", mysqli_connect_error());
endif;
$col_qry = mysqli_query($link,"
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'cms_plugins_products_models'
AND column_name != 'id'
AND column_name != 'product_id';")
or die(mysqli_error($link)
);
while($col_row = mysqli_fetch_object($col_qry)):
$col_names_array[] = $col_row->column_name;
endwhile;
$qry = "SELECT product.name AS product_name, product.id, model.*, image.src AS thumb
FROM cms_plugins_products AS product
LEFT JOIN cms_plugins_products_models AS model
ON (product.id=model.product_id)
LEFT JOIN cms_plugins_products_images AS image
ON (product.id=image.product_id)
AND (image.is_thumb=1)
WHERE product.id='" . $_GET['product_id'] . "'";
$result = mysqli_query($link, $qry) or die(mysqli_error($link));
while($row = mysqli_fetch_object($result)):
foreach($col_names_array as $column):
$columns = explode('_', $column);
if($column != 'name' && $column != 'description'):
$components_qry = "SELECT name
FROM cms_plugins_products_components_" . $columns[0] . "
WHERE id='" . $row->$column . "'";
$components_result = mysqli_query($link, $components_qry) or die(mysqli_error($link));
$components_row = mysqli_fetch_object($components_result);
endif;
if($columns[0] == 'name'):
$product_data[$row->product_name][$row->name][$columns[0]] = $row->name;
elseif($columns[0] == 'description'):
$product_data[$row->product_name][$row->name][$columns[0]] = $row->description;
else:
$product_data[$row->product_name][$row->name][$columns[0]] = $components_row->name;
endif;
endforeach;
$thumb = $row->thumb;
endwhile; ?>
<table>
<thead>
<tr>
<th></th> <?
$i = 0;
foreach($product_data as $key=>$product):
foreach($product_data[$key] as $key2=>$model): ?>
<th <? if($i == 1): echo 'id="recommended"'; endif; ?>> <?
switch($i):
case 0:
echo 'Basic';
break;
case 1:
echo 'Mid';
break;
case 2:
echo 'Pro';
break;
endswitch; ?>
<div>
<img alt="<? echo $key; ?>" src="http://cms.very-dev.co.uk<? echo $thumb; ?>">
</div>
<h5><? echo $key2; ?></h5>
<p><? echo $product_data[$key][$key2]['description']; ?></p>
<a>Customise?</a>
</th> <?
$i++;
endforeach;
endforeach; ?>
</tr>
</thead>
<tbody> <?
foreach($product_data as $product):
$i = 0;
foreach($product as $model):
foreach($model as $key2=>$component): ?>
<tr> <?
if($key2 != 'name' && $key2 != 'description'): ?>
<td><? echo $key2; ?></td> <?
foreach($product as $key=>$model): ?>
<td><? echo $product[$key][$key2]; ?></td> <?
endforeach;
endif; ?>
</tr> <?
endforeach;
if($i == 0): exit(); endif;
$i++;
endforeach;
endforeach; ?>
</tbody>
</table>
It's probably quite a simple problem that I'm not seeing, any help on this one?
After looking at the code more carefully, it was a simple error. I was using a GET for the product_id but upon include that of course isn't set so it's breaking down but doesn't error out because of it being an include. Fixed simply by sending the GET variable along.
I have a PHP/MySQL News system which displayes the newest news article on the home page and a full list on a news page.
The newest article bit works but, my problem is that whenever i try to echo all the news article on the news page it either repeats the same or outputs one and nothing else.
**MySQL Information**
id INT AUTO_INCREMENT,
author VARCHAR(xxx),
title VARCHAR(xxx),
message TEXT,
date TEXT,
time TEXT,
PRIMARY KEY(id)
This is the insertion page (news_center.php)
<form action='/?module=admin&n=news_center_ac' method='post'>
<table align="center" width="68%">
<tr>
<td>Title</td>
<td><input style="width:100%;" type='text' name='news_title' /></td>
</tr>
<tr>
<td height="57">Message</td>
<td><input style="width:100%; height:100%;" type='text' name='news_message' /></td>
</tr>
<tr>
<td colspan='2'><input type='submit' /></td>
</tr>
</table>
This is news_center_ac.php
<?php
$conn = mysql_connect(*Connection Information*) or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$author == $_SESSION['name'];
if(!empty($_POST['news_title']) || !empty($_POST['news_message']))
{
if(!empty($_POST['news_title']) && !empty($_POST['news_message']))
{
$date = date( 'jS F Y' );
$time = date( 'H:i' );
$query = "INSERT INTO news (id, author, title, content, date, time) VALUES('', '".$author."', '".$_POST['news_title']."', '".$_POST['news_message']."', '".$date."', '".$time."')" or die(mysql_error());
$insert = mysql_query($query) or die(mysql_error());
echo '<p>Successful News Update “'.$_POST['news_title'].'”';
}
else
{
echo '<p>Please fill in all fields</p>';
}
}
?>
This is the Output on the news page (/news/index.php)
<?php
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
$output = mysql_fetch_array($news);
?>
*CONTENT*
<?php
foreach ($output as $value) {
echo "<p> “" .$output['content'];
echo "”";
echo "Posted:" .$output['date'];
echo " " .$output['time'];
}
?>
I just want it to output each news article in turn i can sort out the formatting later once it works.
You are misusing mysql_fetch_array(). It needs to be called in a loop, as it only returns one row at a time.
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
EDIT Added htmlentities() calls to convert html special characters
while ($row = mysql_fetch_array($news)) {
echo "<p> “" . htmlentities($row['content']);
echo "”";
echo "Posted:" . htmlentities($row['date']);
echo " " . htmlentities($row['time']);
}
Rewrite it this way:
<?php
while($output = mysql_fetch_array($news)) {
echo "<p> “" .$output['content'];
echo "”";
echo "Posted:" .$output['date'];
echo " " .$output['time'];
}
?>
When you call output first, it is only returning one value, this will loop through all.
try /news/index.php
<?php
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
while($output = mysql_fetch_assoc($news)) {
echo "<p> “" .$output['content'];
echo "”";
echo "Posted:" .$output['date'];
echo " " .$output['time'];
}
?>
Shouldn't the last foreach loop use $value, ie
<?php
foreach ($output as $value) {
echo "<p> “" .$value['content'];
echo "”";
echo "Posted:" .$value['date'];
echo " " .$value['time'];
}
?>