Like-Unlike function in codeigniter - php

I would like to implement this like and unlike into codeigniter. I can do it in the normal php using the following codes but I just don't why it is not working in codeigniter below is my database table and my model view and controller. any help would be appritiated. thanks.
posts table
CREATE TABLE `posts` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`content` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
like-unlike table
CREATE TABLE `like-unlike` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`purpose` int(2) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Jquery file
function likeItem(post_id)
{
if ($("#likeItem_" + post_id).text() == "Like")
{
$("#likeItem_" + postid).html('Unlike');
var purpose = "Like";
} else
{
$("#likeItem_" + post_id).html('Like');
var purpose = "UnLike";
}
$.ajax({
type: "POST",
url: "<?php echo base_url('posts/likes');?>",
data: "postId=" + postId + "&purpose=" + purpose,
success: function (data)
{
// do seomthing here with data
// console.log(data) --> to see data return or not
}
}
);
This is my model "Post_model.php"
public function itemLike() {
$id = $this->session->userdata('user_id');
$postId = $this->input->post('post_id');
$purpose = $this->input->post('purpose');
if ($purpose == "Like") {
// echo 'test';
// exit();
$data = array(
"user_id" => $id,
"post_id" => $postId,
);
$this->db->insert('like', $data);
} else {
echo 'failed';
}
}
This is my view file
<li><a class="like-unlike" href="#" id="likeItem_{$item['post_id']}" onclick="likeItem({$item['post_id']})">Like</a></li>
This is my Controller "Post.php"
public function likeItem()
{
$this->usermodel->itemLike();
}

In your database schema, you have mentioned table like_unlike and you are saving data in to table like-unlike.
Also, you set column purpose for mandatory and you are not passing any values here:
$data = array(
"user_id" => $id,
"post_id" => $postId,
);
You don't need to pass data if you use default value. You also need to keep in mind that column purpose holds only integer value as per your database schema.
Apart from this you also need to modify code mention by #JYoThI

1st : Post name mismatch data : "postId=" + post_id + "&purpose=" + purpose,
$postId = $this->input->post('post_id');
change to
$postId = $this->input->post('postId');
2nd : pass the data like below and variable name is post_id not postId
data : {postId:postid,purpose:purpose},
Note : variable names are case sensitive take care about that .

Related

how to do casecading in cakephp

i want casecading in cakephp. I am creating city manager where I have two things zones and states as a dropdown. if i select zone then states should come according to selected zone.please help me what should be the code for model view and controller.I am new in cakephp. table for cities table is given below
CREATE TABLE IF NOT EXISTS `cities` (
`id` int(11) NOT NULL,
`zone_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`total_sample` int(11) NOT NULL,
`population` int(11) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cities`
--
INSERT INTO `cities` (`id`, `zone_id`, `state_id`, `name`, `code`, `total_sample`, `population`, `is_active`, `created`, `modified`) VALUES
(1, 2, 2, 'avadi', '15018', 10, 100, 1, '2016-10-03 00:00:00', '2016-10-03 00:00:00');
Please help me with code for controller, view and model.
You can do this by 2 ways
Using Chained javascript library. in this way you have to format dropdown. for doing this you can follow This Tutorial
By using Ajax request according to select Zone and State
For Option 2: Html
echo $this->Form->input('zone_id', ['options' => $zons, 'empty' => '','id'=>'zoneDropdown']);
echo $this->Form->input('state_id', ['options' => $state, 'empty' => '','id'=>'stateDropdown']);
echo $this->Form->input('city', ['options' => [], 'empty' => '','id'=>'cityDropdown']);
Ajax Script for Html
$('#zoneDropdown, #stateDropdown').on('change', function (evt) {
ZONE = $("#zoneDropdown").val();
STATE = $("#stateDropdown").val();
$.ajax({
type: "GET",
url: baseURL+"cities/getCitiesOptions/"+ZONE+"/"+STATE,
dataType: "json",
success : function(returnData) {
$("#cityDropdown").val(returnData);
}
});
});
and the controller Function need to add
Public function getCitiesOptions($zone_id=null, $state_id=null){
$conditions = [];
if (!empty($zone_id)) {
$conditions['Cities.zone_id'] = $zone_id;
}
if (!empty($state_id)) {
$conditions['Cities.state_id'] = $state_id;
}
$cities = $this->Cities->find('all',['conditions'=>$conditions])->all()->toArray();
// make Options for dorpdown
$html = '';
foreach ($cities as $key => $value) {
$html .= '<option value="'.$value['code'].'">'.$value['name'].'</option>';
}
return $html;
}

Delete from database doesn't work correctly

So i have Many-to-many extra table and i want to delete a row from the extra table .
CREATE TABLE `person_cars` (
`person_cars_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`person_id` int(10) NOT NULL,
`car_id` int(10) NOT NULL,
PRIMARY KEY (`person_cars_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
This PHP doesn't work
if(isset($_GET['id']) && isset($_GET['person_cars_id'])) {
$person_id = $_GET['id'];
$person_cars_id = $_GET['person_cars_id'];
$person->deleteCarOfPerson($person_cars_id);
header('location:join.php?id=' + $person_id);
}
SQL
public function deleteCarOfPerson($person_cars_id) {
$sql = ("DELETE FROM person_cars
WHERE person_cars_id = '{$person_cars_id}'");
$result = mysql_query($sql, $this->mysql_database->getConnection());
return $result;
}
Now delete is working but not header('location:join.php?id=' + $person_id);
if(isset($_GET['person_cars_id'])) {
$person_id = $_GET['id'];
$person_cars_id = $_GET['person_cars_id'];
$person->deleteCarOfPerson($person_cars_id);
header('location:join.php?id=' + $person_id);
}
Your re-direct isn't working as you're mixing PHP with Javascript.
Change
header('location:join.php?id=' + $person_id);
to
header('Location: join.php?id='.$person_id);
+ is used in Javascript to add something.
Whenever use header function you should use exit also after header redirection.
header("lOCATION:JOIN.PHP");
EXIT;

getting a last inserted varchar id which is an primary key

I have multiple table ,which has to be inserted using different forms and all table have one id which is primary key and its varchar (NOT NULL),So i have one class function named as id_calc($tbl,$id) where $tbl is a parameter with table name and $id is a field id .And each time while inserting this function has to be called for id.
for example: If my id is "web1" ,next when i insert it shud give "web2","web3"...... i have tried with LAST_INSERT_ID() but its not working.so i tried with fetching the max(id) and splitting the string and variable but is also giving some problem.so how can i do this.please help!!!
class first{
public function id_calc($tbl,$id)
{
$sql = mysql_query("SELECT max($id) FROM $tbl where $id like '%web%'");
if($sql)
{
while ($row = mysql_fetch_assoc($sql))
{
$user=$row;
$a=implode(" ",$user);
}
$pattern = "/(\d+)/";
$array = preg_split($pattern, $a, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$new[]=$array['0'];
$new[]=$array['1']+1;
$result=implode("",$new);
return $result;
}
}
}
this function is called like
public function insertreport1()
{
$obj=new first();
$id=$obj->id_calc(tablename,idfield);
//insert query
}
this is my table structure
CREATE TABLE `report` (
`inc_id` varchar(25) NOT NULL,
`inc_status` int(11) NOT NULL,
`inc_date` datetime NOT NULL,
`inc_Name` varchar(45) NOT NULL,
`inc_Age` int(11) NOT NULL,
`inc_Gender` varchar(45) NOT NULL,
`inc_Mobile` varchar(45) NOT NULL,
`inc_Address` varchar(250) NOT NULL,
`inc_treatment` varchar(45) DEFAULT NULL,
`inc_userid` varchar(10) NOT NULL,
`inc_repTime` datetime NOT NULL
PRIMARY KEY (`inc_id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
i think you can do it this way..write the query as
"SELECT MAX(CAST(SUBSTRING($id,4,12) AS UNSIGNED)) FROM $tbl WHERE $id LIKE '%web%'"
and then increment the id as web+(max+1).
Pseudo implementation would be
alter table definition
alter table `table` add column id int(11) not null auto_increment
change code
public function id_calc($tbl,$idcol) {
$sql = mysql_query("SELECT id FROM $tbl order by id desc limit 1");
if($sql){
while($row = mysql_fetch_assoc($sql));
$id = isset($row['id']) ? $row['id'] + 1 : 1;
return "{$idcol}{$id}";
}
}
Hope this helps

Assigning the value of a table row ID with another ID using an SQL statement

So in my database i have two tables. Jokes and Comments. I want the ability to assign the post_id of the comment, to the joke_id of the joke, so it will assign and retrieve the comments relating to that joke. My problem is that i suck at writing SQL statements and haven't the foggiest on how to join two tables to make this happen.
My jokes table looks like this:
CREATE TABLE IF NOT EXISTS `jokes` (
`joke_id` int(11) NOT NULL AUTO_INCREMENT,
`joke` varchar(1024) NOT NULL,
`category_id` int(11) NOT NULL,
`vote` int(255) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and my comments table looks like this:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`comment` text NOT NULL,
`joke_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and for the moment, I am grabbing the data by assigned the $post_id = "1", but i want to change it to something like $post_id = $joke_id (with the joke id being in the same function, but i have no idea how to do it).
I'm using a MVC with codeigniter if thats any help.
Inside my controller, i have a php file called comments which has a function called insertComment, which looks like this:
public function insertComment(){
//extracts the data from the ajax
extract($_POST);
if($_POST['act'] == 'add-com'){
//assigned the db rows with the actual data which was inputted
$data = array(
'name' => htmlentities($name),
'comment' => htmlentities($comment),
//id_post should correlate to the joke_id
'id_post' => $id_post = "1"
);
$this->comments_m->insertComment($data);
}
and my insertComment function, inside the models of comment_m function looks like this:
function insertComment (){
extract($_POST);
if($_POST['act'] == 'add-com'){
$data = array(
'name' => htmlentities($name),
'comment' => htmlentities($comment),
'id_post' => $id_post = "1"
);
if(strlen($data['name']) <= '1'){
$data['name'] = 'Guest';
}
$this->db->insert('comments', $data);
}
}
To finalise, it would be a great help if someone could help with an SQL statement which joins the two tables together, which the joke_id having the same value as the comment's post_id which will make it unique to that joke.
Thank you
The SQL to join these two tables is -
SELECT `jokes`.*, `comments`.*
FROM `jokes`
LEFT OUTER JOIN `comments`
ON `jokes`.`joke_id` = `comments`.`joke_id`
This will return all of the comments for each joke. You can then filter or limit by adding the WHERE clause(s) -
WHERE `jokes`.`joke_id` = 1

Create a new page on submit from database

I've created a chained menu using php and a database, following this tutorial.
The first table content a list of categories like :
CREATE TABLE IF NOT EXISTS `chainmenu_categories` (
`id_cat` int(4) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
PRIMARY KEY (`id_cat`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
My second table, the type, like :
CREATE TABLE IF NOT EXISTS `type` (
`id_type` int(4) unsigned NOT NULL AUTO_INCREMENT,
`id_cat` int(4) unsigned NOT NULL,
`name` varchar(40) NOT NULL,
`destination` varchar(40) NOT NULL,
PRIMARY KEY (`id_type`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
I managed, once clicking on submit, to redirect to another page by that in my select.php:
var result = $("select#type option:selected").html();
$("#select_form").submit(function( event ) {
var the_url = $("#type").val();
window.location = the_url;
event.preventDefault();
});
and adding this on my select.class.php
public function ShowCategory()
{
$sql = "SELECT * FROM chainmenu_categories";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . $row['destination']. '">' . $row['name'] . '</option>';
}
return $category;
}
So now it redirects each time to a different page depending of the option choose from the menu, like http://mydomain.com//3 then 4, 5, 6, etc.
But as the page doesn't exist, it redirects to a dead link.
Can someone give me help to create these pages from the chained menu (or have some highlight)? and if possible, some pointer to create the admin interface to allow an admin to add the pages and categories to the chained menu?
I've been trying to start with something which look like:
PHP Code:
<?php require('db_config.php');
$stmt = $db->prepare('SELECT id_type, name FROM type WHERE id_cat=$_POST[id]');
$stmt->execute(array(':id_cat' => $_GET['name']));
$row = $stmt->fetch();
However, I don't know if this is good at all.
if(file_exists($filename.'.php'))
echo "file : " . $filename.'.php' . " is exist";
else
{
$file = fopen($filename.'.php',"w");
$code="here what U want to write inside the new page.php";
fwrite($file,$code);
fclose($file);
}

Categories