php echo doesnt print newlines - php

I started doing a new project in PHP / MySql . The Aim of this project is to manage articles for a magazine that i am the editor of.
So the content of the articles, i decided i would store with the "TEXT" column type of MySql
Now when i retrieve this column and print it with echo, the newlines are not there. Its all on the same line.
$resset = mysql_query("select txt from articles where id = 1");
$row = mysql_fetch_assoc($resset);
$txt = $row['txt'];
echo $txt; //doesnt print it as it is in the database as it was typed (multiline)
Find below, the text as it looks in the database and as it looks when it is echoed
in the databse, it is with new lines http://img413.imageshack.us/img413/4195/localhostlocalhostzxcvb.jpg
Text as it looks when echod http://img718.imageshack.us/img718/1700/sdashboardmozillafirefo.jpg
But within the database, its stored with newlines.
Has anybody else encountered this problem?
Please help me as my project depends on this :|

Whitespace in HTML is folded into a single space. Use nl2br() if you want to maintain newlines in HTML.

Have you tried
echo $txt."<br/>";

alternatively, you can put your output between <pre> tags:
echo "<pre>";
$resset = mysql_query("select txt from articles where id = 1");
$row = mysql_fetch_assoc($resset);
$txt = $row['txt'];
echo $txt; //doesnt print it as it is in the database as it was typed (multiline)
echo "</pre>";
btw,
echo $txt."<br/>";
may not work since it will just append newline at the end but not within $txt string

I know this isn't part of your question, but if you additionally want new lines in your HTML code but not your presentation, use double quotes with \n. This can help keep the HTML really tidy.
echo "\n";

Related

Cannot pass variable with apostrophe in "a href" link

I select a list of names from mysqli database then display row details in display.php with if (isset($_GET['name']));
The link is
$str = strtoupper($str);
echo "<tr><td><a href='php/display.php?name=$str'>$str</a></td></tr>";
This executes correctly unless name contains '(apostrophe).
For instance $str (as input/click) shows as L'ECLIPSE but the <a> link only L'
The result in display.php is 'No data found for your request'
I have found exact same queries on this site but none of the answers have resolved my problem. Perhaps I am not implementing correctly.
I assume this is about escaping. But I know little about it.
<?php
$str = strtoupper($str);
echo "<tr><td><a href='php/display.php?name=".urlencode($str)."'>$str</a></td></tr>";
urlencode() the string first. So you don't get this kind of problems.
Try this code.
<?php
$str = strtoupper($str);
echo "<tr><td><a href='php/display.php?
name=".htmlspecialchars($str)."'>$str</a></td></tr>";
?>
Your Single quote becomes &#039 ;
I hope it will help

Get html link from database with PHP

I have a database table that contains these rows, "id" ,"link" and "name"
with link being :
<a href=\"https://www.sample.com/file1.php\">[1-200]< /a> <a href=\"https://www.sample.com/file2.php\">[201-224]< /a>
and name :
item1
I have the following PHP code to get the info from the database and return it to visitors. My problem is that the link for file2.php, is not only applied as hyper link for [201-224], the hyperlink is applied for the rest of the page content also. How do I prevent this? And thanks in advance.
echo "</br> ".$name= $row['name'];
echo "</br> ".$Torrentlink= preg_replace('/\\\\/', '',$row['Torrentlink']);
echo "</br> ";
echo "</br> ";echo "</br> ";
echo "the rest of my text goes here ";
This is a terrible way to handle this type of data. If you know they are all links then you should only be storing the link and the name (of course id and other meta data could be useful). Your current situation allows for too many errors and a maintenance problem for those working behind you. If you do not want to create a record for each link, consider storing them as JSON or some other format.
Example: (Store JSON in DB as VARCHAR)
<?php
//Populate variable from DB
//$TorrentLinks = $row{'Torrentlink'};
$TorrentLinks = '[
{"url":"https://www.sample.com/file1.php","text":"[1-200]"},
{"url":"https://www.sample.com/file2.php","text":"[201-224]"}
]';
//Convert to array
$jsonLinks = json_decode($TorrentLinks,true);
//Iterate and print links
foreach ($jsonLinks as $key => $value) {
echo "{$value["text"]}<br />";
}
Results:
[1-200]
[201-224]
Depending on how you capture the data, you could also use something like htmlspecialchars() to keep the special characters from executing.
I think there's a problem with your preg_replace('/\\\\/', '',$row['Torrentlink']);
/\\\\/ finds text with double backslash \\. It seems that your intention is to find only single backslashes to get rid of them in your links.
So try replacing it with
preg_replace('/\\/', '',$row['Torrentlink']);
For example https://regexr.com/ is a good place to check your regular expressions.
the error was simply the input html text.
the problem was the " < /a> " in the line:
<a href=\"https://www.sample.com/file1.php\">[1-200]< /a> <a href=\"https://www.sample.com/file2.php\">[201-224]< /a>
I had a space before the the backslash.

Run PHP code stored in a database

database has php value saved like that as string
<?php $s = 'my name is'; ?>
and what am trying to do is calling the value as php code and want when type echo $s; to print my name is but now it's given my empty value see the code below to get what i mean
<?php
$b = '<?php $s = 'my name is';?>';
echo $b; //empty value
?>
Sounds like you're talking about eval() - but I'd be wary of using it. If you do, be extremely careful.
"If eval() is the answer, you're almost certainly asking the wrong question." -Rasmus Lerdorf
You'd probably need to strip the <?php and ?> tags, and watch for double quotes surrounding variables you don't want to replace:
$s=0;
eval('$s = "my name is";');
echo $s;
PHP is not recursively embeddable:
$b = '<?php $s = 'my name is';?>';
That's not PHP code in there. it's some text with the letters <, ?, p, etc...
And you ARE getting output. But you're viewing it in a browser, so the <?php ... ?> gets rendered as an unknown/illegal html tag and simply not displayed. If you'd bothered doing even the most basic of debugging, e.g. "view source", you'd have seen your PHP "code" there.

PHP - Echoing a variable in color

Im new to learning PHP as you might have guessed. I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour.
My code without colour:
<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?>
I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! I think its because I'm using 'fgets' not just a variable? Is there a way to colour the echo red?
The code I tried but doesn't work:
echo "<div style=\"color: red;\">fgets($file)</div>";
(In general) You need to separate the actual PHP code from the literal portions of your strings. One way is to use the string concatenation operator .. E.g.
echo "<div style=\"color: red;\">" . fgets($file) . "</div>";
String Operators
Other answer already told that you can't use a function call in a double quoted string. Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element.
Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
You should try:
<div style="color: red;"><?= fgets($file);?></div>
Note: <?= is an short hand method for <?php echo fgets($file);?>
This version does not need to escape double quotes:
echo '<div style="color:red;">' . fgets($file) . '</div>';
You can do this with the concatenate operator . as has already been mentioned but IMO it's cleaner to use sprintf like this:
echo sprintf("<div style='color: red;'>%s</div>", fgets($file));
This method comes into it's own if you have two sets of text that you want to insert a string in different places eg:
echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));

Putting Something Inside a Link with PHP

So I'm basically calling and returning an entire row from a mysql table using a while loop (which is working), but I'm trying to use the data that I call inside an html link, but I can't seem to get it to work.
Ideally, eventually it will just be a list of links with each person's individual name. I can return the list fine, but I can't seem to return the list with a link.
Here is my code that I feel should be working :(
<?php
require 'db/connect.php';
$result = $con->query('SELECT distinct name FROM mytable');
while($rows = $result->fetch_assoc())
{
echo ''$rows['name']'' , "</br>";
}
?>
Any help would be greatly appreciated!
Issue might be with your string concatenation. Try following code block
echo ''.$rows['name'].'';
echo ''. $rows['name']. '' , "</br>";
You just need to use . to concatenate strings together.
try this
echo ''.$rows['name'].'' , "</br>";
Should work just fine. Basically it's '.$row['name'].'
when concatenating strings with variables you have to use dot(.) like echo "string".$var; it will be invalid to write echo "string"$var; in your example you have ignored this point.

Categories