i have a function and an update query in it like this :
//Article Function
function article()
{
if($_GET['action'] == "article" && !empty($_GET['id']))
{
$id = intval($_GET['id']);
$article = array();
$selectArticle = mysql_query("SELECT * FROM articles WHERE id='$id'");
$rowArticle = mysql_fetch_array($selectArticle);
$id = $rowArticle['id'];
$title = stripcslashes($rowArticle['title']);
$category = stripcslashes($rowArticle['category']);
$image = stripcslashes($rowArticle['image']);
$description = stripcslashes($rowArticle['description']);
$full_description = stripcslashes($rowArticle['full_description']);
$keywords = stripcslashes($rowArticle['keywords']);
$url = "/article/" . $rowArticle['id'] . "/" . str_replace(" ","-",stripcslashes($rowArticle['title']));
$article = array('id' => $id, 'title' => $title, 'category' => $category, 'image' => $image, 'description' => $description, 'full_description' => $full_description, 'keywords' => $keywords, 'url' => $url);
mysql_query("UPDATE articles SET visits=visits+1 WHERE id='7'");
}
return $article;
}
the function called only once but the query runs multiple times when i refresh the page.
for example in first load the visits column is 24 and after refresh the visits column is 48 !!!!!!
i cant understand why i am mixed up
1..Use header and redirect the page.
header("Location:your_page.php");
2..You can redirect to same page or different page.
Unset $_POST after inserting it to Database.
unset($_POST);
Related
I am trying to make an amazon type mock web application. I am currently stuck on my adding a product section because every time I try adding a product it pulls up this error Uncaught PDOException: SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than max_allowed_packet bytes. I am not sure how to fix this in my code. Here is my code:
<?php
require_once('database_controller.php');
require_once(__DIR__ . '/../../model/product/product.php');
class ProductController extends DatabaseController
{
public function __construct()
{
parent::__construct();
}
public function create_product(Product $product): int /* 0 => success / 2 => error on query */
{
$sql = "INSERT INTO product (seller_account_id, name, description, price, category, type_of_sale, thumbnail, image_1, image_2, image_3, image_4, end_of_auction, account_id_last_proposal_auction) VALUES (:seller_account_id,:name,:description,:price,:category,:type_of_sale,:thumbnail,:image_1,:image_2,:image_3,:image_4,:eoa,:author_auction)";
$query = $this->_database->prepare($sql);
$res = $query->execute(array(
'seller_account_id' => $product->get_seller_account_id(),
'name' => $product->get_name(),
'description' => $product->get_description(),
'price' => $product->get_price(),
'category' => $product->get_category(),
'type_of_sale' => $product->get_type_of_sale(),
'thumbnail' => $product->get_thumbnail(),
'image_1' => $product->get_image1(),
'image_2' => $product->get_image2(),
'image_3' => $product->get_image3(),
'image_4' => $product->get_image4(),
'eoa' => $product->get_end_of_auction(),
'author_auction' => $product->get_account_id_last_proposal_auction()
));
return $res ? 0 : 2;
}
public function delete_product(int $product_id): bool
{
$sql = 'DELETE FROM product WHERE id = :pid';
$query = $this->_database->prepare($sql);
return $query->execute(array('pid' => $product_id));
}
public function get_last_produces(int $count): ?array
{
$sql = 'SELECT * from product ORDER BY id ASC LIMIT :count';
$query = $this->_database->prepare($sql);
if (!$query->execute(array('count' => $count)))
return null;
return $query->fetchAll();
}
public function get_product(int $id): ?Product
{
$sql = 'SELECT * from product WHERE id = :id';
$query = $this->_database->prepare($sql);
if (!$query->execute(array('id' => $id)))
return null;
$data = $query->fetch();
return $data == null ? null : new Product($data);
}
public function get_all_products(int $seller_account_id): ?array
{
$sql = 'SELECT * FROM product WHERE seller_account_id = :id';
$query = $this->_database->prepare($sql);
if (!$query->execute(array('id' => $seller_account_id)))
return null;
return $query->fetchAll();
}
public function update_price(int $product_id, float $new_price, int $author_auction): bool
{
$sql = 'UPDATE product SET price = :new_price, account_id_last_proposal_auction = :aid WHERE id = :pid';
$query = $this->_database->prepare($sql);
return $query->execute(array(
'new_price' => $new_price,
'pid' => $product_id,
'aid' => $author_auction
));
}
public function get_products(string $category, string $filter): ?array
{
if ($category == 'all' && $filter == '') {
$sql = 'SELECT * FROM product';
$query = $this->_database->prepare($sql);
if (!$query->execute())
return null;
return $query->fetchAll();
} elseif ($filter == '' && $category != 'all') {
$sql = 'SELECT * FROM product WHERE category = :category';
$query = $this->_database->prepare($sql);
if (!$query->execute(array('category' => $category == 'suits' ? 1 : 2)))
return null;
return $query->fetchAll();
} elseif ($category == 'all' && $filter != '') {
$sql = "SELECT * FROM product WHERE name LIKE '%$filter%'";
$query = $this->_database->prepare($sql);
if (!$query->execute())
return null;
return $query->fetchAll();
} else {
$sql = "SELECT * FROM product WHERE name LIKE '%$filter%' AND category = :category";
$query = $this->_database->prepare($sql);
if (!$query->execute(array('category' => $category == 'suits' ? 1 : 2)))
return null;
return $query->fetchAll();
}
}
}
The error is in this part of the code :
$sql = "INSERT INTO product (seller_account_id, name, description, price, category, type_of_sale, thumbnail, image_1, image_2, image_3, image_4, end_of_auction, account_id_last_proposal_auction) VALUES (:seller_account_id,:name,:description,:price,:category,:type_of_sale,:thumbnail,:image_1,:image_2,:image_3,:image_4,:eoa,:author_auction)";
$query = $this->_database->prepare($sql);
$res = $query->execute(array(
'seller_account_id' => $product->get_seller_account_id(),
'name' => $product->get_name(),
'description' => $product->get_description(),
'price' => $product->get_price(),
'category' => $product->get_category(),
'type_of_sale' => $product->get_type_of_sale(),
'thumbnail' => $product->get_thumbnail(),
'image_1' => $product->get_image1(),
'image_2' => $product->get_image2(),
'image_3' => $product->get_image3(),
'image_4' => $product->get_image4(),
'eoa' => $product->get_end_of_auction(),
'author_auction' => $product->get_account_id_last_proposal_auction()
));
How would I go on about fixing this.
Thanks in advance :)
In general you should increase this session setting. For example, twice, by SET SESSION max_allowed_packet := ##max_allowed_packet + ##max_allowed_packet ; executed in the connection before the query which causes this error.
But in your case this is not a solution. You save 4 images into the table which is bad practice.
You should at least normalize your structure and create separate table for images which stores main row identifier (reference to product table), image number (1..4) and the image... but the best way is to store images in the filesystem and save name/path into the database.
My main problem is with that code in which when I click on submit buttons many times, it inserts duplication many times in the database in which I need to avoid that. Please help me to solve this problem. These are the two tables in which I am trying to insert. mat_ans_options_choose and mat_answer.
$val = $this->input->post(null, true);
$val['id'] = $this->input->post('id');
$val['sub_type'] = $this->input->post('sub_type');
$val['timeout'] = $this->input->post('timeout');
$val['level'] = $this->input->post('level');
$val['mat_category'] = $this->input->post('mat_category');
$option = $val['option'] = $this->input->post('option');
$type = $this->input->post('type');
$marks = [];
$uid = $this->session->userdata('id');
if (isset($val['id']) && isset($option)) {
$query = $this->db->query("SELECT * FROM mat_ans_options WHERE deleted=0 AND active=1 AND question=" . $val['id']);
$result = $query->result_array();
if ($query->num_rows() > 0) {
$count1 = 1;
foreach ($result as $res) {
if ($res['marks'] == 1) {
break;
} else {
$count1++;
}
}
}
// MAT answers options choose
$query1 = $this->db->query("SELECT * FROM mat_ans_options_choose WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id']);
$result1 = $query1->result_array();
if ($query1->num_rows() > 0) {} else {
$data1 = [
'uid' => $uid,
'q' => $val['id'],
'option_chose' => $option,
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_ans_options_choose', $data1);
}
if ($count1 == $option) {
$marks = 1;
} else {
$marks = 0;
}
// if($marks==1 || $marks==0)
// {
// MAT answers
$query2 = $this->db->query("SELECT * FROM mat_answers WHERE deleted=0 AND active=1 AND uid=$uid AND q=" . $val['id'] . " AND type=" . $type . " AND sub_type=" . $val['sub_type'] . " AND level=" . $val['level']);
$result2 = $query2->result_array();
if ($query2->num_rows() > 0) {} else {
$data = [
'uid' => $uid,
'q' => $val['id'],
'type' => $type,
'level' => $val['level'],
'sub_type' => $val['sub_type'],
'mat_category' => $val['mat_category'],
'marks' => $marks,
'timeoutstatus' => $val['timeout'],
'createdon' => $this->general_model->server_time(),
];
$this->db->insert('mat_answers', $data);
}
// }
return 1;
} else {
return 0;
}
Use JS in which you disable the button after first click - it will work no matter if you are using AJAX or not.
You can use JS/jQuery to limit the number of requests made on the client side. For example by disabling the button on submit:
$("#my-button").prop("disabled", true);
But if the data is sensitive for duplicates (orders, user registration etc) you should make the request limit server side with PHP. You can achieve this by adding a unique index to the tables, either on user id or on a unique token that is submitted with the html form.
Create UNIQUE index in database for uid and q. The database will not insert same question's id from same user's id mulitple times.
php codeigniter i want to redirect this function print_view and also pass the data $this->db->insert('invoice_main',$datas);$result = $this->db->insert_id();
Public function insert_invoice(){
$item_name = $_POST['item'];
$rate = $_POST['rate'];
$quantity = $_POST['quantity'];
$tax = $_POST['tax'];
$amount = $_POST['amount'];
$invoice_id = $this->input->post('invoice_id');
//$invoice_id++;
$datas = array(
'user_id' => $this->session->userdata('user_id'),
'invoice_id' => $this->input->post('invoice_id'),
'pt_opnum' => $this->input->post('pt_opnum'),
'pt_uhid' => $this->input->post('pt_uhid'),
'doc_name' => $this->input->post('doc_name'),
'status'=>1
);
$this->db->insert('invoice_main',$datas);
$result = $this->db->insert_id();
for ($i=0; $i <count($item_name) ; $i++) {
$data=array(
'invoice_id' =>$invoice_id,
'pt_name'=> $this->input->post('pt_opnum'),
'date'=>date('d-m-Y'),
'name'=>$item_name[$i],
'rate'=>$rate[$i],
'quantity'=>$quantity[$i],
'tax'=>$tax[$i],
'amount'=>$amount[$i],
'sub_total'=>$_POST['sub_total'],
'o_tax'=>$_POST['o_tax'],
'grand_total'=>$_POST['grand_total'],
'status'=>1
);
$this->db->insert('invoice_details',$data);
}
return($this->db->affected_rows()!=1)?false:true;
$this->print_view($result);
}
public function print_view($result){
redirect(base_url()."invoice/print_view/".$result);
}
You can pass the any data with flashdata.
$this->session->set_flashdata('something',$result);
On the other page you can access it
$something = $this->session->flashdata('something);
But on your case you don't have to use flash data, you can get the params from url and you can search on your DB.
So I've spent hours on trying to fix this one. every time I upload a file. all the data/id3 tags are being inserted twice on my database. before it was working properly now it has this bug and I badly need some help now.
In my controller I am executing update at the same time since I want also to update the data inserted into database with the details from the id3 tags.
Controller
public function save()
{
$id = $this->session->userdata('user_id');
$status = $this->input->post('status');
$original_file = $this->input->post('original_file');
$revised_file = $this->input->post('revised_file');
$song_data = array(
'user_id' => $id,
'song_info_status' => $status,
'song_info_file_name' => $original_file,
'song_info_revised_file_name' => $revised_file,
'song_info_date_added' => 'now()',
'song_info_date_updated' => 'now()'
);
$song_info_id = $this->song_info_model->save($song_data);
$composer_data = array(
'composer_name' => ''
);
$composer_id = $this->composer_model->save($composer_data);
$song_composer_data = array(
'song_info_id' => $song_info_id,
'composer_id' => $composer_id
);
$this->song_composer_model->save($song_composer_data);
$status_data = array(
'song_info_id' => $song_info_id
);
$status_id = $this->status_model->save($status_data);
$tags_info = array();
$tags_info = $this->getTagsInfo(FCPATH ."temp" . "/" .$revised_file);
if(isset($tags_info['Author']))
{
// echo iconv("UTF-8","EUC-JP", $tags_info['Author']);
//echo $str = mb_convert_encoding($tags_info['Author'], "UTF-8", "auto");
$status_data = array(
'status_artist_name' => $tags_info['Author']
);
$this->status_model->update($status_data, $status_id);
}
if(isset($tags_info['Title']))
{
$song_data = array(
'song_info_original_title' => $tags_info['Title']
);
$this->song_info_model->update($song_data, $song_info_id);
}
rename($this->source.$revised_file, $this->destination.$revised_file);
}
In my model I am just getting the data I have from my controller. there's no loop or anything and I really can't find the culprit.
Model
public function save($data)
{
$this->db->insert('song_info', $data);
return $this->db->insert_id();
}
public function update($data, $id)
{
$this->db->where('song_info_id', $id);
$this->db->update('song_info', $data);
}
This is my sample code:
switch($topic_type) {
case 1: //post
$model = 'Userposts';
$field_name = 'user_post_id';
$select_name = 'post_title';
break;
}
$model = ClassRegistry::init($model);
$model->alias = 'TP';
$model->id = $topic_id;
$result = $model->find('first',
array(
'conditions'=>array($field_name=>$topic_id),
'fields'=>array($select_name.' as topic',$field_name.' as id'),
));
if(!empty($result)){
$this->updata[$model_name][$select_name] = $modified_topic;
$this->updata[$model_name][$field_name] = $topic_id;
if($model->save($this->updata)){
$respArr['token'] = $token;
$respArr['status'] = 1;
$respArr['msg'] = 'Success';
echo json_encode(array('token' => $token, 'status' => 1, 'msg' => 'Success'));exit;
}
}
The $model->find is working and fetching result where as $model->save after find is not working.
field_name is the primary key and select_name is the save that i want to update after modifying title.