php/mysql comments duplicating automatically on pages reload - comments

I have created a commenting system for my website. The problem I have is that, the old comments duplicate themselves anytime the webpage is refreshed or reloaded.
How can I stop this and only show original comments?
I have added the entire code here below:
<pre>
require 'data/connect.php';
if(isset($_POST['name'])&& isset($_POST['comment'])){
$name = trim($_POST['name']);
$comment = trim($_POST['comment']);
if(!empty($name) && !empty($comment)){
$insert = $connect->query("INSERT INTO
comments(name,comment)VALUES('$name','$comment')");
if($insert){
echo "Success";
}else{
echo "Sorry";
}
}
}
?>
</pre>
form here
<pre>
<?php
if(isset($_POST['name'])&& isset($_POST['comment'])){
$name = trim($_POST['name']);
$comment = trim($_POST['comment']);
if(!empty($name) && !empty($comment)){
$query = $connect->query("SELECT name,comment FROM comments WHERE name='$name' AND comment='$comment'");
while($row = $query->fetch_object()){
echo "<b>",$row->name,"</b><br/>",$row->comment;
}
}
}
?>
</pre>
Your help will be appreciated.

Send out a unique value (created with php's uniqid() for example) in a hidden field in the form. Every time you send the form to a browser, change the value. If you get the same value twice from the same browser, you know it was a double post.
You could also compute a hash of the posted information and compare that against hashes of what's already in the database, for speed, you could store the hash for each comment in the database.
You may also be able to restrict this at the database level, for example by using replace instead of insert (for mySQL).

Related

Ajax to update on database not work

I have a code that is supposed to receive from other apps an ajax call with points variable to update this variable on Database, but something is wrong.
This Is My Code:
The variable should work in points.
I have insert it on the query but it seems there is something wrong because it's not updated the database.
<?php
header('Access-Control-Allow-Origin: *');
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
if(isset($_GET['points'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$points = strip_tags(mysql_real_escape_string($_GET['points']));
//$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
$sql = mysql_query("UPDATE `users` SET user_points = '$points' WHERE user_id = " . $_SESSION['user']);
}
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close();//Close off the MySQL connection to save resources.
?>
enter image description here
enter image description here
I Finally Solve The Problem...
<?php
header('Access-Control-Allow-Origin: *');
error_reporting(E_ALL);
ini_set('display_errors',1);
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
if(isset($_GET['points'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$points = strip_tags(mysql_real_escape_string($_GET['points']));
//$sql = mysql_query("INSERT INTO `publiadd_loginsx`.`users` (`points`) VALUES ('points');");
$sql = mysql_query("UPDATE `users` SET user_points = user_points +'$points' WHERE user_id = " . $_SESSION['user']);
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your Points was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your points. Please try again later.';
}
}else{
echo 'Your points wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
// close MySQL connection
mysql_close();
?>
<html>
<head>
</head>
<body>
<body bgcolor="#ffffff">
</body>
</html>
And This is work now really work

CodeIgniter : image upload on article

I'm building a website with MongoDB and Codeigniter where users can create articles (title + text) and after it (but before to submit), upload some pictures (images are not in the text).
I think i will use jquery.upload for it. But my question is how to do link between pictures and article (because img will be uploaded first), how to rename them ?, is there any good way to do this ?
jquery upload would work. and check if it is success then create new hidden input into the form and set its value as you wish to use.
While I've never attempted this feature, this is a hypothetical solution that popped in my head:
Create a unique string on your Create Article page, and insert it into your document as a hidden field. A random string of 6 characters or something would probably be sufficient.
When uploading the images, use that string as an identifier for what future post the images belong to. Use the string in the file name, path, DB entry, or whatever's useful for your scenario.
When the article itself is submitted, the unique string will allow it to be identified with the images, and you can work whatever magic you need to at that stage to fully commit everything together.
Keep in mind that you should have some sort of statistics and/or garbage collection regarding any images that are uploaded and then the related article is abandoned.
Add 'thumbnail' field in your table 'articles_table' . I removed the unnessary parts for simpler need.We will only use 'title' and 'thumbnail' as field.
View | create.php
<?php echo form_open_multipart('articles/insert'); ?>
Title <br>
<?php echo form_input('title','','id="title_input"'); ?><br>
Thumbnail<br>
<input type="file" name="file" size="20" />
<?php echo form_submit('Submit',"Submit"); ?>
<?php echo form_close(); ?>
Controller | articles.php
function insert()
{
//$this->articles_model->insert();
$this->articles_model->save();
redirect('articles/index');
}
Model | articles_model.php
function save($id=0)
{
$title=$this->input->post('title');
//Set the config
$config['upload_path'] = './files/';
$config['allowed_types'] = 'gif|jpg|png|PNG';
$config['max_size'] = '1100';
$config['max_width'] = '11024';
$config['max_height'] = '1768';
$config['overwrite'] = FALSE;
//Initialize
$this->upload->initialize($config);
//Upload file
if( ! $this->upload->do_upload("file"))
{
//echo the errors
echo $this->upload->display_errors();
}
//If the upload success
$thumbnail = $this->upload->file_name;
if($id<1)
{
$data=array(
'title'=>$title,
'thumbnail'=>$thumbnail
);
$this->db->insert('articles_table',$data);
}
}

Joomla pagination across different components

Because pagination is using getUserStateFromRequest method to get the limit and limitstart variable, I'm having a problem where as I navigate from one component to another, I'm shown a no items found message.
To clarify, I have a products component that has 3 pages worth of products listed. Then I have a branches component with 2 pages worth of branch information. So if I navigate to the third page in the products list, and then go to the branches component, nothing is displayed.
Has anyone any idea how to stop this from happening? Any way to maybe clear the session data?
What I ended up doing was this,
in line 624 in libraries/joomla/application/application.php file I added the following lines
$this->setUserState('option','default');
$curr_comp = JRequest::getCmd( 'option' );;
if($this->getUserState('option') != $curr_comp)
{
$this->setUserState($option . 'limitstart',0);
$this->setUserState('option',$curr_comp);
}
so the whole function reads this,
public function getUserStateFromRequest($key, $request, $default = null, $type = 'none')
{
$this->setUserState('option','default');
$curr_comp = JRequest::getCmd( 'option' );
if($this->getUserState('option') != $curr_comp)
{
$this->setUserState($option . 'limitstart',0);
$this->setUserState('option',$curr_comp);
}
$cur_state = $this->getUserState($key, $default);
$new_state = JRequest::getVar($request, null, 'default', $type);
// Save the new value only if it was set in this request.
if ($new_state !== null)
{
$this->setUserState($key, $new_state);
}
else
{
$new_state = $cur_state;
}
return $new_state;
}
This seems to be working fine at the moment. But please test before implementing on a live site
To prevent editing the core files, but with the effect limited to your extension (so other extensions could load at the wrong page, but not yours), and if your model extends modellist, override the getStart() method:
public function getStart()
{
$store = $this->getStoreId('getstart');
$input = JFactory::getApplication()->input;
$start = $limitstart = $input->getInt('limitstart', 0);
$this->setState('list.start', $limitstart); // maybe redundant
$limit = $this->getState('list.limit');
$total = $this->getTotal();
if ($start > $total - $limit)
{
$start = max(0, (int) (ceil($total / $limit) - 1) * $limit);
}
// Add the total to the internal cache.
$this->cache[$store] = $start;
return $this->cache[$store];
}
If you want a solution that works system-wide and for all extensions, you should be able to override modellist with your implementation in a plugin. Start here.
This is an old question, but I just had the same issue as the OP, but in my case with Joomla 3.4.3.
After a lot of digging and testing, I discovered a solution for this that doesn't involve any plugin or core change:
If you put limitstart=0 in the URL, the pagination will restart for that page, and this solves the problem between menus.
The way to implement this could be either with javascript, or by overriding the menu module, I chose the override:
I just need this in some menus, so I placed a CSS class into the
menu link (edit the menu, and in the "Link Type" tab, place the CSS
class in the "Link CSS Style" field), in my case it was "
video-area" (without the quotes).
Add override (add the module to the html folder of your template,
in my case it was the menu module, so it was a matter of adding the
mod_menu folder: templatefolder/html/mod_menu)
In the override of the component part of the module
(default_component.php), check to see if we have the CSS class, if
so, add the extra query to the URL (I edited case 0):
case 0: $paginationLinks = ""; if(isset($class) && strpos($class, '
video-area') !== false){ $paginationLinks =
"?limitstart=0&limit=12"; } ?><a <?php echo $class; ?>href="<?php
echo $item->flink; ?><?php echo $paginationLinks;?>" <?php echo
$title; ?>><span><?php echo $linktype; ?></span></a><?php break;
That's it! it solved my problem, and even the pagination links have the extra query :)
BONUS: notice that I have &limit=12, this changes the limit for the pagination into 12 per page, without any extra code!, (before, I had a lot of code to implement this, and by adding this to the menu it calculates the correct page number and totals, and filters the query, nice one Joomla!)

codeigniter : using flash data but no new page load?

Usually, I just set a $feedback var or array and then check for that to display in my views.
However, it occurred to me I should perhaps use flashdata instead.
The problem is sometimes - for say an edit record form, I may simply want to reload the form and display feedback - not redirect. when i use flashdata, it shows but then it shows on the next request as well.
What would be the best practice to use here?
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
u use hidden field for that
I would use the validation errors from the Form validation class and load those directly to the view in its 2nd argument.
$this->form_validation->set_error_delimiters('<p>', '</p>');
$content_data = array();
if (!$this->form_validation->run()) {
$content_data['errors'] = validation_errors();
}
$this->load->view('output_page', $content_data);
Then check in your view whether $errors isset.
Controller:
$data['message'] = 'some message you want to see on the form';
$this->load->view('yourView', $data);
View:
if (isset ($message)) : echo $message; endif;
...

how to load view into another view codeigniter 2.1?

Ive been working with CI and I saw on the website of CI you can load a view as a variable part of the data you send to the "main" view, so, according the site (that says a lot of things, and many are not like they say ...ej pagination and others) i did something like this
$data['menu'] = $this->load->view('menu');
$this->load->view ('home',data);
the result of this is that I get an echo of the menu in the top of the site (before starts my body and all) and where should be its nothing, like if were printed before everything... I have no idea honestly of this problem, did anybody had the same problem before?
Two ways of doing this:
Load it in advance (like you're doing) and pass to the other view
<?php
// the "TRUE" argument tells it to return the content, rather than display it immediately
$data['menu'] = $this->load->view('menu', NULL, TRUE);
$this->load->view ('home', $data);
Load a view "from within" a view:
<?php
// put this in the controller
$this->load->view('home');
// put this in /application/views/home.php
$this->view('menu');
echo 'Other home content';
Create a helper function
function loadView($view,$data = null){
$CI = get_instance();
return $CI->load->view($view,$data);
}
Load the helper in the controller, then use the function in your view to load another one.
<?php
...
echo loadView('secondView',$data); // $data array
...
?>

Resources