My homepage pulls in content from my MySQL database to create a blog. I've got it so that it only displays an extract from the posts. For some reason it displays HTML tags as well rather than formatting it using the tags (See picture below).
Any help is appreciated.
Homepage:
<html>
<head>
<title>Ultan Casey | Homepage</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div class="wrapper">
<div id="upperbar">
Home
About Me
Contact Me
Twitter
<form id="search-form" action="/search" method="get">
<input type="text" id="textarea" size="33" name="q" value=""/>
<input type="submit" id="submit" value="Search"/>
</form>
</div>
<div id="banner">
<img src="images/banner.jpg">
</div>
<div class="sidebar"></div>
<div class="posts">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
$sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT 5";
$result = mysql_query($sql) or print ("Can't select entries from table php_blog.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", $row['timestamp']);
$title = stripslashes($row['title']);
$entry = stripslashes($row['entry']);
$id = $row['id'];
?>
<?php echo "<p id='title'><strong>" . $title . "</strong></p>"; ?><br />
<div class="post-thumb"><img src="thumbs/<?php echo $id ?>.png"></div>
<?php echo htmlspecialchars(substr($entry, 0, 1050)) ?>...
<br>
<hr><br />
Posted on <?php echo $date; ?>
</p>
</div>
</div>
</p
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
Image:
You're passing your post through htmlspecialchars, which encodes < as < and > as >, among other things. This means they display as < and > instead of being parsed as html tags.
The whole point of htmlspecialchars is to produce text that's inert in HTML... to make it display as-is.
A better way to do this is to NOT store <br /> (or any other html) in your post. Instead, use regular line breaks, and echo nl2br(htmlspecialchars($text)) into your page.
If you absolutely need to allow html, you might consider something like HTML Purifier to handle escaping nasty stuff, in which case you'd skip the htmlspecialchars call. Just beware: It's not a good idea to write your own filter to stop malicious code when displaying user-supplied HTML.
echo substr($entry, 0, 1050)
Related
So I have made a guestbook (http://guestbook.ssdfkx.ch) which has a bug I can't get rid of myself. When you submit an entry and write in HTML text, it is converted into HTML and not plain text. This leads to the problem that one person can mess up the whole website in seconds.
I have tried it with the <plaintext> tag. But if I do so, even when I close the tag again, everything from the tag down turns into plain text.
Help is appreciated. The following is my code:
while ($row = mysqli_fetch_object($ergebnis)) {
$message = $row->message;
$name = $row->name;
$date = $row->date;
$id = $row->id;
$datetime = new DateTime($date);
$formatteddate = $datetime->format('d.m.Y');
$formattedmessage = nl2br($message);
if ($_SESSION['logged_in'] == true) {
$entryfeld = '<article>
<div>
<main>
<div class="innerdiv">
<p>'.$formattedmessage.'</p>
</div>
</main>
<div class="innerleft">
<form method="POST">
<input name="id" type="hidden" value="'. $id . '"/>
<input name="löschen" class="deletebutton" id="deletebutton" value="Löschen" type="submit"> </form>
<br/>
<p id="innerleftp">'.$name.'</p>
</div>
<div class="innerrightdel">
<p>'.$formatteddate.'</p>
</div>
</div>
</article>';
EDIT: Well, the variable $formattedmessage is what the user enters. If the user enters HTML it actually converts it which should not be happening. I tried using the <plaintext> tag before and after the variable. It somehow changed everything after the variable into plain text and not only the user input.
I am trying to pull a random question from one of my tables and display it in HTML. The point is to have the user put in their info in a form, answer the random question that appears, and submit the form that will store the users info along with the question they were asked and their answer. I can't seem to get the question to show up in my HTML and I'm not sure how to fix this. Still new to mySQL.
Code:
<?php
define('DB_NAME', 'db');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db', $link);
$db_selected = mysql_query("SELECT Question FROM QuestionDB ORDER BY RAND() LIMIT 1");
if (!$db_selected) {
die('Cant use ' . DB_NAME . ': ' . mysql_error());
}
if(isSet($_POST['submit'])) {
$fname = $row['f_name'];
$lname = $row['l_name'];
$email = $row['email'];
$question = $row['question'];
$answer = $row['answer'];
$sql = "INSERT INTO StudentDB VALUE ( NULL,'$fname','$lname','$email','$question','$answer')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
echo 'Thank you, your information has been sent';
}
else{
echo'
<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>
<form id = "myForm" method="POST">
<div class="col-sm-6" >
<h5><b>First Name: </b><br/><input type="text" name="f_name" size="70" required></h5> <br/>
<h5><b> Last Name: </b><br/><input type="text" name="l_name" size="70" required></h5> <br/>
</div>
<div class="col-sm-6" >
<h5><b>Email: </b><br/><input type="text" name="email" required></h5><br/>
</div>
<div class="col-sm-12" >
<br/><br/> Question: ' .$row["Question"]. '
</div>
<div class="col-sm-12" >
<br/><br/>
<h3><b>Answer:</b></h3>
<textarea maxlength="500" name="comment" id="comment"></textarea><br/>
</div>
<div class="col-sm-6" >
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>';
}
?>
On a side note running ORDER BY RAND() is not a good idea. It works to generate a random result, but it adds a lot of overhead which translates into long load times. If you start getting past 100 records you can see this really slow down MySQL queries and lead to long time to first byte wait times by the server. See here: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/
So, from what I have been learning for these past few weeks I believe I have sufficient knowledge on how to perform PHP, and SQL related queries to create a good and dynamic website that could support something like a forum. I've not been able to do that yet, and am having quite a bit of trouble with it as well. So far, I've made a PHP file, that was simply to see if I could use PHP well. It did not work out, and I've been getting plenty of errors, and I've been unable to fix them, whatsoever. And so, I'd like to come here to ask, if anyone out there could possibly analyze my code that I've written, and see what is wrong with it, if possible. Along with that, I'd like to know what would be the "Proper" way of
A. Connecting to SQL
B. Selecting Data
C. Displaying/Utilizing Data
And thank you, for reading and/or possibly replying to this.
Here, is the code I've written but have been unable to work.
<?php
include 'header.php';
include 'connect.php';
?>
<body>
<form>
Input First name:<br>
<input type="text" name="FN">
<br>
Input Last name:<br>
<input type="text" name="LN">
<br>
Input Email:<br>
<input type="text" name="Email">
<br>
<input type="submit" method="post">
<?php
if (isset($_POST['FN'], $_POST['LN'], $_POST['Email']))
$sql = 'INSERT INTO `info` ("USERID", "FN", "LN", "Email") VALUES (\'$_POST[FN]\', '$_POST["LN"]', '$_POST["Email"]')';
?>
</form>
<?php
$sql = "SELECT FN, LN, Email
FROM
info"
$result = "mysql_query($sql)"
while($row_list = mysql_fetch_assoc( $result )) {
ECHO <div>The Names are:</div><br>
ECHO $FN . "," . $LN . "," . $Email;
}
?>
</body>
</html>
Your PHP code is wrong in so many ways even in your query. What I did is clean your codes.
<?php
include 'header.php';
include 'connect.php';
?>
<body>
<form action="" method="POST">
Input First name:<br>
<input type="text" name="FN">
<br>
Input Last name:<br>
<input type="text" name="LN">
<br>
Input Email:<br>
<input type="text" name="Email">
<br>
<input type="submit" name="submit-btn" value="submit">
</form>
<?php
if (isset($_POST['submit-btn'])){
$sql = 'INSERT INTO info ( "FN", "LN", "Email") VALUES ('$_POST[FN]', '$_POST["LN"]', '$_POST["Email"]')';
if (mysql_query($sql)) {
echo "New record created successfully";
}
}
$sql = "SELECT FN, LN, Email FROM info";
$result = mysql_query($sql)
while($row_list = mysql_fetch_assoc( $result )) {
ECHO '<div>The Names are:</div><br>';
ECHO $FN . "," . $LN . "," . $Email;
}
?>
</body>
</html>
try to indent your code to make it more readable for yourself.
as already answered by user3814670, your insert query was wrong, with 4 elements (id,fn,ln,email) and only 3 data (fn,ln,email)
your query was't being executed also cleaned by user3814670 by adding the lines
if (mysql_query($sql)) {
echo "New record created successfully";
}
try to print your query to the screen and executing it in you database to see if your query fails or print the error to screen
mysql_error()
add this on top of your file after
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Here's how you display data from the database using while loop
while($row=mysql_fetch_array($result)) {
echo $row['FN'] . " " . $row['LN'] . " " . $row['Email'];
}
I keep getting this error:
Fatal error: Unsupported operand types on line 34
And I'm not sure how to fix it, i am trying to make it so that the number that is entered into the form such as 10, will be the discount and it will echo the discounted price, can anyone help me fix this, here is the code
<!DOCTYPE html>
<html>
<head>
<title> Car Shop Cars! </title>
<link rel="stylesheet" type="css/text" href="style.css"
</head>
<body>
<div id="header">
</div>
<div id="carpic">
</div>
<div id="price">
<center> This is the Nissan 350z and costs 8,999,999 <br>
please enter your promo code </center>
</div>
<div id="form">
<form action="index.php" method="post">
<center> <input type="text" name="percent" id="percent" />
<input type="submit" /> </center>
</form>
<?php
$percent=$_POST['percent'];
$total=['8,999,999'];
/*calculation for discounted price */
$discount_value= ($total / 100) *$percent;
$final_price = $total - $discount_value;
echo $final_price;
?>
</div>
</body>
</html>
This is invalid
$total=['8,999,999'];
I guess you mean something like this
$total = 8999999;
Look at your code:
$discount_value = ($total / 100) * $percent;
^
|
So more specifically here:
$total / 100
^
|
If you put in there the value of $total you just have set the lines before;
$total = ['8,999,999'];
It will create this operation:
['8,999,999'] / 100
Which means you want to divide an array by 100. PHP does not support dividing arrays by integers, hence it gives the error. So when you try to divide an array by an integer, I have to tell you the truth and say that this is not possible with PHP.
All operators PHP support for arrays are on this website:
http://php.net/language.operators.array
If on the other hand you're concerned to first convert the value in the array into an integer number, then you need to add a convertion function to the operation:
$converter($total) / 100 # 89999.99
Where $converter is a function that parses the array:
$total = ['8,999,999'];
$converter = function (array $input) {
$string = reset($input);
$formatter = new NumberFormatter('en_GB', NumberFormatter::DECIMAL);
return $formatter->parse($string, NumberFormatter::TYPE_INT32);
};
var_dump($converter($total) / 100); # double(89999.99)
Hope this helps.
all the above are right but try also this :
if (isset($_POST['percent'])) {
$percent=$_POST['percent'];
$total='8999999';
/*calculation for discounted price */
$discount_value= ($total / 100) *$percent;
$final_price = $total - $discount_value;
echo $final_price;
}
not only the $total was wrong but you should verify is the form was submited before doing the calculations.
Why are you using this : $total=['8,999,999']; ? This is an error
Use it This way : $total= 8999999;
Solution To Discount is :
Just an example:
<?php
$percent = 10;
$total = 1000;
$discount_value= ($total / 100) *$percent;
echo $final_price = $total - $discount_value;
?>
NOTE: This version is only a suggestion to check for a numerical value.
If a numerical value is entered in the form field, it will show the new price afterwards.
Yet, if the field contains anything other than numbers, it will revert back to the original price.
I also noticed your <link rel="stylesheet" type="css/text" href="style.css" in your original code was incomplete.
It should have read as <link rel="stylesheet" type="css/text" href="style.css"> You left out the closing "greater than symbol" => >
Added the following code:
if (is_numeric ($_POST['percent']))
{
echo "<center>";
echo "Your new price is: $" . $final_price;
echo "</center>";
} else {
echo "<center>";
echo "Please enter your promo code. <br>The current price is: $" . $final_price;
echo "</center>";
}
Please feel free to use it at your disposal. (I used a more realistic number for the price of the car).
<!DOCTYPE html>
<html>
<head>
<title> Car Shop Cars! </title>
<link rel="stylesheet" type="css/text" href="style.css" />
</head>
<body>
<div id="header">
</div>
<div id="carpic">
</div>
<div id="price">
<center> This is the Nissan 350z and costs $35,000.00<br>
</center>
</div>
<div id="form">
<form action="index.php" method="post">
<center> <input type="text" name="percent" id="percent" />
<input type="submit" /> </center>
</form>
<?php
$percent=$_POST['percent'];
$total = 35000;
/*calculation for discounted price */
$discount_value= ($total / 100) *$percent;
// I added this below
$final_price = $total - $discount_value;
$final_price = number_format($final_price);
number_format($final_price, 2, '.', '');
if (is_numeric ($_POST['percent']))
{
echo "<center>";
echo "Your new price is: $" . $final_price;
echo "</center>";
} else {
echo "<center>";
echo "Please enter your promo code. <br>The current price is: $" . $final_price;
echo "</center>";
}
?>
</div>
</body>
</html>
Hello: I am using signaturePad [http://thomasjbradley.ca/lab/signature-pad/]and have created a short web form in codeIgniter 2, located here: [http://gentest.lfwebz.com/crd/open_form3], that requires the users to actually sign the form.
I have also installed mPDF and domPDF and I have them working, sort of, but not quite the way I want it to.
The functionality I want is this: User opens web form, fills it out, signs it,
using signPad mentioned above. I then want to click a button that runs mPDF/domPDF and
captures the page and of course the embedded signature.
When I run mpdf/domPDF and pass it the view that houses the form, I think I have figured out it is just grabbing a fresh view, one without the signature, but several parts
of the form are missing. So after digging around, I think I have determined that I have to use image conversion of the signaturePad - this is where I am stuck. I have the code in, using the reference here: Signature pad and dompdf, but it does not work.
If you go to my page here: http://gentest.lfwebz.com/crd/open_form3, sign the page, click the "I accept" button
Here is my view
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../assets/jquery.signaturepad.css" media="screen">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="../jquery.signaturepad.min.js"></script>
</head>
<body>
<?php echo base_url(); ?>
<form method="post" action="<?php echo base_url(); ?>pdf.php" class="sigPad">
<label for="name">Print your name</label>
<input type="text" name="name" id="name" class="name">
<p class="typeItDesc">Review your signature</p>
<p class="drawItDesc">Draw your signature</p>
<ul class="sigNav">
<li class="typeIt">Type It</li>
<li class="drawIt">Draw It</li>
<li class="clearButton">Clear</li>
</ul>
<div class="sig sigWrapper">
<div class="typed"></div>
<canvas class="pad" width="198" height="55"></canvas>
<input type="text" name="output" class="output">
<input type="text" name="imgOutput" class="imgOutput">
</div>
<br /><br /><br />
<button type="submit">I accept the terms of this agreement.</button>
</form>
<script>
var sig;
$( document ).ready( function ( ) {
sig = $('.sigPad').signaturePad({defaultAction:'drawIt'});
} );
$( '.sigPad' ).submit( function ( evt ) {
$( '.imgOutput' ).val( sig.getSignatureImage( ) );
} );
</script>
</body>
</html>
here is the controller or the pdf.php mentioned above:
<?php
if(isset($_POST['imgOutput'])){$img_output = $_POST['imgOutput'];}
echo "position 1";
$bse = preg_replace('#^data:image/[^;]+;base64,#', '', $img_output );
echo "position 2";
echo $bse;
if ( base64_encode( base64_decode( $bse) ) === $bse ) {
require_once 'dompdf/dompdf_config.inc.php';
$html = '<!DOCTYPE html><html><head></head><body><p>Your signature:</p><br /><img src="'. $img_output .'"></body></html>';
$dompdf = new DOMPDF;
$dompdf->load_html( $html );
$dompdf->render( );
$dompdf->stream("test.pdf");
}
else{
echo ("ERROR !");
}
?>
What am I missing here? Please could some one point me in the right direction?
Let me know if you need more info.
Thank you in advance.