Button to trigger jQuery to grab HTML and save to database - php

I have some jQuery that when you click the save button it triggers a function to grab the HTML matching a selector and post the HTML to save_report.php:
function saveReport() {
$.post('save_report.php', function(data) {
$('.report').html(data);
});
}
$('.save').click(function () {
saveReport();
});
In save_report.php I want to know how i can then save that string to my db.
$report = $_POST['']; # <-- not sure how to post
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO reports (id, report) VALUES('', $report) ")
or die(mysql_error());
How do I retrieve the POST value in my php file?
Thanks

Couple of things wrong here... The posted code doesn't actually post any data, and the post and html functions are called incorrectly.
So, first I'll grab the html from the .report selector, and store it in a variable. Then I'll post it providing a variable name of 'report'. I added a simple callback that alerts what the web server sends back, which you can remove or change.
function saveReport() {
var data = $('.report').html();
$.post('save_report.php', {'report':data}, function(response) { alert(response); });
}
$('.save').click(function () { saveReport(); });
In your PHP, you would be looking for $_POST['report'] which is how I named the data being posted.
You're not sanitizing any of the input, so basically any random hacker could take over your entire database with SQL injection. At a minimum, after getting $_POST['report'], run it through the mysql_real_escape_string() function.

Most likely you need to change your jQuery code to
function saveReport() {
$.post('save_report.php', {report: $('.report').html(data)} );
}
and php to
$report = $_POST['report']; **<-- not sure how to post**
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO reports
(id, report) VALUES('', '".mysql_real_escape_string($report)."' ) ")
or die(mysql_error());

Please don't forget to escape the HTML before you put it in your insert query. What you're doing has the potential to go very wrong very fast. I've modified your save_report.php code to fit Fosco's answer. I am now passing the 'optional' $link parameter to all of the mysql_* functions because in general it is a best practice to do so. I've also added some escaping of the value before it is used in your INSERT query; It is important to pass the $link parameter to the mysql_real_escape_string() function so it can properly escape the value.
$report = $_POST['report'];
$link = mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database", $link) or die(mysql_error());
$report = mysql_real_escape_string($report, $link);
mysql_query("INSERT INTO reports (id, report) VALUES('', '{$report}')", $link)
or die(mysql_error());

Related

How can I insert data held within a square bracket array into a database?

I'm trying to insert some data into a database, I have the following code which is connecting to the database but not inserting any results (just empty rows).
I know the below code doesn't work, I've just tried to explain in PHP what I want. The issue is with the data being held in an array such as $tweet['created_at'] and I need this in a variable format so I can insert it into the database.
Any help is greatly appreciated, thank you!!
if ($_GET) {
$conn = mysql_connect('localhost', 'user', 'pass')
or die (mysql_error());
$tweet['created_at']=$tweet_created_at;
$tweet['text']=$tweet_text;
$tweet['location']=$tweet_location;
$tweet['followers_count']=$tweet_followers_count;
$tweet['sentiment']=$tweet_sentiment;
mysql_select_db("db") or die(mysql_error());
mysql_query("INSERT INTO table (Created_at, Tweet, Location, Number_of_Followers, Semantic_Result) VALUES ('$tweet_created_at', '$tweet_text', '$tweet_location', '$tweet_followers_count', '$tweet_sentiment')", $dbconnect);
}
Mysql only understands SQL. So to insert an array into a mysql database you have to convert it to an sql statement. This can be done manually or by a library. The output should be an INSERT statement.
$columns = implode(", ",array_keys($tweet));
$values = array_map('mysql_real_escape_string', array_values($tweet));
$values = implode(", ", $values);
$sql = "INSERT INTO `table `($columns) VALUES ($values)";
You can do something like this:
if ($_GET) {
$conn = mysql_connect('localhost', 'user', 'pass')
or die (mysql_error());
$tweet['created_at']=$tweet_created_at;
$tweet['text']=$tweet_text;
$tweet['location']=$tweet_location;
$tweet['followers_count']=$tweet_followers_count;
$tweet['sentiment']=$tweet_sentiment;
mysql_select_db("db") or die(mysql_error());
mysql_query('INSERT INTO `table` (`'.implode('`,`',array_keys($tweet)).'`) VALUES ('.implode("','",array_map('mysql_real_escape_string',$tweet)).')');
}
I included mysql_real_escape_string because you should always escape your data. If your database still has empty data then check the character encoding and make sure that the fields in the database are defined properly. such as INT for followers, TEXT for 'text', etc...
Edit: I suspect you're trying to retrieve data from input fields. Make sure the form does not "POST" (<form method="post">) and that the field names match. you should also use $_SERVER['REQUEST_METHOD'] to determine request.
if the data is in the url. I.E: page.php?created_at=xxx&.... Then this works fine...
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$conn = mysql_connect('localhost', 'user', 'pass') or die (mysql_error());
$tweet['created_at']=$_GET['tweet_created_at'];
$tweet['text']=$_GET['tweet_text'];
$tweet['location']=$_GET['tweet_location'];
$tweet['followers_count']=$_GET['tweet_followers_count'];
$tweet['sentiment']=$_GET['tweet_sentiment'];
mysql_select_db("db") or die(mysql_error());
mysql_query('INSERT INTO `table` (`'.implode('`,`',array_keys($tweet)).'`) VALUES ('.implode("','",array_map('mysql_real_escape_string',$tweet)).')');
}
Cheers guys, I've used some of your suggestions and I've got it working.
I replaced:
$tweet['created_at']=$tweet_created_at;
with:
$created_at = mysql_real_escape_string( $tweet['created_at'] );
and used the implode attribute
Now it works fine!
Thanks!!!

I am trying to store form information in a mysql database but it does not foward to the database

So I have a form and the form action= the file that contains the code below. I am getting a connection but the data is not saving. I formatted my form with input type textarea and the database with long text because I want to give the user as much space as they need to write their information. I think this might be my issue and have been searching the web to see if it is but I can't find anything that says it is or not. The weird part is that one time i did see an increase in the row of the database but when I checked it the row didn't contain the info I sent, it was blank.
<?php
session_start();
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ='0')
{header('location:shareerror.php');}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
header ('location:thanks.php'); }
?>
By mistake you are assigning instead of checking corrected statement is:
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ==0)
There is an error in your query
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
change this to
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
You are not setting the values for $recipe, $usrtext and $usrtxt
You are missing a comma in the values.
You are using strlen instead of isset
Also please take a look at How can I prevent SQL injection in PHP?. Your code is vulnerable to sql injection.
Here is the fixed code (with sql injection vulnerability intact!!)
<?php
session_start();
if (!isset($_POST['recipe'])|| !isset($_POST['usrtext'])||!isset($_POST['usrtxt']))
{
header('location:shareerror.php');
}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$usrtxt = $_POST['usrtxt'];
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext','$usrtxt')");
header('location:thanks.php');
}
?>
Also you didn't assign the variables used in the query.
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
do that like this:
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$urstxt = $_POST['usertxt'];
Then you can use the variables in the query

mysql_query not inserting anything into my database

I have this bit of code here:
<?php
error_reporting(E_ALL);
include 'DB.php';
$con = mysql_connect($host,$user,$pass)
or die("Error: ".mysql_error());
$dbs = mysql_select_db($databaseName, $con);
$name = $_POST['name'];
$date = date('Y-m-d');
$amount = $_POST['amount'];
$timPaid = $_POST['timPaid'];
$rennyPaid = $_POST['rennyPaid'];
$sql = "INSERT INTO $tableName (`name`, `date`, `amount`, `timpaid`, `rennypaid`)
VALUES ('$name', '$date', '$amount', '$timPaid', '$rennyPaid')";
$result = mysql_query($con, $sql)
or die("Error: ".mysql_error());
mysqli_close($con);
?>
DB.php is my database settings. I call a query to it on page load and it connects and pulls data fine, so I know it's not an issue there. I also don't get any errors. I get a status code 200 OK on the post.
Here's the ajax post:
var name = $('#name').val();
var amount = $('#amount').val();
var timPaid = $('#timPaid').val();
var rennyPaid = $('#rennyPaid').val();
var data = $('#newSubmissionForm').serialize();
$.ajax({
url: 'insert.php',
data: data,
type: 'post',
success: function()
{
window.location.href = '';
}
});
Does it have something to do with me serializing it?
I hope this is enough info. Thanks!
mysql_query requires first parameter as query and second parameter as connection object (optional)
change this
$result = mysql_query($con, $sql);
to
$result = mysql_query($sql, $con);
Also you used mysql for connection and query but you used mysqli to close the connection.
You have likely just switched the $sql and $con statement. in mysql_query $sql should be the first parameter. It's easy to forget, since mysqli_query should have $con as the first. :/
php die() statement is the same as exit, and will end the script with status 200. Likely you DO get an error in the output. Try viewing it in e.g developer console (Chrome)
check in internet explorer which code is generated
(inspect element)
add to the beginning of your session php file
<?php
echo '<pre>';
var_dump($_POST);
die();
?>
This will show the values that are sent to the database.

MySQL not saving sentence after an '

This one has got me stumped. When I try to save something to the database that contains an apostrophe ('), it will save the sence up until then and after that it does not not. For example;
Say I am trying to save this: Report details Tim Cook's changes at Apple, for better or worse ยป
It saves: Report details Tim Cook
It saves to the database fine but only everything before the '
My code:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Any help as to why it might not be saving properly? I have tried mysql_real_escape_string but (if I am using it correctly) that does not seem to work.
Side note: What is the best way to secure the form above from attacks?
Update It is also doing it for " as well.
You need to call mysql_real_escape_string() after connecting to your database:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Change
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
to
$query = "INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')";
echo $query;
mysql_query($query);
And check out the actual query you are sending, easy to spot the problems then :)

PHP will not delete from MySQL

For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!

Categories