Delete from database doesn't work correctly - php

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;

Related

Like-Unlike function in codeigniter

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 .

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

insert in DB php+mysql

i have a DB MySQL;
CREATE TABLE IF NOT EXISTS `obsequios` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`promocion` int(1) NOT NULL,
`dia` date NOT NULL,
`hora` time NOT NULL,
`autorizacion` varchar(30) NOT NULL,
`obsequiado_a` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
php code:
$sql_obsequios = '"INSERT INTO `obsequios`(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`) VALUES ('.$promocion.','.'"'.$date.'"'.','.'"'.$hour.'"'.','.'"'.$user_loading.'"'.','.'"'.$regalado_a.'"'.')"';
$sql_obsequios_result = mysqli_query($con, $sql_obsequios);
if ($sql_obsequios_result) {
$result_gral = true;
}else{
$result_gral = false;
}
when I try to add data to the table, I get the value return is false.
try to see the value of $ sql_obsequiosy its value is as follows:
"INSERT INTO `obsequios`(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`)
VALUES (1,"2014-04-13","08:47:55","marcos","sergio")"
using phpmyadmin I have managed to successfully query. I detect what's wrong in this code
Where is Your instructions to add data to DB ?
$sql_obsequios = ...
if ($sql_obsequios_result) ...
it is not the same
Try this and see the difference:
$sql_obsequios = "
INSERT INTO `obsequios`
(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`)
VALUES
('".$promocion."','".$date."','".$hour."','".$user_loading."','".$regalado_a."')";
Also, I dont see any call of mysql_query() or something to get $sql_obsequios_result
Try this:
$sql_obsequios = "INSERT INTO `obsequios`(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`) VALUES ('$promocion','$date','$hour','$user_loading','$regalado_a')";
$sql_obsequios_result = mysql_query(sql_obsequios);
if ($sql_obsequios_result) {
$result_gral = true;
}else{
$result_gral = false;
}
Or try:
$sql_obsequios = "INSERT INTO obsequios(promocion, dia, hora, autorizacion, obsequiado_a) VALUES ('.$promocion.',''.$date.'',''.$hour.'',''.$user_loading.'',''.$regalado_a.'')";
$sql_obsequios_result = mysql_query(sql_obsequios);
if ($sql_obsequios_result) {
$result_gral = true;
}else{
$result_gral = false;
}

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);
}

Function to check to see if a field in a MySQL table equals 1

For the MySQL table below, what PHP function would simply test to see if 'subcheck' equals 1?
Thanks in advance,
John
`submission` (
`submissionid` int(11) unsigned NOT NULL auto_increment,
`loginid` int(11) NOT NULL,
`title` varchar(1000) NOT NULL,
`slug` varchar(1000) NOT NULL,
`url` varchar(1000) NOT NULL,
`displayurl` varchar(1000) NOT NULL,
`datesubmitted` timestamp NOT NULL default CURRENT_TIMESTAMP,
`subcheck` tinyint(1) NOT NULL,
PRIMARY KEY (`submissionid`)
)
You haven't provided much needed information such as the table name, your conditions for checking, so I'm just going to give you a simple query for you to work with...
$query = mysql_query('SELECT subcheck FROM your_table WHERE subcheck = "1"');
if ($query)
{
//your subcheck is 1
}
else
{
//your subcheck is not 1 / nothing was found
}
If you need to select only ones with a certain submissionid it would be best to change it to the following:
$submissionid = 809;
$query = mysql_query('SELECT subcheck
FROM your_table
WHERE submissionid = "' . $submissionid . '"');
if ($row = mysql_fetch_row($query))
{
if ($row[0] == 1) { } //your subcheck is one
else { } //your subcheck is not one
}
else { } //no matching records found
Remember to escape $submissionid if it's going to be based from an unsafe source such as user input!

Categories