How can i echo the first row of a query result 2 or more times, outside and inside of the while loop?
The following code just echo the first row outside of loop and doesn't allow to echo again inside of loop
case '1':
$db->Query("SELECT titulo_video,subtitulo_video,youtube_id,nome_norma FROM videos");
echo "<h2>" . $db->Row()->nome_norma . "</h2>";
while ($row = $db->Row()) {
echo "<h3>" . $row->titulo_video . "</h3>";
echo "<p>" . $row->subtitulo_video . "</p>";
}
break;
I want the data as follows:
<h3>row 1 - colum 1</h3>
<h2>row1 - colum 2</h2>
<p>row 1 - colum 3</p>
<h2>row2 - colum 2</h2>
<p>row 2 - colum 3</p>
<h2>row3 - colum 2</h2>
<p>row 4 - colum 3</p>
You can fiddle with the loops a bit.
if ($row = $db->Row ())
{
echo '<h2>' ...;
do
{
echo '<h3>' ...;
echo '<p>' ...;
} while ($row = $db->Row ());
}
Make use a Sentinel value:
$i = 0;
while ($row = $db->Row()) {
echo "<h3>" . $row->titulo_video . "</h3>";
echo "<p>" . $row->subtitulo_video . "</p>";
if($i==0){
echo "<h3>" . $row->titulo_video . "</h3>";
echo "<p>" . $row->subtitulo_video . "</p>";
}
$i++;
}
If you really want to treat the first row differently, handle it entirely outside of the loop, rather than including a conditional in your while loop, it's cleaner to handle it like this:
$first_row = $db->Row();
echo "<h2>" . $first_row->nome_norma . "</h2>";
echo "<h3>" . $first_row->titulo_video . "</h3>";
echo "<h3>" . $first_row->subtitulo_video . "</h3>";
while ($row = $db->Row()) {
echo "<h3>" . $row->titulo_video . "</h3>";
echo "<p>" . $row->subtitulo_video . "</p>";
}
break;
Related
I'm trying to re-write this code so that it goes with the columns that are going to be user-defined. With this, my challenge consists of
a) Needs to select random starting item from array
b) Select the next random color from the original array that is not equivalent to the most recent items selected based the number: $intNotesColumn + 1
I was thinking a do-while statement nested inside another was appropriate for this but am unsure how to go about this. Here is my code so far:
$metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
$metroUIcolorsLength = count($metroUIcolors);
$intNotesColumn = 3; // This will be user-defined later
// Now I query the SQL database to get my base-code
if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
. '<tr>'
. '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>'
. '</tr>'
. '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">"
. "<h2>" . $row["username"] . '</h2><br />'
. "<p class='notes'>" . $row["notes"] . "</p>"
. "<p class='footnotes'>"
. "<br />Last Reset: " . $row["lastReset"]
. '<br />Last Update: ' . $row['lastUpdate']
. '<br />SessionID: ' . $row["sessionID"]
. "<br />Counter = " . $counterRank . "</td>". '</p>';
if ($counterRank % $intNotesColumn == 0)
{
echo '</tr><tr>';
}
$counterRank++;
}
echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}
Then, why don't you do it order picking one color at a time. You could use shuffle() so that there will be a different starting color everytime.
<?php
$counterRank = 1;
// shuffle the array
shuffle($metroUIcolors);
while($row = $result->fetch_assoc()) {
$rand_color = $counterRank % $metroUIcolorsLength;
echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";
// everything else
$counterRank++;
}
?>
If you insist on doing the way you said, you may create an array $colorCount which has color codes as keys and count as values.
<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);
while($row = $result->fetch_assoc()) {
do {
$rand_color = $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
} while ($colorCount[$rand_color] > 5);
echo "<td bgcolor=" . $rand_color. ">";
// everything else
$counterRank++;
$colorCount[$rand_color] += 1;
}
?>
How to add in this code multiple ID category.
I have in kategorija_id 5 arrays:
1 - News
2 - Magazine
3 - Kokursi
4 - Grantovi ect..
I whant to display just key 1 and 2
when i add array i just print the first key
$kategorija = Kategorija::model()->findByPk($item->kategorija_**id=1,2**);
Thnx :)
Code update:
<div class="carousel-inner">
<div class="item active">
<ul class="thumbnails">
<?php
$i = 0;
$lastDefault = 0;
foreach ($ids as $itemId) {
$item = InfoPaket::model()->findByPk($itemId);
$kategorija = Kategorija::model()->findByPk($item->kategorija_id);
if ( $i % 3 == 0 && $i > 0 ) {
echo "</ul></div><div class='item'><ul class='thumbnails'>";
}
$imageUrl = $_SERVER['DOCUMENT_ROOT'] . Yii::app()->baseUrl . "/images/infopaket/" . $item->slika;
if ( !file_exists($imageUrl) || empty($item->slika)) {
if ( $lastDefault == 0 ) {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/info_paket.png";
$lastDefault = 1;
} else {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/info_paket_redv2.png";
$lastDefault = 0;
}
} else {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/" . $item->slika;
}
echo "<li class='span3 thmb-elem'>";
echo "<div class='thumbnail right-caption image'>";
echo "<a class='img-link' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'><img class='img-class' src='$imagePath'></a>";
echo "</div>";
echo "<div class='caption caption-link'>";
echo "<div class='naziv'><img class='arrow-img' src='". Yii::app()->getBaseUrl() . "/themes/shadow_dancer/images/arrow.png'> " . strtoupper($kategorija->naziv) . "</div>";
echo "<p><a class='naslov' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'><strong>" . $item->naslov . "</strong></a></p>";
echo "</div>";
echo "</li>";
$i++;
}
?>
</ul>
</div>
</div>
I solve this problem adding this line of code
if ($item->kategorija_id==3 || $item->kategorija_id==4 ) {
now code look like this and it works perfect.
<?php
$lastDefault = 0;
foreach ($ids as $itemId) {
$item = InfoPaket::model()->findByPk($itemId);
$kategorija = Kategorija::model()->findByPk($item->kategorija_id);
if ($item->kategorija_id==3 || $item->kategorija_id==4 ) {
echo '<li>';
echo '<img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/infopaket/info_paket.png" />';
echo '<h2>';
echo strtoupper($kategorija->naziv);
echo '</h2>';
echo '<h1>';
echo "<a class='naslov' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'>";
echo $item->naslov;
echo '</h1>';
echo '</a>';
echo '</li>';
}
}
?>
findByPk() accepts first argument as array too. So you can do
category::model()->findByPk(array('1', '2'));
Also, $item->category_id will return only single entry. If your item has multiple categories, than set up relations to categories and then get categories ID's with
CHtml::listData($item->categoriesRelationName, 'id', 'id');
can use function ($data){return $data->attribtues} too ---------^--- to get all attributes of model
Wondering if someone could help give me a push in the right direction, I am building a search function (php and mysql) which will display search results and highlights keywords that the user has searched for. at the moment I grab the search criteria that the user has entered and query that against the database which works fine to get the desired results. the problem I have is
$highlight = preg_replace("/".$_GET['criteria']."/", "<span class='highlight'>".$_GET['criteria']."</span>", $_row['name']);
This will only highlight a phrase and not individual keywords. so for example if the document was called "Hello world" and the user typed this exactly it would highlight no problem however if the user typed "world hello" it will not highlight anything. I thought it would be a good idea to take the search criteria and use explode and check each word individually but this seems to fail as well. here is my query and how I am displaying results
$sql = "SELECT *
FROM uploaded_documents
WHERE dept_cat = 'procedures'
AND cat =:cat
AND keywords REGEXP :term ";
$result->execute(array(':cat' => $_GET['category'],':term' => $_GET['criteria']));
//display results
while($row = $stmt->fetch()){
$explode_criteria = explode(" ",$_GET['criteria']);
foreach($explode_criteria as $key){
$highlight = preg_replace("/".$key."/", "<span class='highlight'>".$key."</span>", $row['name']);
echo '<td><a target="_blank" href="'.$row['url'].'">'.$highlight.'</a></td>';
echo '<td>'.$row['version'].'</td>';
echo '<td>'.$row['cat'].'</td>';
echo '<td>'.$row['author'].'</td>';
echo '<td>'.$row['added'].'</td>';
echo '<td>'.$row['auth_dept'].'</td>';
echo '<td>';
}
}
For the sake of length I have omitted code here and tried to keep it minimal, I have been trying to base my work on the following post
highlighting search results in php/mysql
I think my first problem is the foreach loop in the while loop duplicating results but I cant think of a way around it.
Thanks in advance
In this block of code:
//display results
while ($row = $stmt->fetch())
{
$explode_criteria = explode(" ", $_GET['criteria']);
foreach ($explode_criteria as $key)
{
$highlight = preg_replace("/" . $key . "/", "<span class='highlight'>" . $key . "</span>", $row['name']);
echo '<td><a target="_blank" href="' . $row['url'] . '">' . $highlight . '</a></td>';
echo '<td>' . $row['version'] . '</td>';
echo '<td>' . $row['cat'] . '</td>';
echo '<td>' . $row['author'] . '</td>';
echo '<td>' . $row['added'] . '</td>';
echo '<td>' . $row['auth_dept'] . '</td>';
echo '<td>';
}
}
The loop is constantly referring to $row['name'], so the replacement is done, but the next time the loop happens it is replacing the next word on the original unmodified $row['name']
I think this should help you:
//display results
while ($row = $stmt->fetch())
{
$explode_criteria = explode(" ", $_GET['criteria']);
$highlight = $row['name']; // capture $row['name'] here
foreach ($explode_criteria as $key)
{
// escape the user input
$key2 = preg_quote($key, '/');
// keep affecting $highlight
$highlight = preg_replace("/" . $key2 . "/", "<span class='highlight'>" . $key . "</span>", $highlight);
echo '<td><a target="_blank" href="' . $row['url'] . '">' . $highlight . '</a></td>';
echo '<td>' . $row['version'] . '</td>';
echo '<td>' . $row['cat'] . '</td>';
echo '<td>' . $row['author'] . '</td>';
echo '<td>' . $row['added'] . '</td>';
echo '<td>' . $row['auth_dept'] . '</td>';
echo '<td>';
}
}
As you can see on http://www.mattmaclennan.co.uk/a2 ... when you hover over "New Motorcycles", it has the array numbers, and not the labels as required. Also, the categories need to be grouped into their IDs. Below is what I have tried.
<?
$output = mysqli_query("SELECT * FROM bikes, bikeTypes WHERE bikes.model_id = bikeTypes.model_id");
$result = array();
while($row = mysqli_fetch_array($output))
{
$result[] = $row;
}
//var_dump($result);
foreach ($result as $key => $val) {
echo "<li><a href='test.php?id=" . $val['model_id'] . "'>".$key.'</a><ul>';
echo "<li><a href='details.php?id=" . $val['bike_id'] . "'>" . $val['bikeName'] . "</a></li>";
echo '</ul>';
echo '</li>';
}
?>
The category field is called 'model'. Thanks for any help!
Thats because you're display the $key, instead of the $value.
<?
$output = mysqli_query("SELECT * FROM bikes, bikeTypes WHERE bikes.model_id = bikeTypes.model_id");
while($row = mysqli_fetch_array($output))
{
echo "<li><a href='test.php?id=" . $row['model_id'] . "'>".$row['???'].'</a><ul>';
echo "<li><a href='details.php?id=" . $row['bike_id'] . "'>" . $row['bikeName'] . "</a></li>";
echo '</ul>';
echo '</li>';
}
?>
As part of a project I have a form in which our clients can edit a list of the keywords in which we work on as part of their SEO.
This is the code I use to display the keywords we have for them on our database
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword". $counter .
"' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
What I don't know what do do is collect the data when the form is submitted into an email.
I have the PHP mail bit ready but struggling on this a bit.
Any help?
I'd recommend changing the code to this:
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword[]' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
You can then access all keywords in the target php file for your form (after submission) using $_POST['keyword'], eg
foreach($_POST['keyword'] as $key => $value) {
echo "Keyword #". $key." value: ". $value."<br />";
// or your code to build your message
}
Instead of naming the inputs like "keyword1", "keyword2", etc, just name them all "keyword[]". When the form is submitted, PHP will aggregate them all into an array.
To use the POST data (make sure your form is using POST):
<?php
$message = '<ol>';
foreach($_POST as $key => $post) {
$message .= "<li><strong>Keyword " . $key . ":</strong>";
$message .= " <span>" . $post . "</span>";
$message .= "</li>";
}
$message .= '</ol>';
// mail the message here.
?>
Brian and Ergo summary are right, but if you don't want to modify the code inside the while loop you could, at the end of that, insert an hidden input that holds the last $counter value. Then in the target php file (where you will send the email), you can load the POST fields (modifying what Stephen wrote):
<?php
$counter = (int)$_POST['counter'];
$message = '';
for($i = 1; $i <= $counter; $i++){
$key = $_POST['keyword'.$i];
$message .= "<p>";
$message .= "<strong>Keyword " . $key . " </strong></label>";
$message .= "<span> " . $post . "</span>";
$message .= "</p>";
}
// mail message here.
?>