edit display of php recordSet output - php

The following code produces each result as text. I would like to add some html to each result, to change it from regular text to an href tag:
while (!$recordSet->EOF()) {
if ($pclass_name_list == '') {
$pclass_name_list .= $recordSet->fields['class_name'];
} else {
$pclass_name_list .= ',' . $recordSet->fields['class_name'];
}
$recordSet->MoveNext();
}
The above produces Result 1, Result 2. I'd like to change these to
Result 1
Result 2
etc..

If you are doing a simple addition of content into a string, you can either wrap the variable in curly braces and include it in a string that has double quotes (as below), or you can use the sprintf function to merge content into a template.
$pclass_name_list = array();
while (!$recordSet->EOF()) {
$current_class_name = $recordSet->fields['class_name'];
$pclass_name_list[] = "{$current_class_name}";
$recordSet->MoveNext();
}
$pclass_name_list = implode(", ", $pclass_name_list);

Maybe:
if ($pclass_name_list == '') {
$pclass_name_list .= '' . $recordSet->fields['class_name'] . '';
} else {
$pclass_name_list .= ', ' . $recordSet->fields['class_name'] . '';
}

Related

how to separate the second comma in a php variable from mysql in html

Sorry if my question is being duplicate because I've tried to find similar questionI've got a data column in MySQL which look something like this :
https://i.stack.imgur.com/3VRI9.png
I've created a form which display the address in html using php.
$pdf_content .= '<div style="padding-left:5%">';
$pdf_content .= $company_name.'<br>';
$pdf_content .= '<div id="errorMessage">'.$address.'<br></div>';
//$pdf_content .= 'Add2,<br>';
//$pdf_content .= 'Add3,<br>';
$pdf_content .= $postcode.'<br>';
$pdf_content .= $state.'<br>';
$pdf_content .= $country.'<br>';
$pdf_content .= $mobile_phone.'<br>';
$pdf_content .= '<b>RE: Quotation for 3<sup>rd</sup> party claim vehicle </b>';
$pdf_content .= '</div><br>';
What I wanted to do now is the address which look something like No.43,Jalan Bandar Bahagia,Taman Pinji Mewah 1 , I wanted to separate the second comma which will look something like this
https://i.stack.imgur.com/0OlG3.png
I've tried but still not working
$pdf_content .= $address.'<br>';
$myList_explode = explode(",",$address);
for($i=0;$i<sizeof($myList_explode);$i++){
echo $myList_explode[$i];
if(($i+1)%2==0){
echo "</br>";
}else{
echo ",";
}
}
Is possible to do it in php while in MySQL it won't be separated?Thanks in advance.
Consume the leading substring before the second occurring comma, then forget it with \K. Then match the second occurring comma and replace it.
Regex prevents having to write a multi-line solution with a loop.
Code: (Demo)
echo preg_replace('~^[^,]*,[^,]*\K,~', '<br>', $address);
Output:
No.43,Jalan Bandar Bahagia<br>Taman Pinji Mewah 1
My pattern bears some similarity to the pattern in this preg_match() call: https://stackoverflow.com/a/65355441/2943403
You can try like this...:
$string = 'No.43,Jalan Bandar Bahagia,Taman Pinji Mewah 1';
echo formatString($string);
// No.43,Jalan Bandar Bahagia
// Taman Pinji Mewah 1
function formatString($inputString) {
$stringToArray = explode(",",$inputString);
$finalString = "";
$count = count($stringToArray) - 1;
foreach($stringToArray as $k => $arr) {
$addon = ",";
if($k == 1) {
$addon = "<br>";
}
if($k == $count) {
$addon = "";
}
$finalString .= $arr.$addon;
}
return $finalString;
}
Basically you create an array from string with explode, loop over it and create a string out of the elements. And since you want to add after second comma, function adds it if $key == 1 (second key).

Need help sorting this logic with JSON Pretty Print

Trying to pretty print json, and works fine, cept, seems to add an extra line when printing out an array of objects between each object array. Could use some help on the logic of this as I haven't touched this in awhile...
code for pretty printing it is as follows:
public function pretty_print($json_data, $line_numbers = true)
{
$return = '';
$space = 0;
$flag = false;
$json_data = trim($json_data);
$line = 1;
if (!empty($json_data)) {
if (!empty($line_numbers))
$return .= '<div class="line" data-line-number="' . $line . '">';
//loop for iterating the full json data
for($counter = 0; $counter < strlen($json_data); $counter++)
{
//Checking ending second and third brackets
if ($json_data[$counter] == '}' || $json_data[$counter] == ']')
{
$space--;
$line++;
$return .= !empty($line_numbers) ? '</div><div class="line" data-line-number="' . $line . '">' : PHP_EOL;
$return .= str_repeat(' ', ($space*4));
}
//Checking for double quote(“) and comma (,)
if ($json_data[$counter] == '"' && ((!empty($counter) && $json_data[$counter-1] == ',') || ($counter > 1 && $json_data[$counter-2] == ',')))
{
$line++;
$return .= !empty($line_numbers) ? '</div><div class="line" data-line-number="' . $line . '">' : PHP_EOL;
$return .= str_repeat(' ', ($space*4));
}
if ($json_data[$counter] == '"' && !$flag)
{
if ( (!empty($counter) && $json_data[$counter-1] == ':') || ($counter > 1 && $json_data[$counter-2] == ':' ))
$return .= ' <span class="json-property">';
else
$return .= '<span class="json-value">';
}
$return .= $json_data[$counter];
//Checking conditions for adding closing span tag
if ($json_data[$counter] == '"' && $flag) {
$return .= '</span>';
}
if ($json_data[$counter] == '"')
$flag = !$flag;
//Checking starting second and third brackets
if ($json_data[$counter] == '{' || $json_data[$counter] == '[')
{
$space++;
$line++;
$return .= !empty($line_numbers) ? '</div><div class="line" data-line-number="' . $line . '">' : PHP_EOL;
$return .= str_repeat(' ', ($space*4));
}
}
if (!empty($line_numbers))
$return .= '</div>';
}
return !empty($return) ? trim($return) : json_encode(json_decode($json_data, true), JSON_PRETTY_PRINT);
}
But seems to parse the json with an extra <div class="line" data-line-number=""></div>
Here's an image of this and would like to get rid of the extra space between objects of the array in here if possible. Any help here, would really appreciate it.
Why the heck are you manually parsing JSON? That code is going to be incredibly difficult to reason about and maintain, especially if you come back to it later when a bug almost inevitably presents itself.
Rather than taking the difficult approach, consider instead doing the following:
1. Reformat the JSON so that it suits your needs. In this case, for example, you prefer to keep the closing and ending brackets of objects on the same line, rather than on separate lines.
2. Split the already-pretty-formatted JSON into separate lines.
3. Wrap the individual lines of your JSON in HTML.
4. Re-join the lines to get your final HTML.
function prettyWrapJson($json_data, $line_numbers = true) {
// Ensure that our JSON is in pretty format.
$json_data = json_encode(json_decode($json_data, true), JSON_PRETTY_PRINT);
// Modify the formatting so that adjacent closing and opening curly braces are on the same line.
// Note: we can add a similar line if we want to do the same for square brackets.
$json_data = preg_replace('/},\n +{/s', '},{', $json_data);
$line_number = 1;
// Coerce a boolean value.
$line_numbers = !empty($line_numbers);
// Split into an array of separate lines.
$json_lines = explode("\n", $json_data);
// Wrap the individual lines.
$json_lines = array_map(function($json_line) use ($line_numbers, &$line_number) {
// Check if this line contains a property name.
if(preg_match('/^( +"[^"]+"):/', $json_line, $matches)) {
// Similar result to explode(':', $json_line), but safer since the colon character may exist somewhere else in the line.
$parts = array($matches[1], substr($json_line, strlen($matches[1]) + 1));
// Wrap the property in a span, but keep the spaces outside of it.
$parts[0] = preg_replace('/^( +)/', '$1<span class="json-property">', $parts[0]) . '</span>';
// We only want to wrap the other part of the string if it's a value, not an opening brace.
if(strpos($parts[1], '{') === false && strpos($parts[1], '[') === false) {
// Similarly, wrap the value in a span, but keep the spaces outside of it.
$parts[1] = preg_replace('/^( +)/', '$1<span class="json-value">', $parts[1]) . '</span>';
}
// Re-join the string parts with the colon we stripped out earlier.
$json_line = implode(':', $parts);
}
// Finally, we can wrap the line with a line number div if needed.
if($line_numbers) {
$json_line = '<div class="line" data-line-number="' . ($line_number++) . '">' . $json_line . '</div>';
}
return $json_line;
}, $json_lines);
// Re-join the lines and return the result.
return implode("\n", $json_lines);
}
You may need to tinker with it slightly to get it formatted exactly to your preferences, but this should be much easier for you to work with.

dont break line if data ending "\" while writing in csv in php

writing in csv file from database, if same id trying to append in "comments" coulmn with same row. but if from database value ending with "\" sign so next comments is writing in new line..if value is not ending with "\" for this working properly.
function cleanComments($string) {
$cleanstring = trim($string);
$returnstring = preg_replace("/\n/", "", $cleanstring);
return $returnstring;
}
function remove_special_char($string) {
$RemoveChars[] = "([,%+*¢£¥¤¡~©¦§¨ª«¬®¯°±²³´µ¶¸¹º»¿\[:^print:]])";
$ReplaceWith = "";
$text = preg_replace($RemoveChars, $ReplaceWith, $string);
return $text;
}
$comment_text = cleanComments($query_result['user_name'] . ':' . $query_result['comment']);
if ($counter == 1) {
$row['comment'].= remove_special_char($comment_text);
} else {
$row['comment'].= PHP_EOL . remove_special_char($comment_text);
}
if "\" this special character is ending with dont write in line in csv check my code anyting i missed? or any solution ?
i changed to this.
$comment_text = cleanComments(stripslashes($query_result['user_name'] . ':' . $query_result['comment']));
if ($counter == 1) {
$row['comment'].= remove_special_char($comment_text);
} else {
$row['comment'].= PHP_EOL . remove_special_char($comment_text);
}
its working properly now.

Add titles to items from array

I don't have that much experience with PHP and am looking for help with the following:
I am fetching data from an SQL table that has a column "countries" containing the name of a country and a column "desc" containing a comment.
On my web page I create an array out of the matching countries (based on certain criteria) in order to sort them alphabetically and to add an image in front of each of them (images have the same name as the countries).
Finally I am just echoing out this array in order to display the countries and corresponding images on the page.
All of this works well so far (using the below code).
My code:
$countries = '';
$valC = '';
$countC = 0;
foreach ($objDays->days as $days) {
if(($days->dateMatch == "Yes") && ($days->locales != "")) {
$inputC[] = explode(',', $days->locales);
$countC++;
}
}
if($countC == 0) {
$countries = " <img src='images/icons/emotion_what.png' alt='' /> No data on file for this date.";
} else {
$arrC = array_map("trim", call_user_func_array("array_merge", $inputC));
sort($arrC);
array_walk($arrC, function (&$valC) { $valC = "<img src='images/icons/flags-32/flag_" . str_replace(" ", "_", $valC) . ".png' alt='' id='c" . $valC . "' style='width:32px' /> " . $valC; } );
$countries = implode(' ', $arrC);
}
// ...
echo $countries;
Update:
The explode is no longer needed as now there is always only one country in each cell of the table.
What I am unable to do is the following:
I would like to add also the the comments from my column "desc" as a (hover) title to each country that I am echoing out.
I can fetch this via $objDays->days->desc resp. $days->desc but can't find a way to add this in.
Can someone here help me with this ?
You can store a sub array inside $inputC like that :
foreach ($objDays->days as $days) {
if(($days->dateMatch == "Yes") && ($days->locales != "")) {
$inputC[] = array(
"text" => explode(',', $days->locales),
"desc" => $days->desc
);
$countC++;
}
}
And modify your array_walk
array_walk($arrC, function (&$valC) { $valC = "<img src='images/icons/flags-32/flag_" . str_replace(" ", "_", $valC['text']) . ".png' alt='".$valC['desc']."' id='c" . $valC['text'] . "' style='width:32px' /> " . $valC['text']; } );
edit : Your trim & array_merge will be certainly broken and need to be updated.

php string in to javascript code with comma except last string

I'm using a javascript plugin this is the line which I need help from u
<script type="text/javascript">
$('ul#news').newswidget({ source: ['http://rss.news.yahoo.com/rss/us', 'http://rss.news.yahoo.com/rss/world', 'http://feeds.bbci.co.uk/news/rss.xml'],
I would like to add URL data from MySQL
I'm using it with while loop like this
$('ul#news').newswidget({ source:[<?php
while($rssrow = mysql_fetch_array($rss))
{
echo "'"."$rssrow[rss_name]"."'".",";
}
?>],
It doesn't work properly :(.
I need to get like URL,URL,RUL like this.
that means no comma for the last one
any one please help me
You can actually do that pretty easily by a simple reorganization:
if($rssrow = mysql_fetch_array($rss))
{
echo "'".$rssrow['rss_name']."'";
while($rssrow = mysql_fetch_array($rss))
{
// note no quotes -- they are redundant
// prepend the comma
echo ","."'".$rssrow['rss_name']."'";
}
}
It does make for an extra step for the reader, but it does have the benefit of not needing substring, a new array, or a flag.
You could just build the string and remove the last comma:
$result = '';
while($rssrow = mysql_fetch_array($rss))
{
$result .= "'"."$rssrow[rss_name]"."'".",";
}
echo ($result != '') ? substr($result, 0, -1) : "''";
OR use implode():
$result = array();
while($rssrow = mysql_fetch_array($rss))
{
$result[] = $rssrow[rss_name];
}
echo "'" . implode($result, "','") . "'";
(both of these methods will output '' if the result set is empty.)
$urls = "";
while($rssrow = mysql_fetch_array($rss))
{
$urls.= "'$rssrow[rss_name]',";
}
echo substr($urls, 0, -1);
I wonder why no comment points out that you should definitely escape your output. If an entry contains a ', all solutions aside from Dmitry F’s first will break badly.
$('ul#news').newswidget({ source:[<?php
$arr = array();
while($rssrow = mysql_fetch_array($rss))
{
$arr[] = '"' . str_replace('"', '\"', $rssrow['rss_name']) . '"';
}
echo implode(',', $arr);
?>],
here is a little bit different approach:
<?php
$news = array(
'source' => array(
'http://example.com',
'http://example.com'
)
);
$news_json = json_encode($news);
?>
<script>
$('ul#news').newswidget(<?php echo $news_json; ?>);
</script>
another variation:
$url = array();
while($rssrow = mysql_fetch_array($rss))
{
$url[] = '"' . $rssrow['rss_name'] . '"';
}
echo implode(',', $url);

Categories