Inserting text from textarea into MySQL database without losing formatting - php

I am trying to add text from a textarea on my site into a MySQL database.
Below is the PHP code that is adding the text to the database.
if (isset($_POST['text']))
{
$text = sanitizeString($_POST['text']);
$text = preg_replace('/\s\s+/', ' ', $text);
$query = "SELECT * FROM profiles WHERE user='$user'";
if (mysql_num_rows(queryMysql($query)))
{
queryMysql("UPDATE profiles SET text='$text' where user='$user'");
}
else
{
$query = "INSERT INTO profiles VALUES('$user', '$text')";
queryMysql($query);
}
}
else
{
$query = "SELECT * FROM profiles WHERE user='$user'";
$result = queryMysql($query);
if (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
$text = stripslashes($row[1]);
}
else $text = "";
}
$text = stripslashes(preg_replace('/\s\s+/', ' ', $text));
And below is the code of the form.
<textarea name='text' cols='40' rows='3'>$text</textarea><br />
But when the data is inputted, it shows it in the database correct but not showing it displayed properly. See the images below:
The text that is entered
How the text is displayed on the page
How the text is in the database
This is the PHP code that displays the text on the page.
$result = queryMysql("SELECT * FROM profiles WHERE user='$user'");
if (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
echo stripslashes($row[1]) . "<br clear=left /><br />
Hope you can help!!
EDIT: added extra php code

Your text, unless you're using a rich-text editor, such as Mark-down (as here on Stackoverflow), is styled by your CSS, not by the contents of the textarea itself.
If the problem is preservation of new-lines, then you could run the string through the nl2br($text) function before storing in, or retrieving from, the database.
I'd suggest on retrieval would be better, but that's just my opinion (and I can't offer any evidence to back it up).

Or you can use
echo nl2br($test);

Related

Pass value from one PHP file to another

I'm trying to pass a value which is input into a box on one Php page (itinerary.php) into another Php page ('submit.php') so it can, from there, be saved into a database. But I can't quite figure out how to get it across. I've tried using GET as you can see from code below, but I am already using a GET statement to receive and acknowledge another value from that very same page 'submit'. I guess I am overcomplicating it, but my knowledge of Php is still pretty limited at this stage so any ideas would be appreciated!
This is an extract from the itinerary.php file (it sits within a Bootstrap/Html framework. Note the entry which contains the input box for the sequence number).
<h3><br>YOUR ITINERARY</h3>
<?php
//Display contents of itinerary
if(!empty($_SESSION['itinerary'])){
//Retrieve details of each location in array from database
$query = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $loc_id=>$value)
{$query.=$loc_id.',';}
$query = substr($query, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $query);
echo'<table><tr><th colspan="5">LOCATIONS IN YOUR ITINERARY</th></tr>';
//Display locations in array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$loc_id = $row['loc_id'];
echo"<br><td>{$row['loc_name']}</td></tr><br>
<td>{$row['loc_desc']}</td>
<td><p>Seq. No</p><input type=\"text\" size=\"3\" name=\"sequence\" value=????????>NOT SURE WHAT TO ADD INTO THIS LINE TO RETAIN THE INFO THAT IS INPUT</td>
<td><a href=remove_loc.php?value=$loc_id>Remove location</a><br></br></td>
</tr><br></table>";
}//while
print_r($_SESSION);
mysqli_close($db);
}//if
else {echo '<p><br>Your itinerary is empty.<br></p>';}
echo '<br><p>
<a href=submit.php?submit>Save itinerary</a>
<a href=clear_itin.php?clear>Clear itinerary</a>
Your details
Logout
</p>';
?>
And this is where I am trying to receive it and then use it in a SQL command to add to the database. (Again, this is within a Bootstrap framework)You can ignore the first SQL Insert statement as it is passing other info in successfully anyway..
<div class="row">
<div class="col-md-9">
<?php
if (isset($_GET['sequence'])){
$sequence = $_GET['sequence'];
}//if
if (isset($_GET['submit'])){
$query = "INSERT INTO itineraries (user_id, date_created) VALUES (".$_SESSION['user_id'].", NOW())";
$result = mysqli_query($db, $query);
$itinerary_id = mysqli_insert_id($db);
$retrieve_locs = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $id=>$value)
{$retrieve_locs.=$id.',';}
$retrieve_locs = substr($retrieve_locs, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $retrieve_locs);
//Store items in itin_locs db
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)){
//This is the command I have been trying to use, commented out. The second one below this works fine, but obv doesn't input a sequence number.
//$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id, sequenceNo) VALUES ($itinerary_id, ".$row['loc_id'].", $sequence)";
$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id) VALUES ($itinerary_id, ".$row['loc_id'].")";
$insert_result = mysqli_query($db, $insert_locs);
echo mysqli_error($db);
if ($insert_result === FALSE) {
die("Query failed!" . mysql_error() . $insert_locs);}
}//while
mysqli_close($db);
echo"<p>Your itinerary is saved!. Itinerary number is #".$itinerary_id."</p><br>";
$_SESSION['itinerary']= NULL;
echo '<p>
Your details
Logout
</p>';
}//if
else {echo '<p>Your itinerary is empty.<br></br></p>';}
?>
Use a form on your HTML page to hold all the input fields in the table.
Also instead of anchor "a" tag use a submit button to submit the form to other page.
Use some thing like:
Send value of submit button when form gets posted

How to remove br while extracting contents from database?

I'm trying to develop the dynamic site using PHP and obsolete mysql_query.
I need to extract limited contents from my database so I've used substr and this content is placed at the index page. But while the user edits the page, the content is formatted, sometimes the font size is too large, sometimes the content has lots of <br>. It destroys the look of my website. I'm troubled by unnecessary <br> and want to remove it and also want to ignore the formatted font size in the index page.
My code goes like this:
<?php
$sql = "SELECT contents FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$contents = $row['contents'];
echo substr($fld_page_details, 0,125);
}
?>
Try the following:
<?php
$sql = "SELECT contents FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$contents = $row['contents'];
echo str_replace('<br>', '', $contents);
}
?>

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

How to select certain fields from table in mySQL using PHP

I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit

Display image on php mysql blog based on username of post

Thanks in advance!
I have a simple mysql and php blog that I built based on a tutorial I found online. What I would like to be able to do, but have no idea how to go about it, is this:
I would like a picture (avatar) to be displayed with each comment on each post. The picture that is chosen would be based off of the name in the Posted By: area of the comment. So for instance: Let's say me, the admin, leaves a comment on the thread. My name is automatically pulled in via a '$_SESSION' variable so I don't have to worry about entering that each time. When the comment is displayed on the blog thread page, it shows Commented on By: Admin. This name is stored in the db and pulled in with the a php echo statement.
So what I want this avatar code to be able to do is
1) look at the area where the Commented on By: text is
2) read the text
3) see that it says Admin and display the admin.png image next to it. If it sees anything other than Admin in the Commented on By: area, then it will display something like guest.png
Here is a snippet of code I found in my stackoverflow and google searches. It works but it pulls in the guest image 6 times, then the actual admin.png image, and then the guest image 3 more times. And it displays this way on EACH comment on EACH thread! And when I add a new thread and a new comment to that thread, it adds the guest image again at the end of the multiple images being displayed on each comment. Did I set it up wrong?
<?
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) != 0) {
$counter = $starting + 1;
$pathImg = "images/";
while ($row = mysql_fetch_array($result)) {
//calculate url image
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
?>
<img src="<?=$pathFile?>" alt="<?=$row['comment_user']?>">
</p>
<?
$counter++;
}
}
?>
This displays out as (Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Admin Image)(Guest Image)(Guest Image)(Guest Image).
Any help on throwing something together would be great! Trying to keep it simple to!
EDIT:
This is how the comments are displayed, along with the code from FlyingGuy's answer.
<?php
foreach ($post['comments'] as $comment){
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$commentCount++ ;
$pathImg = "images/";
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
?>
<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
<p><?php echo $comment['body']; ?></p>
<hr />
<?php
}
?>
This is how the functions look for displaying and adding comments:
function get_comments($pid){
$pid = (int)$pid;
$sql = "SELECT `comment_body` AS `body`, `comment_user` AS `user`, DATE_FORMAT(`comment_date`, '%m/%d/%Y') AS`date` FROM `comments` WHERE `post_id` = {$pid}";
$comments = mysql_query($sql);
$return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){
$return[] = $row;
}
return $return;
}
// adds a comment
function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}
$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentities($user));
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
return true;
}
?>
Look what you are trying to do is select the image that matches the name of the user in the current row of your result set. So you will set your image file variable as appropriate for each row and you are sending that to the browser.
For starters and can see the probability of case issues here. Are all user names forced to lower case and all image names forced to lower case? If this is on a linux box that is a land mine on windows not so much, but this should be taken into account.
It will set an image name for each row of your queries result set so it will look like:
[image] [comments]
[image] [comments]
[image] [comments]
if you have three rows in your result set.'
Personally I avoid all of the turning php on and off all over the place. Concat a single string and then simply echo it out for each row. So I would code it like so:
<?
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$commentCount++ ;
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
So I have eliminated a lot of things from your code example like counters etc. You don't really need to check and see if there are rows since the while loop simply will not execute of there are no rows so you will simply have a question of comment with no subordinate comments and it will only send the image link if there are comments.
No if it were me doing this I would create an avatar file name is the user table and store the path to those as part of the system configuration which would be part of the global set of variables that are always present. Your query would then join in the users table and the image name or guest image would be in your result set. A bit more complex but much cleaner and it simplifies your code.
One of the reasons I don;t like dynamic typing. $row was being mutated to an array of ALL the rows..

Categories