I am echoing a list of areas covered from a database. The list has Headings and sub headings taken from the database,
$area_shire = '';
$area_district = '';
$area_name = '';
while($rows = mysql_fetch_array($query)):
if($rows['area_shire'] != $area_shire) {
echo '<h1>'.$rows['area_shire'].'</h1>';
$area_shire = $rows['area_shire'];
}
/* same for district using h2 and name using h3 */
endwhile;
I now want to make each result a hypertext url so i have added
$area_shire_url = str_replace(' ', '_', $area_shire);
$area_district_url = str_replace(' ', '_', $area_district);
$area_name_url = str_replace(' ', '_', $area_name);
and changed each echo to
echo '<a href=\"Tree_Surgery_'.$area_shire_url.'.php\"><h2>'.$rows['area_shire'].'<br></h2>';
$area_shire = $rows['area_shire'];}
/* same for district using h2 and name using h3 */
This has not worked at all?
I would rewrite the snipped as:
$area_shire = '';
$area_district = '';
$area_name = '';
while($rows = mysql_fetch_assoc($query)) {
if ($rows['area_shire'] != $area_shire) {
$area_shire = $rows['area_shire'];
$area_shire_url = 'Tree_Surgery_'.str_replace(' ', '_', $area_shire).'.php';
echo '<h2>'.$area_shire.'</h2><br>';
}
// same for district using h2 and name using h3
}
Your error seems to have been that you escaped the " while in a single-quoted string. When using ', php will echo all contained characters as-is; no escaping needed.
Note that I've also used mysql_fetch_assoc instead of mysql_fetch_array and rearranged the order of you HTML-tags to avoid nesting block-level elements inside inline elements.
I also choose to store the complete url in a variable, instead of just a part of it and combining it in the echo statement into the full url. This is, in my opinion, easier to read. Especially when you want to edit things later on.
'<a href=\"Tr
I don't think you need to escape the " since you're not using " to define your php statement.
You do not need to escape the double quotes as the text is not within double quotes. You also seem to have a } at the end of your code, unless this is not all of the code, this is not necessary.
I have not see this format or while loop, try changing it to this:
while($rows = mysql_fetch_array($query)){
// do stuff
}
More importantly, you have not ended your a tag. End your line with </a>
Related
I got the below code but at the moment it generates a string of results but with about 40+ empty spaces.
$user_ = JFactory::getUser();
$db = JFactory::getDBO();
$levels = JAccess::getAuthorisedViewLevels($user->id);
foreach($levels as $key => $level)
{
$query = 'SELECT title FROM #__pf_projects';
$query .= ' WHERE access = ' . $level . " AND TRIM(title) != ''";
$db->setQuery($query);
$projectlist = $db->loadResult($query).'<br>';
echo $projectlist;
}
At first I thought that array_filter() would be good here but as PatrickQ points out it is a string so the array filter won't work.
Then I adapted the code according to the answer from Don't Panic. This adapted code is what you can see above.
It returns now a list like this.
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
http://www.domain1.com
<br>
<br>
<br>
<br>
http://www.domain5.com
http://www.domain23.com
http://www.domain65.com
http://www.domain213.com
<br>
<br>
<br>
<br>
<br>
<br>
So how to adapt the code to just get a list like this:
http://www.domain1.com
http://www.domain5.com
http://www.domain23.com
http://www.domain65.com
http://www.domain213.com
When you change the <br> into a , then the list becomes ,,,,,,,,,,,http,,,,,,httphttphttphttp,,,,,,, <= I wrote it down a bit shorter.
First thing, array_filter, if no callback was passed, will remove only falsy elements. String with empty spaces is evaluated to true and therefore will not be remove from array. You can do something like:
$filteredArray = array_filter($projectList, function($val) {
return trim($val);
});
print_r($filteredArray);
Also, you can't echo an array. You can use print_r or var_dump.
If array_filter isn't filtering out empty values, then they probably aren't really empty. Assuming there is some sort of whitespace there rather than nulls or empty strings, you can probably modify your query to trim the title and only return results where there's still something there.
SELECT title FROM #__pf_projects
WHERE access = ? AND title IS NOT NULL AND TRIM (title) != ''
Or, in terms of your original PHP code:
$query = 'SELECT title FROM #__pf_projects';
$query .= ' WHERE access = ' . $level . " AND TITLE IS NOT NULL AND TRIM(title) != ''";
It is best to avoid concatenating variables into your SQL like this, though. If the framework you're using has some way to utilize prepared statements, you should go that route instead.
If this still doesn't work, I don't really know what else to try with the query, but you should be able to just check for an empty result in PHP and only echo if there's something to show.
$projectlist = $db->loadResult($query);
if (trim($projectlist)) echo $projectlist.'<br>';
Thanks to everyone's answers I finally figured out a way to get the results. My way is not necessarily the right way for everyone. And someone with more knowledge then me in this area would probably do it different.
Essentially my answer is outputting the entire string with each result inside a div. This will create a lot of empty divs but those are not generated by HTML. They do however show up in the Inspector.
The final code that I use in my script.
$user_ = JFactory::getUser();
$db = JFactory::getDBO();
$levels = JAccess::getAuthorisedViewLevels($user->id);
foreach($levels as $key => $level)
{
$query = 'SELECT title FROM #__pf_projects';
$query .= ' WHERE access = ' . $level;
$db->setQuery($query);
$projectlist = '<div class="project">'.$db->loadResult($query).'</div>';
echo $projectlist;
}
This is now giving me a list like this:
http://www.domain1.com
http://www.domain5.com
http://www.domain23.com
http://www.domain65.com
http://www.domain213.com
I have a database with a field called part_name.
with the values:
Front Control Arm, Rear Control Arm
I need to echo out only Control Arm, once only.
As of now what i'm getting on the while loop results is
Control Arm, Control Arm.
Need to echo out distinct values from while loop results. I can't do it on the SQL query SELECT DISTINCT because i'm preg replacing the value from the row that i'm queering on the database.
while ($rowsparts = mysql_fetch_array($displayparts)) {
$part=''.$rowsparts['part_name'].'';
$part = preg_replace('/\bFront\b/u', '', $part);
$part = preg_replace('/\bRear\b/u', '', $part);
echo '<li>'.$part.'</li>';
}
I need to echo out the $part variable distinct values, only once per part name.
Control Arm only.
This might work if you want to only display the part name once:
$lastpart = '';
while ($rowsparts = mysql_fetch_array($displayparts)) {
$part = $rowsparts['part_name'];
$part = trim(str_replace('Rear','',str_replace('Front','',$part)));
if($lastpart != $part) {
$lastpart = $part;
echo "<li>".$part."</li>\n";
} else {
echo "<li>Part name duplicate: $part, lastpart: $lastpart</li>\n";
}
}
I added the else for debugging. It will show the two vars that are used to detect duplicates. You would remove it after testing.
This might work if you want to only display the part name once when the part names are not in order.
It builds a list of part names, and checks each part names against the list, showing
only the ones not found in the list.
$part_list = array();
while ($rowsparts = mysql_fetch_array($displayparts)) {
$part = $rowsparts['part_name'];
$part = trim(str_replace('Rear','',str_replace('Front','',$part)));
if(!isset($part_list[$part])) {
$part_list[$part] = 1;
echo "<li>".$part."</li>\n";
}
}
I am echoing a list of areas covered as hypertext links taken from a database,
$area_shire = '';
$area_district = '';
$area_name = '';
while($rows = mysql_fetch_assoc($query)) {
if ($rows['area_shire'] != $area_shire) {
$area_shire = $rows['area_shire'];
$area_shire_url = str_replace(' ', '_', $area_shire);
echo '<h2><a href=Driveway_Cleaning_'.$area_shire_url.'>'.$area_shire.'</a></h2><br>';
}
if ($rows['area_district'] != $area_district) {
$area_district = $rows['area_district'];
$area_district_url = str_replace(' ', '_', $area_district);
echo '<h3><a href=Driveway_Cleaning_'.$area_district_url.'>'.$area_district.'</a></h3><br>';
}
if ($rows['area_name'] != $area_name) {
$area_name = $rows['area_name'];
$area_name_url = str_replace(' ', '_', $area_name);
echo '<a href=Driveway_Cleaning_'.$area_name_url.'>'.$area_name.'</a><br>';
}
}
?>
This is Giving me a linear output of
West Midlands
Birmingham
Harborne
Edgbaston
Moseley
Dudley
Halesowen
Sedgley
Warwickshire
I am trying to put the output into a dynamic table so each area_district (e.g) Dudley starts in a new column and is therefore to the right of Birmingham rather than below. Everything i try is affecting the order of the output. Any ideas?
Why don't you try to use an HTML table then? Or put each grouping in a flaoting div to where they can be placed along side each other? My main recommendation is just work out your HTML template first, then work out how to inject the dynamic data into it afterwards.
I have following code for an autocomplete box, I'm adding an image for choice clarification but want to make sure the title returned is unique, but, when I get to the code which makes the array unique, i've added other code which makes it non unique in other areas. Is there a way around this?
$query = "SELECT $title, imageURL FROM PRprodINFO2 WHERE ((prodcatID = '$cat_id')
AND ($title LIKE \"%" . $_GET["q"] . "%\")) group by $title LIMIT 8";
}
$result = mysql_query($query);
// set the array
$output_items = array();
while($row = mysql_fetch_array($result)) {
// clean after first non letter/number
$row[$title] = preg_replace('/[^\w\s].*$/', "", $row[$title]);
//trim spaces
$row[$title] = trim($row[$title]);
// add image src
$output_items[] = '<img src='.$row[imageURL].' style=max-width:50px;>'
.$row[$title];
} // while
// here i need just $row[title] to be unique,
// it is made non unique after regex strips off some characters
$output = array_unique($output_items);
print(implode("\n", $output));
mysql_close();
I am possibly confused by what you are asking. It seems like you would already have unique titles since you are grouping by title in your sql. But, maybe you have extra non alpha-numeric characters you are stripping out with your regex that makes some unique titles the same.
In that case, instead of building up your $output_items like you are, try:
$output_items[$row['title']] = $row['imageURL'];
This will ensure that each title is unique. You will have the imageURL of the last row that matched that title. If you want, instead, the first title that matched, then just check isset before overwriting it like:
if (!isset($output_items[$row['title']])) $output_items[$row['title']] = $row['imageURL'];
Then, outside of the loop, build up your output string.
$output = '';
foreach ($output_items as $title => $image) {
$output .= '<img src='.$image.' ...>'.$title."\n";
}
echo $output;
again.
I'm trying to go through a database table and replace all instances of old BBCode (ie: [i:fs8d979]) and replace it with simple BBCode ([i]). However, I'm getting very confusing results.
$root_path = './';
include($root_path.'includes/common.php');
$posts = array();
$sql = 'SELECT post_id, post_text FROM posts';
$db->query($sql);
while($row = $db->fetch_assoc())
{
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
}
foreach($posts as $post)
{
$regex = "/\[(\D)(\:[a-zA-Z0-9_]{1,})\]/";
if(preg_match($regex, $post['text'], $matches))
{
$string = preg_replace('/'.$matches[2].'/', '', $post['text']);
$sql = 'UPDATE posts SET post_text = "'.$string.'" WHERE post_id = '.$post['id'];
$db->query($sql);
echo $post['id'].'--Matched and replaced<br />';
}
else
{
echo $post['id'].'--No Match<br />';
}
}
echo 'done';
when i run this script, I get output like this:
1302--No Match
--No Match
1303--No Match
--No Match
17305--No Match
--Matched and replaced
5532--No Match
--No Match
17304--No Match
--No Match
1310--No Match
--No Match
it would appear that the script is attempting to do everything twice, and I'm not sure why. The database fields are not getting updated either.
I've echoed everything out for debugging purposes, and all variables are set and everything looks like it should be working properly.
Any suggestions?
At the point in the code:
while($row = $db->fetch_assoc())
{
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
}
You are creating two entries in the array, one with the id, followed by the text.
I think you want:
while($row = $db->fetch_assoc())
{
$posts[] = array('id' => $row['post_id'], 'text' => $row['post_text']);
}
It would explain why each one is happening twice and nothing is changing.
The debug was showing the wrong value too:
echo $post['id'].'--Matched and replaced<br />';
and the output was
--Matched and replaced which showed no post id.
First: the lines
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
are adding two elements to the $posts array. That is why you are getting two outputs per post.
Second: I don't think the colon : is a special character - it doesn't need to be escaped. So it should look like:
$regex = "/\[(\D)(:[a-zA-Z0-9_]+)\]/";