update table in mysql when user loses focus of a textarea? - php

I want users of my site to be able to update their profile information by clicking into a textarea. When they type in some text and click out of the text area (on blur), I want this to update a table in my database called 'bio'.
I have been working on this for several days, I'm ashamed to admit but I am really new to php and sql so I am learning as I go along. I have tried to make sense of a script but it's probably completely wrong. Can someone please advise me of what I need to do?
Here's my code:
<textarea id="bio" style="width: 456px;
margin-top:3px;
text-align:left;
margin-left:-2px;
height: 120px;
resize: none;
border: hidden;" textarea name="bio" data-id="bio">
<?php echo $profile['bio'] ?>
</textarea>
<script type="text/javascript">
$('textarea').on('blur',function () {
var bioVal = $(this).val(),
id = $(this).data('id');
$.ajax({
type: "POST",
url: "includes/changebio.php",
data: {bio:bioVal , id:id},
success: function(msg) {
$('#bio-' + id).val(msg);
}
})
});
</script>
Here's the url php file that should do the work:
function update_profilebio() {
global $connection;
global $profile_id;
$query = "UPDATE ptb_profiles
SET bio=''
WHERE ptb_profiles.user_id = \"$profile_id\"
AND ptb_profiles.user_id = ptb_users.id";
$update_profilebio_set = mysql_query($query, $connection);
confirm_query($update_profilebio_set);
return $update_profilebio_set;
}

I checked HTML+JavaScript code and AJAX POST request is sending data correctly to the PHP script (You may check this in Chrome Developer Tools or with Firebug add-on).
This changebio.php script has only definition of this update_profilebio() function ? Definition alone won't execute this function, you need to call it.
<?php
update_profilebio(); // tells php to call the function, defined below
function update_profilebio() {
global $connection;
global $profile_id;
$query = "UPDATE ptb_profiles
SET bio=''
WHERE ptb_profiles.user_id = \"$profile_id\"
AND ptb_profiles.user_id = ptb_users.id";
$update_profilebio_set = mysql_query($query, $connection);
confirm_query($update_profilebio_set);
return $update_profilebio_set;
}
?>
Also, SQL query has two conditions and I don't understand this part "...AND ptb_profiles.user_id = ptb_users.id ". You update only one column in one table, the only thing you need is user id which you provide in first where condition.

Your HTML + jQuery code looks ok, just cheng php output <?php echo $profile['bio'] ?> by adding htmlspecialchars, that will help you avoid some trouble
<?php echo htmlspecialchars($profile['bio']); ?>
The thing that fails in your code is SQL query; you are setting bio to empty text. Also you have condition on matching user_id with other table id, but you have not joined this table in your query. Just requiring user_id to be equal to given integer is enough. Also remember to escape user input properly, to prevent them from injecting malicious code into your database.
SQL should look like this:
$bio = mysql_real_escape_string($_POST['bio']);
$query = "
UPDATE
ptb_profiles
SET
bio='{$bio}'
WHERE
ptb_profiles.user_id = " . intval($profile_id);

You got your quoting wrong, try something like this
$query = "UPDATE ptb_profiles SET bio='".$_REQUEST['bio']."'
WHERE ptb_profiles.user_id = ".$profile_id;
SQL usually uses single quotes, PHP uses both.

Related

How do i use AJAX to update my page after running a PHP function?

So i'm trying to make some text appear on my web page after a user clicks a button and runs a mysql function, but my AJAX function is only running the mysql function without doing anything else, i'm a little confused on what exactly i'm supposed to write to get it to update my page.
AJAX:
<script>$(document).ready(function(){
var game = 69;
var review = 21;
$('#fav').click(function(){
$(document).load('core/like.php', {
thegame: game,
thereview: review
});
});
});</script>"
PHP (core/like.php)
<?php
session_start();
if (isset($_SESSION['username'])) {
require 'connect.php';
$thegame = $_POST['thegame'];
$thereview = $_POST['thereview'];
$username = $_SESSION['username'];
$datentime = date("m/d/Y h:i:s a");
$stmt = $conn->prepare("UPDATE reviews SET likes=likes+1 WHERE r_id='$thereview'");
$stmt2 = $conn->prepare("INSERT INTO likes (l_id, username, r_id, date) VALUES (NULL, '$username', '$thereview', '$datentime')");
$stmt->execute();
$stmt2->execute();
$stmt->close();
$stmt2->close();
$conn->close();
echo "<div id="content"><h1>THIS IS A TEST</h1></div>";
exit();
} else {
echo "<h1>ERROR</h1>";
}
?>
Also, it only runs the mysql query when i use "document" as the jQuery selector. If i try and use a specific div like $(#abox).load('core/like.php'.. it does nothing. If i try to add a selector at the end to specify what content from the php file i want to return like $(document).load('core/like.php #content'.., it also does nothing.
It seems that there are two problems:
There are nested double quotes in the PHP:
echo "<div id="content"><h1>THIS IS A TEST</h1></div>";
Use single quotes for the outer ones:
echo '<div id="content"><h1>THIS IS A TEST</h1></div>';
Use quotes around the jQuery selector:
$(#abox).load('core/like.php'...
Like this:
$("#abox").load('core/like.php'...
Also, please take serious note of the comment about SQL injection.

Saving javascript code inside database

I've very annoying problem with hosting of well known company however
I've website and at its back-end there is form has textarea field where it should be for google adsense code when i submit it does not respond at all and keep loading
but when i type anything else then adsense ads code it accepted so i noticed it not allowing for html
Form code
<form method=post action="1.php" name="adsense" id="adsense">
The Code : <textarea id="ad" name="ad">Put your code here</textarea>
<input type="submit" name="submit" value="Save">
</form>
1.php Code
<?PHP
include "header.php"; // connect to db
if(isset($_POST[submit])){
$qma = "update webads set
ad = '$_POST[ad]'";
$rma = mysql_query($qma) or die(mysql_error());
echo 'Thanks';
}
?>
The problem when i put adsense ads code it not respond and not save it in database but if i put any text it save it normally
so i've been thinking to addslashes() but it also didn't worked after i made such changes
ad1 = 'addslashes($_POST[ad1])'
here is example of unaccepted google adsense code
<script type="text/javascript">
google_ad_client = "pub-0000000000000000";
google_ad_width = 250;
google_ad_height = 250;
google_ad_format = "250x250_as";
google_ad_type = "text";
google_ad_channel = "0000000000";
google_color_border = "FFFCE1";
google_color_bg = "FFFCE1";
google_color_link = "FFFCE1";
google_color_text = "FFFCE1";
google_color_url = "FFFCE1";
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
One last note
the database field structure is text NOT NULL
CREATE TABLE `webads` (
`id` varchar(50) NOT NULL default '',
`ad` text NOT NULL
PRIMARY KEY (`id`))";
so any idea how to save it ! but it must be easy to recall it back without being altered
i don't know if it stupid or not but if i didn't got any answer how to do it, been thinking to base_64 encoder before save it then when i call it back will base_64 decode it but this sound last hope i can do
Thanks a lot
You need to escape the posted variable for MySQL - the best way to do this is to use PHP's built in function as it will do it correctly for your version of MySQL
$qma = "update webads set ad = '" . mysql_real_escape_string($_POST[ad]) . "'";
You have to use htmlentities before storing data to database.
and you can't use function inside string.
$ad = htmlentities($_POST['ad']);
Also when using addslashes you'd better first check if it's automatically enabled by server configuration, not to over-quote strings. See get_magic_quotes_gpc
if(!get_magic_quotes_gpc()) {
$ad = addslashes($ad);
}
...
$qma = "update webads set ad = '$ad'";
Alternately, you can use
$ad = htmlspecialchars($_POST['ad']);
$qma = "update webads set ad = '$ad'";
When I work with MySQL Workbench and I do something like update webads set
ad = '$_POST[ad]' it throws an error because of the safe mode. My SQL query doesn't have an ID. Maybe the safe mode is on?
If you want to bypass it, just add WHERE ID != -1 but I don't recommend doing this.
Don't forget to sanitize your input.

php variable through jquery ajax to external php

i found a php/jquery/ajax script that has a textfield that is sent after the user clicks the input to an external php script to be written into a mysql database.
http://gazpo.com/2011/09/contenteditable/
whats missing is the userid passed into the external php file:
$sql = "UPDATE customer SET comment = '$content' WHERE userid = 12345 ";
here is what i do:
i am catching the user id in the main file with:
$s = $_GET['contact'];
from the url parameter.
then i put it in to my db select in the main php:
$sql = "select customer from user where userid = $s";
then there are some div
<div id="content">
<div id="editable" contentEditable="true">
followed by the ajax script:
$(document).ready(function() {
$("#save").click(function (e) {
var content = $('#editable').html();
var content_two = $('#editable_two').html();
$.ajax({
url: 'save2.php',
type: 'POST',
data: {
content: content
},
in the save.php there is this:
$content = $_POST['content']; //get posted data
$sql = "UPDATE customer SET comment = '$content' WHERE userid = "XXXX" ";
So: how do i get the $s variable from my url parameter into the "XXXX"
As others pointed out in comments that seem to be quitly ignored , you really need to check this out, since the way you build your query is very insecure. Please read about SQL injection.
Add userid to the data you pass from your ajax call back to save.php.
data: {
content: content,
userid: <?= $s ?>
}
This is a guess without seeing the rest of your code and how the code actually renders the page.
Thanx alot for the hint.I changed theses lines:
In Ajax/Jquery section of the main php file:
$("#save").click(function (e) {
var content = $('#editable').html()
var nr = <?php echo $s; ?>;
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content,
nr: nr
}
And in the external save.php i added this:
$s = $_POST['nr'];
and also included the variable into $s into my sql update section:
$sql = "UPDATE ADRESSEN SET BEMERKUNG = '$content' WHERE NR = $s ";
This is for a telefonsoftware, when somebody calles me up the software is opening a webpage with the main.php and this variable is using the sql select to show the customer informations, then i write a commend into the editable field and it gets written back into my sql databbase.
So! If somebody is looking for a way to path a url command variable via $_get into a php and then into ajax bach into an external file, i hope he google finds this keywords and is showing this page to help him :)
here its in short:
www.url.com/?contact=12345
php catch url parameter:
$s = $_GET['contact'];
sql select:
$sql = "select user, userid from customer where userid = $s";
in AJAX/jquery ad:
var nr = <?php echo $s; ?>;
and later on
nr: nr
in external save php:
$content = $_POST['content']; //get posted data
and
$sql = "UPDATE customer SET comment = '$content' WHERE userid = $s ";

how to get the current added in the table without getting all the data

guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead

Updating HTML Element Every Second With Content From MySQL Database

I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.

Categories