print all words before a specific character - php

Im having a problem with my function.
The user is able to post text to the page and set categories to the article.
categories that is set is saved in mysql in this way: categorie1,categorie2,categorie3
So, I want my visitors to be able to choose categories by providing a list with all categories.
This is how im thinking:
<?php
$sql02 = "SELECT * FROM article ORDER BY id";
$result02 = mysql_query($sql02);
while($rad02 = mysql_fetch_array($result02))
{
?>
<?php
$before = "<li><a href='index.php?p=cmd&kat=TEST'>";
$string = $rad02["kategori"];
$newstring = str_ireplace(",", "<br>", $string);
$kat = $newstring;
?>
<li><a href='index.php?p=cmd&kat=<?php echo $kat; ?>'><php echo "$kat"; ?></a></li>
<?php
}
?>
But that does not work.. what am I doing wrong?

You don't need $kat = $newstring; and when you said echo "$kat"; you shouldn't put $kat into ""
Hope this helps

If every categorie has it's own id you can do this than with foreach loop like this
while($rad02 = mysqli_fetch_array($result02)){
$rads[] = $rad02;
}
foreach($rads = $rad02){
?>
<li><a href='index.php?p=cmd&kat=<?php echo $rad02['kategori']; ?>'><?php echo $rad02['karegori']; ?></a></li>
<?php } ?>

Related

How can i replace a string in php url

i made a search box which use $_GET method. I search for category and size.
When the category search submitted my url becomes:
index.php?category=1
through:
<li class=""><?php echo $category['name']; ?></li>
When size submitted my url is:
index.php?category=1&size=1
through:
<li id="">
<?php echo $size['name']; ?>
</li>
When i search for another size i have:
index.php?category=1&size=1&size=2
How can i just replace the size instead of adding it again in my url?
You have to use http_build_query function to build your URL from the associative array of parameters. And try to avoid doing it directly in a template. Move this code at least to the controller level.
// Somewhere at the controller
$category = ...;
$size = ...;
$searchParams = array();
if (!empty($category)) {
$name = $category['name'];
$searchParams['category'] = $category['id'];
}
if (!empty($size)) {
$name = $size['name'];
$searchParams['size'] = $size['id'];
}
$searchQuery = http_build_query($searchParams);
// Somehow pass it to the template
$this->addViewVar('searchUrl', $_SERVER['REQUEST_URI'] . $searchQuery);
$this->addViewVar('searchName', $name);
And in the template just use searchUrl variable:
<li class=""><?php echo $searchName; ?></li>
Another way to accomplish this task, if you don't have a separate controllers level, it's to create special functions build_search_url() and search_name():
function build_search_url($path, $category = null, $size = null) {
$searchParams = array();
if (!empty($category)) {
$searchParams['category'] = $category['id'];
}
if (!empty($size)) {
$searchParams['size'] = $size['id'];
}
$searchQuery = http_build_query($searchParams);
return $path . $searchQuery;
}
And then use it like this:
<li class="">
<a href="<?php echo build_search_url($_SERVER['REQUEST_URI'], $category, $size); ?>">
<?php echo search_name($category, $size); ?>
</a>
</li>
Use
<?php echo $_SERVER['PHP_SELF'];?>
Instead of
<?php echo $_SERVER['REQUEST_URI'];?>
REQUEST_URI is adding query strings to your request.
Where as PHP_SELF gives plain file name e.g. index.php.
Easiest way IMHO:
Set the new value for the index in $_GET (or a copy, if you don’t want to manipulate the original array) – and then use http_build_query to create a new query string from that.
You should call a function in you "href" tag.
Inside, use http_build_query($array) to reconstruct the array.
$data = array('category' => $_GET['category']);
$data['size'] = $_GET['size'] ? $_GET['size'] : NEW_SIZE;
function getQuery($data) {
return http_build_query($data);
}
You can also use $_SERVER['REQUEST_URI'], but I'm not sure that this function will replace your item value instead of adding it to the end of the query.

Getting last record value only

I am getting only the last element value, like in my case i am trying to get value of $dwnld_name
but don't know where i am missing, so only getting download name for the last record
<?php
global $cat_id;
$dwnld_sql = "SELECT * FROM wp_dm_downloads";
$dwnld_qry = mysql_query($dwnld_sql);
while($dwnld_row = mysql_fetch_array($dwnld_qry)){
echo $link = $dwnld_row['link'];
echo $dwnld_name = $dwnld_row['name'];
$cat_id = $dwnld_row['category'];
}
?>
<?php
$sql = "SELECT * FROM wp_dm_category";
$myquery = mysql_query($sql);
echo '<ul>';
while($row = mysql_fetch_array($myquery)){
$x = $row['name'];
echo $x_id = $row['id'];
?>
<li><a href="#"><?php echo $x; ?>
<?php if($x_id == $cat_id) { ?>
<ul>
<li><?php echo $dwnld_name; ?></li>
</ul>
<?php } ?>
</a></li>
<?php echo "<br/>";
}
echo '</ul>';
?>
It is because, you are taking the values from loop in strings.
Everytime loop runs, it overwrites the values by recent values.
You can create an array and append values to that and loop through that array using foreach
Corrected Code:
<?php
global $cat_id;
$dwnld_sql = "SELECT * FROM wp_dm_downloads";
$dwnld_qry = mysql_query($dwnld_sql);
$downloads = array();
while($dwnld_row = mysql_fetch_array($dwnld_qry)){
$downloads['link'] = $dwnld_row['link'];
$downloads['dwnld_name'] = $dwnld_row['name'];
$downloads['cat_id'] = $dwnld_row['category'];
}
?>
Now, loop through $downloads array.
Note: Do not use mysql_ functions are they are deprecated and will be removed in future versions of PHP.
You need to echo $dwnld_name in the loop, or save names into array.
With this solution you overwrite $dwnld_name variable in each loop and as a result after the loop you have the last record.

How to change loadObjectList() item positions?

I tried to change the positions of the loadObjectList(). but it is not working. can anyone help me to solve this problem?
This is the code i used.
$catID = 8;
//echo $catID;
$doc = JFactory::getDocument();
$page_title = $doc->getTitle();
$db = JFactory::getDBO();
$db->setQuery("SELECT title,alias FROM #__content WHERE catid = ".$catID);
$articles = $db->loadObjectList(); ?>
<div>
<?php foreach($articles as $article){
$title = $article->title;
if($title == $page_title){?>
<h4><?php echo $article->title; ?></h4>
<?php
}else{ ?>
<h4><?php echo $article->title; ?></h4>
<?php }
}
?>
</div>
what i want to do is, i want to display the page title as the first element of the list. Thats means if condition's item should display first.
can anyone helpe me?
A quick dry solution is to add 2 foreach loops and first display the value if condition match and after the rest values.
<?php
foreach($articles as $article){
$title = $article->title;
if($title == $page_title){
echo '<h4>'. $article->title .'</h4>';
}
}
foreach($articles as $rest_articles){
$title = $rest_articles->title;
if($title != $page_title){
echo '<h4>'. $rest_articles->title .'</h4>';
}
}
?>
A better solution is to store values in a new array and display them afterwards.
Hope this helps
Just had a double take here. Multiple foreach loops can be used, however are not required. Try the following:
<?php
foreach($articles as $article) {
$title = $article->title;
$alias = $article->alias;
if($title == $page_title) {
echo '<h4>'. $title .'</h4>';
}
else {
echo '<h4>'. $title .'</h4>';
}
}
?>

How to ACF list label not value

Im using ACF repeater to generate results form a list, which is all working fine. But, rather than display the list value, I want to display the list label.
Here is the code:
<ul class="notifications-content">
<?php while(has_sub_field('notification')):
$house = get_sub_field('house');
$year = get_sub_field('year');
$date = DateTime::createFromFormat('Ymd', get_sub_field('date'));
$newDate = date("D j F", strtotime($date->format('d-m-Y')));
?>
<li class="<?php echo safe_url($house); ?> <?php echo $year; ?>">
<h2 class="black"><?php echo str_replace($replace, '', get_sub_field('message')); ?></h2>
<h3 class="interstatebold white uppercase"><?php echo $house; echo $year ? ", $year" : ''; echo ' | '.$newDate; ?></h3>
<?php echo get_sub_field('urgent') ? '<div class="circle"></div>' : ''; ?>
</li>
<?php endwhile; ?>
</ul>
How do I get the label?
Take a look at this official documentation about get_field_object
There is a usage example in the bottom:
Get a field object and display it with it's value
$field_name = "text_field";
$field = get_field_object($field_name);
echo $field['label'] . ': ' . $field['value'];
You can use this in your repeater to grab that field_object you want and display the label.
Instead of using has sub field, use get_field('platforms'). Put respective repeater field name in place of 'platforms.' Platforms is the name of repeater field.
By using foreach loop with key=>value pair, you get key as well as value.
Try using following code.
$platforms = get_field('platforms');
foreach( $platforms as $val ){
foreach($val as $key=>$v){
echo $key.'=>'.$v.'<br>';
}
}
You can use it the same way you would call the field values by passing it through these functions (add to functions.php):
function get_field_label($slug) {
$field = get_field_object($slug);
return $field['label'];
}
Usage:
<?php echo get_field_label('field-slug'); ?>
function the_field_label($slug) {
$field = get_field_object($slug);
echo $field['label'];
}
Usage:
<?php the_field_label('field-slug'); ?>

PHP Code efficiency in menu

I currently have some VERY long winded code for the menu I use on my site.
My website
It's almost 2000 lines long lol. I think I may be able to use a switch but I've tried and cannot implement it to work properly.
On each menu when you click a button it stays highlighted, telling the user that they are on that page. The only way I could get this to work was like so...
if($subject == 'art') {
echo '<div id="spacer2"><br></div>';
echo '<div class="idName2" id="menu2">';
echo 'All';
echo '<div id="spacer2"><br></div>';
echo '</div>';
echo '<div class="idName3" id="menu3">';
echo 'Art';
echo '</div>';
echo '<div class="idName2" id="menu2">';
echo 'Biology';
echo 'English';
echo 'Chemistry';
echo 'Mathematics';
echo 'History';
echo 'Religion';
echo 'Geography';
echo 'Music';
echo 'Philosophy';
echo 'Psychology';
echo 'Economics';
echo 'Sociology';
echo 'Technology';
echo 'Electronics';
echo 'Food';
echo 'Law';
echo 'Politics';
echo '</div>';
}
elseif($subject == 'biology') {
and then there's however many 'elseifs' as there are menu items, which ends up totalling to 2000 lines of code which is obviously very inefficient and it also makes it unbelievably time consuming to change anything... can someone point me in the right direction in what I need to do please!
Navigation is always a pain. Here is a simple solution that might help.
Put everything in an array, like this:
$menu = array(
'All' => '/browse ...',
'Art' => '/browse ... art',
'Biology' => '/browse ... biology',
// etc.
)
Then, you can build all the links based on the current subject:
$subject = 'Art';
foreach ($menu as $title => $url) {
if ($title == $subject) {
echo "<b>$title</b><br>\n";
} else {
echo "$title<br>\n";
}
}
This is a rather simplistic solution, but it can be extended to create a more complicated menus structure.
Another solution you could look at is Zend_Navigation.
http://framework.zend.com/manual/en/zend.navigation.introduction.html
What about something like:
$subjects = array('art', 'biology', 'english', 'chemistry' /*, etc */);
foreach ($subjects as $current_subject)
{
if ($current_subject == $subject)
{
//write it the id="menu3" way
}
else
{
//write it another way
}
}
You can transform 'biology' to 'Biology' using the ucfirst function.
Also note that there can't be two or more elements with the same ID (menu2 in your case).
You should use an array to represent your menus. Even better, you could place it in a resource file (xml would be preferable), but explaining that exceeds the scope of this answer (nonetheless, you should look into it). Using an external resource for the menu has the added benefit that you can change your menu structure without modifying any code.
Sticking to the simple approach, this is how you should represent your menu without an external resource:
$menus = array('Art', 'Biology', 'English', ...);
You can generate the "A"-"Z" submenus with a simple range command: range('A', 'Z')
So your code echoing the menus would be something like:
<?php
$current_letter = $_REQUEST['letter'];
$current_menu = $_REQUEST['menu'];
$letters = range('A', 'Z');
foreach($letters as $letter) :
$class = $current_letter == $letter ? 'class="active"' : '';
?>
<a <?php echo $class; ?> href="browse.php?letter=<?php echo $letter; ?>&menu=<?php echo $current_menu; ?>&listtype=<?php echo $listtype"><?php echo $letter; ?></a>
<?php endforeach; ?>
This displays the top menubar (A-Z links). For the side menu, here is how to display your categories:
<?php
foreach($menus as $menu) :
$class = $current_menu == $menu ? 'class="active"' : '';
?>
<a <?php echo $class; ?> href="browse.php?letter=<?php echo $current_letter; ?>&menu=<?php echo $menu; ?>&listtype=<?php echo $listtype"><?php echo $menu; ?></a>
<?php endforeach; ?>
Haven'tested it, but apart from possible typos this approach should work for you.
Btw, please don't throw things at me for not validating input and using $_REQUEST directly. It should be done, but that is a whole other topic.

Categories