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)) {
...
Related
I am trying to write a conditional if statement to get image caption if number of images match number of captions in the db row
code does work without if statement but fails to execute even if the condition returns true.
php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$individual_files = explode("|", $row["images_names"]);
$individual_text = explode("_", $row["image_text"]);
for ($file_number = 0; $file_number < sizeof($individual_files) - 1; $file_number++) {
if( count($individual_files) == count($individual_text)) {
echo "<li>";
echo "<img src='Blog-Albums/" . $row["sno"] . "/" . $individual_files[$file_number] . "' alt='gallery image'/>";
echo "<div class='slider-caption'><p style='color:#ffffff'>this is sample file</p></div>";
echo "</li>";
} elseif ( count($individual_files) != count($individual_text)) {
echo "<li><img src='Blog-Albums/" . $row["sno"] ."/". $individual_files[$file_number] . "' alt='gallery image'/><div class='slider-caption'><p></p></div></li>";
}
I am trying to store values from form radio to array. But problem which i am facing is that every time array 1st index is replaced with new value. I believe this is scope problem. I also tried to declare global array but no success.
Here is the code:
<?php
include_once("connection.php");
$c = new DBcon();
$c->startcon();
global $array; // not effecive
// $q = $_POST['t'];
// echo 'fff', $q;
$page = $_GET['page'];
echo 'pagesss', $page, 'ppp';
if ($page == "") {
$page = "1";
} else {
// If page is set, let's get it
$page = $_GET['page'];
}
// Now lets get all messages from your database
$sql = "SELECT * FROM quizes";
$query = mysql_query($sql);
// Lets count all messages
$num = mysql_num_rows($query);
// Lets set how many messages we want to display
$per_page = "2";
// Now we must calculate the last page
$last_page = $num;
echo 's', $num;
// And set the first page
$first_page = "1";
// Here we are making the "First page" link
echo "<a href='?page=" . $first_page . "'>First page</a> ";
// If page is 1 then remove link from "Previous" word
if ($page == $first_page) {
echo "Previous ";
} else {
if (!isset($page)) {
echo "Previous ";
} else {
// But if page is set and it's not 1.. Lets add link to previous word to take us back by one page
$previous = $page - 1;
echo "<a href='?page=" . $previous . "'>Previous</a> ";
}
}
// If the page is last page.. lets remove "Next" link
if ($page == $last_page) {
echo "Next ";
} else {
// If page is not set or it is set and it's not the last page.. lets add link to this word so we can go to the next page
if (!isset($page)) {
$next = $first_page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
} else {
$next = $page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
}
}
// And now lets add the "Last page" link
echo "<a href='?page=" . $last_page . "'>Last page</a>";
// Math.. It gets us the start number of message that will be displayed
$start = ($page * ($page - 1)) / $page;
echo 'start', $start;
echo 'page', $page;
// Now lets set the limit for our query
$limit = "LIMIT $start, $per_page";
// It's time for getting our messages
$sql = "SELECT * FROM quizes $limit";
$query = mysql_query($sql);
echo "<br /><br />";
// And lets display our messages
$i = 0;
$l = 0;
while ($row = mysql_fetch_array($query) or die(mysql_error())) {
$a = $row['A'];
echo '<form method="get" action="?page=".$next."">';
while ($row = mysql_fetch_array($query)) {
echo '<div class="boxed" >';
echo "\t" . '<tr><th>' .
$row['question'] . "<br>" .
'</th><th>' . "<input type='radio' name= 't[]' value='{$row['A']}'>" . $row['A'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['B']}'>" . $row['B'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['C']}'>" . $row['C'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['D']}'>" . $row['D'] . '</th>
</tr>';
echo '<input type="hidden" name="page" value="' . $next . '">';
echo '<input type="submit" name="submit"/>';
$i++;
echo '</div>';
echo '</div>';
}
echo '</form>';
if (isset($_GET['submit'])) {
$example = $_GET['t'];
foreach ($example as $value) {
$array[$i++] = ($value);
echo "$array[0] <br>"; // printing correct statement but replacing old values with new value everytime.
echo "$array[1] <br>"; // 0 values
echo "$array[2] <br>"; // 0 values
}
}
}
?>
I have seen these posts: PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] , PHP - define static array of objects but no help. Kindly help what should i do?
You cannot do
$array[$i++]
this will always be $array[1]
instead do
$i++;
$array[$i]= $value;
P.S. $array is a terrible name for a variable...
if (isset($_GET['submit'])) {
$example = $_GET['t'];
$i=0;
$arrayA = array();
foreach ($example as $value) {
$arrayA[$i] = ($value);
$i++;
}
print_r($arrayA);
}
if you do
$array[$i++] ;
it wont work , just try this and it wont replace your old value
$array[$i] = $value;
$i++;
You must increment your variable first, then use the variable as the array key.
Edit: this is what you're looking for:
$i = 0;
foreach ($example as $value) {
$array[$i] = $value;
$i++;
}
I was asked to modify existing code to allow multi-level page structure. Each page can have one parent, and one page can have multiple children.
I will present following code. My question is is there a more efficient way of doing this? I am hard-coding the number of levels that are reachable.
Is there easier way to do this automatically without hard coding? Recursion perhaps?
function createMenu($parents) {
foreach ($parents as $parent) {
$parentName = $this->getPagefromID($parent);
$kids = $this->areThereKids($parent);
if ($kids == "yes") {
echo "<ul class=\"children\">\n";
$query = "SELECT * FROM pages";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$thisparent = $row['Parent'];
$name = $row['Name'];
$id2 = $row['ID'];
if ($thisparent == $parent) {
echo "<li>" . $name . "</li>\n";
if($this->areThereKids($id2) == "yes") {
$children = $this->getMyKids($id2);
foreach($children as $kid) {
$info = $this->getPersonInformation($kid);
$kidid = $info[0]["ID"];
echo "<li>" . $info[0]['Name'] . "</li>\n";
// more sub
if($this->areThereKids($kidid) == "yes") {
$children1 = $this->getMyKids($kidid);
foreach($children1 as $kid1) {
$info1 = $this->getPersonInformation($kid1);
$kidid1 = $info1[0]['ID'];
echo "<li>-" . $info1[0]['Name'] . "</li>\n";
if($this->areThereKids($kidid1) == "yes") {
$children2 = $this->getMyKids($kidid1);
foreach($children2 as $kid2) {
$info2 = $this->getPersonInformation($kid2);
$kidid2 = $info2[0]['ID'];
echo "<li>--" . $info2[0]['Name'] . "</li>\n";
// No need for 6 levels.
}
}
}
}
}
}
}
}
echo "</ul>\n";
}
echo "</li>\n";
}
}
This would be more efficiently done with recursion.
Identify the steps of the code that are repeated and turn them into a subroutine. From your code, we have the following repeated unit:
(...)
if($this->areThereKids($id2) == "yes") {
$children = $this->getMyKids($id2);
foreach($children as $kid) {
$info = $this->getPersonInformation($kid);
$kidid = $info[0]["ID"];
echo "<li>" . $info[0]['Name'] . "</li>\n";
// more sub
if($this->areThereKids($kidid) == "yes") {
(...)
Turn that into a function (assuming you're working with an object):
function dealWithKids($par) {
if ($this->areThereKids($par) == 'yes') {
$children = $this->getMyKids($par);
foreach ($children as $kid) {
$info = $this->getPersonInformation($kid);
$kidid = $info[0]["ID"];
echo "<li>" . $info[0]['Name'] . "</li>\n";
// instead of repeating the same steps again,
// call the dealWithKids function here
$this->dealWithKids($kidid);
}
}
}
...and then call that function instead of the repeated units of code:
while ($row = mysql_fetch_assoc($result)) {
$thisparent = $row['Parent'];
$name = $row['Name'];
$id2 = $row['ID'];
if ($thisparent == $parent) {
echo "<li>" . $name . "</li>\n";
// instead of this:
// if($this->areThereKids($id2) == "yes") {
// do this:
$this->dealWithKids($parent);
}
}
I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";
I'm working on an online menu ordering system and I wanted to filter the data according to its category. I've tried to make it work with this code but it's only displaying one category.
**<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Scotch/Bourbon</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Brandy/Cognac</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Vodka/Gin/Tequila/Apertifs/Liqueur</a></li><br>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Beer/Softdrinks</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Cocktails</a></li>**
^ basically these are the categories and below is how display them.
**
<?php
$category = $_GET['choice'];
$category = str_replace('%', ' ', $category);
$query = "SELECT * FROM product_drinks WHERE drinks_cat = '" . $category . "'";
$result = mysql_query($query);
$total_records = mysql_num_rows($result); // the number of records in your result set
$num_cols = 2; // the number of columns
$num_rows = ceil($total_records / $num_cols); // the number of rows
$num = 0; // don't change this value, this is the first number of each record inside a record set
echo "<table style= 'cellpadding:8 width:100'>\n";
// next the loop for the table rows
for ($rows = 0; $rows < $num_rows; $rows++) {
echo "<tr bgcolor='black'>\n";
// this is the loop for the table columns
for ($cols = 0; $cols < $num_cols; $cols++) {
if ($num < $total_records) { // show records if available (reduce by one because the first record is no. "0" (zero)
// first create variables with the values of the current record
$title = mysql_result($result, $num, "drinks_name");
$clean_name = str_replace('_', ' ', $title);
$price = mysql_result($result, $num, "drinks_shot");
$price2 = mysql_result($result, $num, "drinks_bottle");
$category = mysql_result($result, $num, "drinks_cat");
$description = mysql_result($result, $num, "drinks_image");
$title = str_replace(' ', '%', $title);
echo "<td class='label'><a class='fancybox fancybox.ajax' href='food.php?drink=" . $title . "'>
<img src='" . mysql_result($result, $num, 'drinks_image') . "' class='masterTooltip' title= '" . $category . "'</a><br>";
echo "<td style='width:50%' class='desc'><b>" . $clean_name . "</b><br> Shot:<font style='color:#0072bc'> Php " . $price . "</font><br> Bottle: <font style='color:#724c0e'>Php " . $price2 . "</font></td>\n";
} else { // show an empty cell
echo "<td> </td>\n";
}
$num++; // raise the number by one for the next record
}
echo "</tr>\n"; // there are no more cols in this row, close the table row tag
}
echo "</table>\n"; // end of the region = closing tag for the table element
?>
**
I wish I could get over this wall. Please help~
First things first.
<?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?>
In the first chunk of code, you are using the same variable for all the links.
Are you passing different values for $category here. I believe you are not! and hence all the links are pointing to the same url.
You should use urldecode instead of str_replace('%', ' ', $category). (http://in2.php.net/urldecode)
Please indent your code so that it can be read and understood easily :)