Discounts with PHP - html

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>

Related

Pull Random Data from mySQL

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/

URL API (JSon) store in MySql

i want to store API result in database
i am new to this API php coding things,
<?php
$account_id = 1122;
$api = "http://url&account_id";
$json = file_get_contents($api);
print_r($json);
?>
here is the output
{"status":"ok","count":1,"meta":{"count":1},"data":{"1122":{"statistics":{"all":{"wins":112,"losses":118},"xp":721},"nickname":"nickie"}}}
now i want to store data in variables and as well want to show in Tables.
for saving it in variables i am using this method.
$nickname = $decoded->{'data'}->{$account_id}->{'nickname'};
$max_xp = $decoded->{'data'}->{$account_id}->{'statistics'}->{'xp'};
how can i show all data in tables. or anywhere on main body page.
sorry for my bad poor programming, i am trying to so learn it.
in this case if I understand correctly, it is necessary to create an HTML form you with two text boxes, you can later send this form in a PHP page that can retrieve the values of these input fields and create the URL for the API:
An HTML page
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Your page title</title>
</head>
<body>
<div>
<form method="post" action="/your/php/file">
<div>
<label for="name" />
<input type="text" name="username" id="name" />
</div>
<div>
<label for="location" />
<input type="text" name="location" id="location" />
</div>
<div>
<button>Submit</button>
</div>
</form>
</div>
</body>
</html>
A PHP page
<?php
if (isset($_POST['username'], $_POST['location']) && !empty($_POST['username']) && !empty($_POST['location'])) {
$username = htmlspecialchars($_POST['username']);
$location = htmlspecialchars($_POST['location']);
$account_id = 1122;
$api = "http://url?account_id&username={$username}&location={$location}";
$json = file_get_contents($api);
//now you have result as associative array
$result = json_decode($json, true);
//you can do what you want now
}
?>
Try to json_decode your results like this:
<?php
$account_id = 1122;
$api = "http://url&account_id";
$json = file_get_contents($api);
//now you have result as associative array
$result = json_decode($json, true);
//print_r($result);
$nickname = $result['data'][$account_id]['nickname'];
?>
try and tell me what

How do I get codeIgniter 2, Bradley - SignaturePad and DomPDF to work correctly

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.

How do I exclude duplicates entries in a CSV-file from being importing into MySQL?

I have a CSV file with many duplicate entries. How do I import the entries into MySQL without also importing the duplicates?
You could define one of the columns (one where you are sure that there will be duplicate data) as UNIQUE in MySQL, and then import everything and just let the DB spit out errors in the duplicate entries.
This is simple code for import the entries into MySQL without also importing the duplicates and count the number of records and number of duplicate
<?php
$duplicate=0;
$record=0;
$total=0;
$conn=mysql_connect("localhost","root","rootpass","") or die(mysql_error());
mysql_select_db("svn",$conn);
ini_set('max_execution_time', 300);
if(isset($_POST['submit']))
{
$file=$_FILES['file']['tmp_name'];
$handle=fopen($file,"r");
while(($fileop=fgetcsv($handle,1000,",")) !== false)
{
if(! get_magic_quotes_gpc() )
{
$fn= addslashes ($fileop[0]);
$ln=addslashes ($fileop[1]);
$ti=addslashes ($fileop[2]);
$ac=addslashes ($fileop[3]);
$em=addslashes ($fileop[4]);
$op=addslashes ($fileop[5]);
$mp=addslashes ($fileop[6]);
$fx=addslashes ($fileop[7]);
$ad=addslashes ($fileop[8]);
$co=addslashes ($fileop[9]);
$st=addslashes ($fileop[10]);
$ci=addslashes ($fileop[11]);
$zc=addslashes ($fileop[12]);
}
else
{
$fn= $fileop[0];
$ln=$fileop[1];
$ti=$fileop[2];
$ac=$fileop[3];
$em=$fileop[4];
$op=$fileop[5];
$mp=$fileop[6];
$fx=$fileop[7];
$ad=$fileop[8];
$co=$fileop[9];
$st=$fileop[10];
$ci=$fileop[11];
$zc=$fileop[12];
}
$query=mysql_query("SELECT * FROM test WHERE email='$em'");
if(mysql_num_rows($query)>0)
{
$duplicate=$duplicate+1;
}
else
{
$record=$record+1;
$sql=mysql_query("INSERT INTO test(first_name,last_name,title,account,email,officephone,mobphone,fax,address,country,state,city,zipcode)
VALUES('$fn','$ln','$ti','$ac','$em','$op','$mp','$fx','$ad','$co','$st','$ci','$zc')");
}
}
echo"Data inserted successfully";
echo "<table width='600' cellpadding='5' cellspacing='5' border='1'>";
echo "<tr>"."<td>"."Record inserted"."</td>"."<td>".$record."</td>"."</tr>";
echo "<tr>"."<td>"."duplicate record"."</td>"."<td>".$duplicate."</td>"."</tr>";
echo "<tr>"."<td>"."Total records"."</td>"."<td>".$total=$record + $duplicate."</td>"."</tr>";
echo "</table>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<?
$duplicate=0;
$record=0;
$total=0;
?>
</head>
<body>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" value="selectfile"/><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Displaying unnecessary HTML when showing content from MySQL database

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)