Storing formated text in sql php - php

I have created a certain form for my website that includes a Textarea with formatted text option so that the user can bold, underline, italics but also insert bulleted points and ordered list or even changing the font type and size.
The problem is when the user opts to insert ordered list then click the submit button the information is stored in the server as [ol] enclosed in square brackets which is not appropriate especially when I want to display the information on the website so I was thinking maybe if the information could be stored as enclosed in HTML tags it will make it easier for displaying the information on the website whenever such information is called.
My question is how can I store the information in tags(<>) instead of the ones enclosed in square brackets[]?
here is the code that gets the data from the form I tried to use the htmlspecialchars function but it didn't work.
<?php
session_start();
include 'connect.php';
$servername = $_SERVER['PHP_SELF'];
$username = 'root';
$password = '';
$dbname = 'members';
$tablename = 'jobs';
if (isset($_SESSION['username'])){ $sessionuser =
$_SESSION['username'];}
else if (isset($_SESSION['company'])){$sessionuser =
$_SESSION['company'];}
if(isset($_POST['company_name'])){
$company_name = $_POST['company_name'];
}
else if(isset($_SESSION['company'])){ $company_name = $_POST['company'];
}
$company_website = $_POST['company_website'];
$job_requirement = htmlspecialchars($_POST['job_requirement']);
$location = $_POST['location'];
$job_title = $_POST['job_title'];
$application_email_url = $_POST['application_email_url'];
$application_deadline = $_POST['application_deadline'];
$category = $_POST['category'];
$job_type = $_POST['job_type'];
if($_SERVER['REQUEST_METHOD']){
$sql = "INSERT INTO $tablename (`Company_name`, `Company_website`,
`Job_requirement`, `Location`, `Job_title`, `Application_deadline`,
`Category`, `Job_type`, `username`,`application_email_url`)
VALUE('$company_name', '$company_website', '$job_requirement',
'$location', '$job_title', '$application_deadline', '$category',
'$job_type', '$sessionuser', '$application_email_url')";}
if($conn->query($sql)===TRUE){ print "your job has been posted";}
else{echo "error" .$conn->error;}
?>

Try using htmlspecialchars() on the string to put into the DB, and then, when pulling it back out, use htmlspecialchars_decode(). Might make a difference.

Related

Multiple criteria replace mysql record with php

I am collecting data from a html form, submitting the data to mysql using a php script.
However, I can't figure out how to replace/update a record if multiple criteria match.
If a new submitted record from the html form, has the same 'type', 'volume' and 'place_name' as an existing record, it should replace the 'price'.
At this moment, it is just writing a new line with the new data.
Can anyone please help me with this? Thanks!
Please see my php code below:
<?php
require("config.php");
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'DB3469638'))
{
echo 'Database Not Selected';
}
$type= $_POST['type'];
$volume= $_POST['volume'];
$price= $_POST['price'];
$email = $_POST['email'];
$place_name = mysqli_real_escape_string($con, $_POST['place_name']);
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$location = mysqli_real_escape_string($con, $_POST['location']);
$sql = "INSERT INTO markers (type, volume, price, place_name,
place_Location, email, place_Lat,place_Lng)
VALUES ('$type','$volume','$price','$place_name',
'$location','$email','$lat','$lng')";
if(!mysqli_query($con,$sql))
{
echo 'Not Inserted';
}
else
{
header("refresh:4; url=addprice.php");
echo "<div align='center' style ='font:40px/60px Arial,tahoma,sans-
serif;color:#ffffff'> Submitted! <br><br> Redirecting Automatically
</div>";
}
?>
First you would want to create a multi-column index in SQL on the columns you don't want to be duplicates:
CREATE INDEX multiIndex ON markers (type, volume, place_name);
Now you can use ON DUPLICATE KEY UPDATE in your PHP:
$sql = "
INSERT INTO markers
(type, volume, price, place_name, place_Location, email, place_Lat,place_Lng)
VALUES
('$type','$volume','$price','$place_name', '$location','$email','$lat','$lng')
ON DUPLICATE KEY UPDATE
price = '$price'
";
First of all, you should find out if this is a new record, or an update of an existing one. To do this, you must either incorporate IDs (recommended) or query the database first (where type, volume and place_name matches with provided one - not recommended).
Beside this, you should avoid SQL injections by not using user input directly in your SQL queries.

Best data type to store long text like news, articles.

This is my problem when im trying to store news entry some of those entries are inserting but some are not. I don't know if the problem is on the data type. Im just copying some news i found in internet and paste it to my form. Can someone help me about this?
my database structure..
sample of the news that are not inserting. i copy this text in the wiki and paste it to my news content input. and didnt work.
sample of news that successfuly inserted
here is my code for adding.
<?php
include_once('connection.php');
session_start();
$username = ucfirst($_SESSION['username']);
if(isset($_POST['submit'])){
$title = $_POST['title'];
$date = $_POST['date'];
$content = $_POST['content'];
$file=$_FILES['image']['tmp_name'];
$image= #addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"img/" . $_FILES["image"]["name"]);
$newsimage="img/" . $_FILES["image"]["name"];
$sql ="INSERT into news (news_title, news_date, news_content, news_image) VALUES ('$title', '$date', '$content', '$newsimage')";
mysqli_query($con, $sql);
echo '<div class="alert alert-success alert-dismissable" id="success-alert">';
echo '<strong>Successfully posted!</strong>';
echo '</div>';
}
?>
Few things could go wrong here.
You need to use POST instead of GET while posting form data.
If data is successfully posted escape text before inserting it into the db with:
$content = mysqli_real_escape_string(stripslashes($_POST['content']));
LONGTEXT is just fine for longer text. You don't need LONGBLOB unless you are using binary data (like pictures etc.)
I solved it by changing the $content = $_POST['content']; to $content = mysqli_real_escape_string($con,$_POST['content']);

Updating database info from php, not saving

I have this code and it seems to be working. The values are updating, but when I reload the page the updated values are without any value. For example now I have set the title as "blablabla" and when I reload the page it's changing to "".
This is the code
<?php
$title = $_POST['title'];
$meta = $_POST['meta'];
$email = $_POST['email'];
$analytics = $_POST['analytics'];
$query = "UPDATE websettings SET title = '$title', meta = '$meta', email = '$email', analytics = '$analytics' WHERE id = '1'";
if(mysql_query($query)){
echo "success";
}
else {
echo "fail";
}
?>
Your code applies $_POST variables to the database, but doesn't check if the client actually posted anything. Better to check if $_POST contains array items (if a form was posted), and check if each of those is set (if the user filled in the right fields), and validate the user input before saving (phone numbers, emails etc formatted correctly).
And as was pointed out in the comments you are vulnerable to SQL injection attack - one of the first things you should address.
Try turning on more PHP errors too - these would flag as unset variables for quicker fixing.

How could I prepend a field in a php form

I'm looking for a sql statement where I can add additoinal text to a form field when being submitted to a mysql database. For example: A field contains a file name that has been loaded to a Web server called "mydoc.pdf". I want to prepend the following text "http://www.example.com/uploads/", so when the form is submitted the field data becomes "http://www.example.com/uploads/mydoc.pdf".
Right now the unappended field "tofiles_link" uses the following mysql query statement to insert to the mysql database:
mysql_query("INSERT INTO site_tofiles (tofiles_title, tofiles_body,
tofiles_link, tofiles_relation, tofiles_type, tofiles_post_ip,
tofiles_post_user) VALUES
('".mysql_real_escape_string($_POST['tofiles_title'])."',
'".mysql_real_escape_string($_POST['tofiles_body'])."',
'".mysql_real_escape_string($_POST['tofiles_link'])."',
'".mysql_real_escape_string($_POST['tofiles_relation'])."',
'".mysql_real_escape_string($_POST['tofiles_type'])."',
'".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',
'".mysql_real_escape_string($_GET['tofiles_post_user'])."')");
echo "Data was Entered Successfully!\n";
mysql_close($conn);
Can this be modified to suit my puroses? THX
To make the code more readable I would do your escaping before creating the SQL query. Not required but makes the code easier to read.
$title = mysql_real_escape_string($_POST['tofiles_title']);
$body = mysql_real_escape_string($_POST['tofiles_body']);
$link = "http://www.example.com/uploads/" . mysql_real_escape_string($_POST['tofiles_link']);
$relation = mysql_real_escape_string($_POST['tofiles_relation']);
$type = mysql_real_escape_string($_POST['tofiles_type']);
$ip = $_SERVER['REMOTE_ADDR'];
$post_user = mysql_real_escape_string($_GET['tofiles_post_user']);
Notice the $link variable on the 3rd line above adds the URL to the string.
$sql = "INSERT INTO site_tofiles (tofiles_title, tofiles_body, tofiles_link, tofiles_relation, tofiles_type, tofiles_post_ip, tofiles_post_user) VALUES ";
$sql .= "('$title', '$body', '$link', '$relation', '$type', '$ip', '$post_user');";
mysql_query($sql);
echo "Data was Entered Successfully!\n";
mysql_close($conn);

PHP Callback - Data not being inserted into DB

Ok so I have 3 files, coinbase.php, si.php (callback file), and profile.php.
Profile.php is what contains my CSS and HTML and the payment button. It also holds the custom parameter I need.
Si.php:
<?
require 'db.php';
$data = json_decode(file_get_contents('php://input'), TRUE);
$text = print_r($data,true);
file_put_contents('coinbase.php', $text);
$id = $data['order']['id'];
$status = $data['order']['status'];
$amount = $data['order']['total_btc']['cents'];
$user = $data['order']['custom'];
mysql_query("INSERT INTO `invoices`(`username`, `invoice_id`, `price_in_btc`) VALUES ('$user', '$id', '$amount')");
if($status == 'completed') {
mysql_query("UDPATE `users` SET `gigagold` = `gigagold` + '$amount' WHERE `username` = '$user'");
}
?>
And coinbase.php is the file that receives the decoded JSON data from the callback when a payment is made through the button. BUT, whenever something is in inserted into the DB all the values say NULL or are empty.
I don't see any problems with my code except I'm thinking my queries are in the wrong file?
Thanks.

Categories