How could I prepend a field in a php form - php

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);

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.

Storing formated text in sql 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.

PHP and SQL one page insert into database

I have written a PHP page with a form on the submit button I set the action to the PHP form page.
<form id="form1" method="post" action="../control_lbs/lbs_trace.php">
The INSERT INTO is basic sql load information to the database.
The problem i have every time I open the page it sends blank information to the rows. Is there away I can prevent this from happening?
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req,
lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES
('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]'
,'$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
The above is my PHP action code
This is the new code and full code I use
if ($con = mysql_connect($host, $username, $password)) {
if ( !empty($_POST["send"])) {
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES ('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]','$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
On refresh or page entry it still gives me blank info on Database
You need to use isset() to see if the $_POST variables are set. I've use $_POST in the example below, I suggest you give the submitbutton a name (like example) and use isset($_POST['example']):
if( isset($_POST) ){
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES(
'".$_POST['lbs_msisdn']."',
'".$_POST['lbs_req_by']."',
'".$_POST['lbs_date_req']."',
'".$_POST['lbs_reason']."',
'".$_POST['lbs_station']."',
'".$_POST['lbs_cas']."',
'".$_POST['lbs_traced_by']."'
)";
echo $sql; // echo it to see if it has any values
// print_r($_POST); // in case the query is still empty, uncomment this. It will show you the values in the POST array
}

Enter variable into sql table Problems

Ok I am having problems insert a variable into a sql table. Heres my code
if (isset ($_GET['comment']))
$commentEntered = $_GET['comment'];
else
$commentEntered = "refuse";
Above I get the variable
Then I try to pass it to the database with the code below
$sql = "insert into $DB_Table (comment) values('$commentEntered');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
My problem is, When I pass a single word it works, But when the text box where comment is received has any spaces in it, It will not insert?
i.e - The user enters Hello - This works
The user enters Hello World - This doesn't work
Any help would be much appreciated!
try
$sql = "INSERT INTO " . $table . " (comment) " .
"VALUES ('" . mysql_real_espace_string($commentEntered) . "')";
Also, dump the var $commentEntered before the "$sql = ..." line just to see what it outputs to the screen.
var_dump($commentEntered);
And another thing, try switching from GET request method to POST and grab the data from $_POST.
try to call:
mysql_query("COMMIT");
before closing the connection.

PHP - Dynamic SQL Query from Dynamic POSTs

First time question, long time reader :)
I am building forms dynamically from Columns in a MYSQL DB. These columns
are created/ deleted etc.. elsewhere on my App. My form runs a query against a
SQL View and pulls in the column names and count of columns. Simple! build the form,
with the HTML inputs built with a PHP for loop, and it echos out the relevant HTML for the new form fields. All very easy so far.
Now i want a user to update these dynamically added fields and have the data added to the relevant columns - same table
as existing columns. So, as the input fields are named the same as the columns, they are posted to a PHP script for processing.
Problem is, while i have the actual field names inserted in to the SQL INSERT query, i cannot figure out how to extract the POST
data from the POST dynamically and add this to the VALUEs section of the query.
Here is my attempt....
The Query works without the variables added to it.
It works like this, first section/ is to retrieve the columns names from earlier created VIEW - as these are identical to POST names from the form. Then output to array and variable for insertion to Query. It looks like the implode function works, in that the relevant column names are correct in the statement, but i fear that my attempt to inject the column names on to the POST variables is not working.
$custq = "SELECT * FROM customProperties";
$result = $database->query($custq);
$num_rows = mysql_numrows($result);
while (list($temp) = mysql_fetch_row($result)) {
$columns[] = $temp;
}
$query = '';
foreach($columns as $key=>$value)
{
if(!empty($columns[$key]))
{
$values .= "'".'$_POST'."['".$value."'], ";
}
}
$q = "INSERT INTO nodes
(deviceName,
deviceInfo,
".implode(", ", $columns).",
nodeDateAdded,
status
)
VALUES
('" . $_POST['deviceName'] . "',
'" . $_POST['deviceInfo'] . "',
".$values."
CURDATE(),
'1'
)";
$result = $database->query($q)
Any help is much appreciated. I will feed back as much as i can. Please note, relativity new to PHP, so if i am all wrong on this, i will be glad for any tips/ advice
Regards
Stephen
If you want to get the values of every POST input without knowing the input names then you can do it this way:
//get all form inputs
foreach($_POST as $name => $value)
{
echo $name . " " . $value . "<br>";
}
If you want to get the value of certain POST inputs where you know the name of the input field then you can do it this way:
if(isset( $_GET["deviceName"]))
{
$deviceName = $_POST["deviceName"];
}
if(isset( $_GET["deviceInfo"]))
{
$deviceInfo = $_POST["deviceInfo"];
}
To connect to a database and insert the info then you have to do something like this:
$host = "localhost";
$dbuser = "username";
$pass = "password";
$datab = "databasename";
//Create DB connection
$con=mysqli_connect($host, $dbuser, $pass,$datab);
if (mysqli_connect_errno($con))
{
echo "ERROR: Failed to connect to the database: " . mysqli_connect_error();
}
else
{
echo "Connected to Database!";
}
//insert into database
mysqli_query($con, "INSERT INTO nodes (deviceName, deviceInfo) VALUES ('$deviceName', '$deviceInfo')");
(Don't forget to add mysql_real_escape_string to the $_POST lines after you get it working.)

Categories