I have table 'viewlogs' which is formed from three field: ViewLogId, VideoId and UserId. ViewLogId has a primary key and AUTO_INCREMENT value. When a user watches a video its value increments. When a user watch a same video the viewLogId increments, but I want this value to increase only once and uniquely. How do I fix this problem. I've attached the table picture.
I used the following php code for updating the view_counts in the "videos" table. The above picture belongs to the viewlogs table.
public function updateStatistics($videoId, $fieldName, $userId)
{
$this->db->reconnect();
$this->db->trans_begin();
$this->db->query("UPDATE videos SET {$fieldName}={$fieldName}+1 WHERE VideoId=?", array($videoId));
if ($fieldName == "ViewCount" && $userId > 0) {
$this->db->insert('viewlogs', array('UserId' => $userId, 'VideoId' => $videoId, 'ViewDateTime' => date('Y-m-d H:i:s')));
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
return false;
}
I solved the problem, just need to check the user_id and video_id before updating the view.
public function updateStatistics($videoId, $fieldName, $userId)
{
$this->db->reconnect();
$this->db->trans_begin();
$sql = "SELECT * FROM viewlogs WHERE UserId ={$userId} AND VideoId ={$videoId}";
$query = $this->db->query($sql);
$result = $query->result_array();
if (empty($result)){
$this->db->query("UPDATE videos SET {$fieldName}={$fieldName}+1 WHERE VideoId=?", array($videoId));
if ($fieldName == "ViewCount" && $userId > 0) {
$this->db->insert('viewlogs', array('UserId' => $userId, 'VideoId' => $videoId, 'ViewDateTime' => date('Y-m-d H:i:s')));
}
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
return false;
}
Related
I am trying to delete data from two different table at the same time but it seems like the query is not deleting data. First I will check either user have posted any blog and delete from user and blog if the query is true.
Here is my controller :
public function delete(){
if(isset($_SESSION['userLogId'])){
$selectedId = $this->uri->segment(3);
// getting the current image and unlink it if image exist
$currentImage = $this->User_account_model->currentImage('student', $selectedId);
if($currentImage != null){
$_SESSION['current_image'] = $currentImage->photo;
}
$isDeleted = $this->User_account_model->deleteUser($selectedId);
if($isDeleted == true){
if(isset($_SESSION['current_image']) && !empty($_SESSION['current_image'])){
unlink($_SERVER['DOCUMENT_ROOT']."/uploadfiles/users/student-img/".$_SESSION['current_image']);
unset($_SESSION['current_image']);
}
echo '<script>';
echo 'alert("User removed successfully.");';
echo 'window.location.href = "'.base_url('account/view-user/').'";';
echo '</script>';
} else {
echo '<script>';
echo 'alert("Error while removing. Deleting user unable to processed.");';
echo 'window.location.href = "'.base_url('account/view-user/').'";';
echo '</script>';
}
}
}
My model function to delete user :
function deleteUser($selectedId){
// first check either user have posted blog
$this->db->select('user_id');
$this->db->from('blog_content');
$this->db->where('user_id', $selectedId);
$query = $this->db->get();
$r = $query->row();
if(!empty($r)){
$this->db->delete('users_student, blog_content');
$this->db->from('users_student, blog_content');
$this->db->where('blog_content.user_id = users_student.id');
$this->db->where('users_student.id',$selectedId);
if($this->db->affected_rows()){
return true;
} else { return false; }
} else {
$this->db->delete('users_student');
$this->db->where('id',$selectedId);
if($this->db->affected_rows()){
return true;
} else { return false; }
}
}
In your deleteUser function, replace this code:
$this->db->delete('users_student, blog_content');
$this->db->from('users_student, blog_content');
$this->db->where('blog_content.user_id = users_student.id');
$this->db->where('users_student.id',$selectedId);
with this:
$this->db->delete('blog_content', array('user_id' => $selectedId));
$this->db->delete('users_student', array('id' => $selectedId));
I have solved my issue. It is the Codeigniter query format to delete.
Note : In Codeigniter delete query, specify WHERE first before DELETE
function deleteUser($selectedId){
// first check either user have posted blog
$this->db->select('user_id');
$this->db->from('blog_content');
$this->db->where('user_id', $selectedId);
$query = $this->db->get();
$r = $query->row();
if(!empty($r)){
// delete from blog first
$this->db->where('user_id',$selectedId);
$this->db->delete('blog_content');
if($this->db->affected_rows()){
// then delete from user
$this->db->where('id',$selectedId);
$this->db->delete('users_student');
if($this->db->affected_rows()){
return true;
} else { return false; }
}
} else {
$this->db->where('id',$selectedId);
$this->db->delete('users_student');
if($this->db->affected_rows()){
return true;
} else { return false; }
}
}
I'm trying to update multiple fields of a row on a table on the database. I tried several solutions I found here in stackoverflow but no one had worked for me.
In this function, I give a feedback of a 'Product', and in the table Product I have 4 fields, called num_votes, num_negative_votes, num_neutral_votes and num_positive_votes.
When I call this function, i need to update this fields of the database depending on the value of the form.
How can I update 2 fields at the same time?
The solution I tried is this one: CakePHP - How to update multiple records
public function setFeedback($id = null) {
$this->autoRender = false;
if (!$id) {
$this->redirect(array('action' => 'index'));
}
else {
$product = $this->Product->findById($id);
$num_votes = $product['Product']['num_votes'] + 1;
if($this->request->data['Product']['num_points'] == "0") {
$num_negative_votes = $product['Product']['num_negative_votes'] + 1;
$arrayToSave = array(
'num_votes' => $num_votes,
'num_negative_votes' => $num_negative_votes);
$this->Product->saveMany($arrayToSave, array('deep' => true));
}
else if ($this->request->data == "1") {
$num_neutral_votes = $product['Product']['num_neutral_votes'] + 1;
$arrayToSave = array(
'num_votes' => $num_votes,
'num_neutral_votes' => $num_neutral_votes);
$this->Product->saveMany($arrayToSave, array('deep' => true));
}
else if ($this->request->data == "2 ") {
$num_positive_votes = $product['Product']['num_positive_votes'] + 1;
$arrayToSave = array(
'num_votes' => $num_votes,
'num_positive_votes' => $num_positive_votes);
$this->Product->saveMany($arrayToSave, array('deep' => true));
}
$this->redirect(array('action' => 'index'));
}
}
Try this-
public function setFeedback($id = null) {
$this->autoRender = false;
if (!$id) {
$this->redirect(array('action' => 'index'));
}
$product = $this->Product->findById($id);
$num_votes = $product['Product']['num_votes'] + 1;
if($this->request->data['Product']['num_points'] == "0") {
$num_negative_votes = $product['Product']['num_negative_votes'] + 1;
$arrayToSave['Product']['num_negative_votes'] = $num_negative_votes;
}
else if ($this->request->data == "1") {
$num_neutral_votes = $product['Product']['num_neutral_votes'] + 1;
$arrayToSave['Product']['num_neutral_votes'] = $num_neutral_votes;
}
else if ($this->request->data == "2 ") {
$num_positive_votes = $product['Product']['num_positive_votes'] + 1;
$arrayToSave['Product']['num_positive_votes'] = $num_positive_votes;
}
$arrayToSave['Product']['num_votes'] = $num_votes;
$this->Product->id = $id;
if($this->Product->save($arrayToSave)){
$this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash('Something is wrong.');
}
}
my controller:
function getFeed()
{
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')
);
$this->load->model('membership_model');
$this->membership_model->feeds($feeds);
}
Model:
function feeds($feeds_data)
{
$this->db->insert_batch('feeds', $feeds_data);
}
Is there a function to insert if only the row doesn't exists in the table? I have a table with 4 column : id,title,url,username. I have an anchor when i click him it calls geFeed function and insert the info into table. But i want to insert only if not exists.
I had the same challenge, so i eventually come up with a function which might be helpful to you.
function safe_update_batch($table_name,$records,$filter_field)
{
$filters=array();
foreach($records as $record)$filters[]=$record[$filter_field];
$this->db->query("SET SESSION group_concat_max_len=10000000");
$query=$this->db->select("GROUP_CONCAT($filter_field) AS existing_keys",FALSE)->where_in($filter_field, $filters)->get($table_name);
$row=$query->row();
$found_fields=explode(',',$row->existing_keys);
$insert_batch=array();
$update_batch=array();
foreach($records as $record)
{
if(in_array($record[$filter_field],$found_fields))$update_batch[]=$record;
else $insert_batch[]=$record;
}
if(!empty($insert_batch))$this->db->insert_batch($table_name,$insert_batch);
if(!empty($update_batch))$this->db->update_batch($table_name,$update_batch,$filter_field);
}
//sample usage
$this->safe_update_batch('feeds', $feeds_data,'title');
You can try this in your model!!
function insertClient($array)
{
$this->db->from('MyTable');
$this->db->where('Id', $array['Id']);
$query = $this->db->get();
if($query->num_rows() != 0){
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->where('Id', $array['Id']);
$this->db->update('CLIENTS', $data);
}else{
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->insert('CLIENTS',$data);
}
}
In controller:
$this->site_model->insertClient($_POST);
Sadly if you are using the active record class an INSERT IF NOT EXISTS function doesn't exist. You could try
Extending the active record class (easier said than done)
You could set indexes on certain columns as UNIQUE so that MySQL will check to see if it already exists
You could do some kind of SELECT before your INSERT to determine if the record is already there
For the queries where you need to do INSERT IF NOT EXISTS do $this->db->query('INSERT IF NOT EXISTS...')
function getFeed()
{
// Load the model up here - otherwise you are loading it multiple times
$this->load->model('membership_model');
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
// check if the feed is unique, if true then add to array
if( $this->membership_model->singleFeedIsUnique($entry) == TRUE ){
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')); }
} //foreach
// check to make sure we got any feeds with isset()
// if yes, then add them
if (isset($feeds)){ $this->membership_model->feeds($feeds); }
}
You can try this in your model and leave you controller without changes
function feeds($feeds_data)
{
$data = array(
title => $feeds_data[0],
url => $feeds_data[1],
username => $feeds_data[2]
);
$this->db->select('*');
$this->db->from('mytable');
$this->db->where('title',$feeds_data[0]);//you can use another field
if ($this->db->count_all_results() == 0) {
$query = $this->db->insert('mytable', $data);//insert data
} else {
$query = $this->db->update('mytable', $data, array('title'=>$feeds_data[0]));//update with the condition where title exist
}
}
you can check the id if you have it, adding in the data array and use it to check if exist
I have a site with 300 articles stored in a mySQL database with the URL format of www.site.com/article1.html.
Most invalid URLs redirect succesfully to the main site. For example, www.site.com/article301 redirects to www.site.com, which is what I want.
But www.site.com/article301.html does not redirect anywhere. Instead it loads a blank article template and the following error at the top of the page:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home//public_html/site.com/functions.php on line 26
Line 26 and down reads
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
if(ENABLE_REWRITE == 1) $path=' » '.$row['name'].''.$path;
if(ENABLE_REWRITE == 0) $path=' » '.$row['name'].''.$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}
Any ideas how to fix this?
Here's the full code, as requested by King Skippus
<?php
/*function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT name, parent FROM categories WHERE id=$id");
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
$path=' » '.$row['name'].$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}*/
function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT * FROM categories WHERE id=$id");
if($result !== FALSE && mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
if(ENABLE_REWRITE == 1) $path=' » '.$row['name'].''.$path;
if(ENABLE_REWRITE == 0) $path=' » '.$row['name'].''.$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}
function get_categories_tree($id) {
static $categs = array ();
static $level=0;
$level++;
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']][0] = $row['id'];
$categs[$row['id']][1] = '/'.$row['nameurl'];
$categs[$row['id']][2] = str_repeat(' ', $level-1);
$categs[$row['id']][3] = $row['name'];
get_categories_tree($row['id']);
}
$level--;
return $categs;
}
function get_cats($id) {
$categs = array ();
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']][0] = $row['id'];
$categs[$row['id']][1] = '/'.$row['nameurl'];
// $categs[$row['id']][2] = str_repeat(' ', $level-1);
$categs[$row['id']][3] = $row['name'];
}
return $categs;
}
/*function login() {
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
return false;
} else {
$result=mysql_query("SELECT * FROM users WHERE login='{$_SERVER['PHP_AUTH_USER']}' AND password='{$_SERVER['PHP_AUTH_PW']}'");
if(mysql_num_rows($result)>0) return true;
else {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
return false;
}
}
}*/
function login() {
if (!isset($_SESSION['AUTH_USER']) || !isset($_SESSION['AUTH_PASS'])) return false;
else {
$result=mysql_query("SELECT * FROM users WHERE login='{$_SESSION['AUTH_USER']}' AND password='{$_SESSION['AUTH_PASS']}'");
if(mysql_num_rows($result)>0) return true;
else return false;
}
}
function get_categories($id) {
static $categs = array ("0" => "[Top]");
static $level=0;
$level++;
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']] = str_repeat('| ', $level-1).'|___'.$row['name'];
get_categories($row['id']);
}
$level--;
return $categs;
}
function get_parent_name($id) {
if($id!=0) {
$result=mysql_query("SELECT name FROM categories WHERE id=$id");
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
return $row['name'];
}
else return '-';
}
else return 'Top';
}
function getcatname($id, $table)
{
$r=mysql_query("SELECT title FROM $table WHERE id='$id'");
if(mysql_num_rows($r)>0) {
$row=mysql_fetch_array($r);
return $row['title'];
}
else
return "-";
}
?>
Probably your query failed, and you have no error handling. Your basic bare-bones query sequence should be:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
If you assume the query succeeded and blindly use $result later, you tend to get the type of errors you do, as mysql_query will return a boolean FALSE when something goes boom. That FALSE is not a valid statement handle, so the subsequent num_rows/fetch calls will also go boom.
Never assume a query has succeeded. Even if your sql syntax is 100% perfect, there's far too many other reasons for failure to NOT check.
Try replacing
if(mysql_num_rows($result)>0) {
with
if($result === FALSE) {
header('Location: http://www.example.com/');
}
else if (mysql_num_rows($result)>0) {
// Query was valid, but no rows returned. Take appropriate action.
}
EDIT
For troubleshooting purposes, what does it display if you change the function to this instead? Please be aware that this will intentionally break your site, but it will provide data that is useful for troubleshooting.
function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT * FROM categories WHERE id=$id");
die(sprintf("Value of id: %s, MySQL Error: %s",
var_dump($id, true), var_dump(mysql_error($result), true)));
// Leave the rest of your function as-is, just insert the line above.
I've created a new meta box for my 'cases' post type. And when I publish a new 'cases' post I want to insert the meta id into a new table created by me called 'sort'. I used this code:
function save_postdata( $post_id ) {
global $post, $new_meta_boxes, $wpdb;
foreach ($new_meta_boxes as $meta_box) {
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( 'cases' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
$data = $_POST[$meta_box['name'].'_value'];
if(get_post_meta($post_id, $meta_box['name'].'_value') == "") {
add_post_meta($post_id, $meta_box['name'].'_value', $data, true);
$meta_id = get_post_meta($post_id, 'meta_id', true);
$wpdb->insert( 'sort', array('meta_id'=>$meta_id, 'column_order' => 1));
}
elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
update_post_meta($post_id, $meta_box['name'].'_value', $data);
elseif($data == "")
delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));
}
}
The sort table has three fields: id, meta_id and column_order. Can someone sees what I'm doing wrong?
Make sure that on your insert statement you add 'NULL'
$wpdb->insert( 'sort', array('NULL', 'meta_id'=>$meta_id, 'column_order' => 1));
This could be causing the issue, and also make sure that it's the correct order of your columns.