I'm trying to delete some rows with checkbox and i'm not sure what am i doing wrong.
The view:
<table class="table table-hover">
<?php echo form_open('site/delete');?>
<?php
foreach ($query as $row){
echo '<tr><td>
<label class="checkbox">
'.form_checkbox('delete[]', $row['link'])."<a href='".$row['link']."'>".$row['title']."</a></td><td>".substr($row['pub_date'], 5, 12).
"</label>
</td></tr>";
} ?>
<?php echo form_submit('submit','Delete');?>
<?php echo form_close();?>
</table>
controller:
function delete()
{
$url = $this->input->post('delete');
if(isset($url))
{
$this->load->model('membership_model');
$this->membership_model->delete();
$this->main_menu();
}
else
{
redirect('site/main_menu');
}
model:
function delete()
{
$delete = $this->input->post('delete');
for($i=0;$i<count($delete);$i++) {
$del_link = $delete[$i];
$this->db->where('link',$del_link);
$this->db->delete('feeds');
}
}
When i click delete nothing changes. I want to delete rows with box checked from my database.
controller
public function delete()
{
$did= $this->input->post('delete');
if(!empty ($did))
{
foreach ($did as $key => $value)
{
$res=$this->membership_model->delete($value);//pass particular id to delete
$this->main_menu();
}
}
else
{
redirect('site/main_menu');
}
}
Model:
function delete($fid)
{
$this->db->where('link', $fid);
$this->db->delete('feeds');
}
Related
I have related tables and show at gridview. When i want to delete data from gridview, i take the mysql error about this data using other tables field. At that time i want to show message to user for example "This data not deleting".
I did it at yii 1.1 as follows.
views/xxx/index.php
<div id="statusMsg">
<?php if(Yii::app()->user->hasFlash('success')):?>
<div class="flash-success" >
<?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>
<?php if(Yii::app()->user->hasFlash('error')):?>
<div class="flash-error">
<?php echo Yii::app()->user->getFlash('error'); ?>
</div>
<?php endif; ?>
</div>
gridview
array(
'class'=>'CButtonColumn',
'afterDelete'=>
'function(link,success,data){
if(success) $("#statusMsg").html(data);
}',
),
controller/xxxcontroller
public function actionDelete($id)
{
try{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
Yii::app()->user->setFlash('success','Normal – Deleted Successfully');
else
echo "<div class='flash-success'>Yiyecek Başarıyla Silindi</div>";
}catch(CDbException $e){
if(!isset($_GET['ajax']))
Yii::app()->user->setFlash('error','Normal – error message');
else
echo "<div class='flash-error'>Yiyecek silinimedi.</div>"; //for ajax
}
}
but afterDelete not using in yii2 . And i didn't know what to use instead of afterDelete.
Thank you.
I used following code in controller delete action
$connection = Yii::$app->db;
$transaction = $connection->beginTransaction();
try {
$this->findModel($id)->delete();
$transaction->commit();
Yii::$app->session->setFlash('success','Silme işlemi başarılı.');
return $this->redirect(['index']);
} catch (IntegrityException $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error','Silme işleminde hata oluştu.');
return $this->redirect(['index']);
}catch (\Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error','Silme işleminde hata oluştu.');
return $this->redirect(['index']);
}
I am creating an event, each event will have attendees, I got this working fine, the problem I am having is an attendee can attend the same event twice, which is not good.
Event View
<?php if($this->session->userdata('user_id')): ?>
<hr>
<?php echo form_open('/attendees/add/'.$event['id']); ?>
<input type="hidden" name="user_id" value="<?php echo $_SESSION['user_id']; ?>">
<input type="submit" value="I'm in!" class="btn btn-success">
</form>
<?php endif; ?>
Attendees Controller
<?php
class Attendees extends CI_Controller {
public function add($event_id) {
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->form_validation->set_rules('user_id', 'required|callback_check_userid_eventid');
if($this->form_validation->run() === FALSE){
$this->session->set_flashdata('attendee_not_added', 'You are already on the list.');
redirect('home');
} else {
$this->attendee_model->add_attendee($event_id);
// Set message
$this->session->set_flashdata('attendee_added', 'You have been added to this event.');
redirect('events');
}
}
}
Attendees Model
<?php
class Attendee_model extends CI_Model {
public function __contruct() {
}
public function get_attendees($id = FALSE){
if($id === FALSE) {
$query = $this->db->get('attendees');
return $query->result_array();
}
$this->db->select('attendees.id, attendees.team, attendees.is_goalie, event.id, user.first_name, user.last_name');
$this->db->from('attendees');
$this->db->join('event', 'attendees.event_id = event.id', 'inner');
$this->db->join('user', 'attendees.user_id = user.id', 'inner');
$this->db->where('event.id', $id);
$query = $this->db->get();
return $query->row_array();
}
public function add_attendee($event_id){
$data = array(
'event_id' => $event_id,
'user_id' => $this->session->userdata('user_id')
);
return $this->db->insert('attendees', $data);
}
// Check attendee exists in event
public function check_userid_eventid($event_id, $user_id){
$query = $this->db->get_where('attendees', array('user_id' => $user_id, 'event_id' => $event_id));
if(empty($query->row_array())){
return true;
} else {
return false;
}
}
}
As you can see I tried creating a custom callback on the button form validation but it did not work.
If anyone can point me in the right direction, let me know if I am even somewhat close.
Thanks in advance.
You are not passing the $event_id value to the callback function. Replace your validation with the following line
$this->form_validation->set_rules('user_id', 'User ID', 'required|callback_check_userid_eventid['.$event_id.']');
add following callback function inside the Attendees Controller file
public function check_userid_eventid($user_id, $event_id){
$CI =& get_instance();
$CI->load->database();
$CI->form_validation->set_message('user_id_unique', "Sorry, that %s is already being used.");
return isset($CI->db) ? ($CI->db->limit(1)->get_where('attendees',compact('user_id','event_id'))->num_rows() == 0) : false;
}
Your callback is in a model that form validation knows nothing about. If you look at the docs: callbacks should be in the same controller as the form validation method that uses it.
However, you can use a function in a model as a callback with a different syntax:
$this->form_validation->set_rules(
'username', 'Username',
array(
'required',
array($this->users_model, 'valid_username')
)
);
as documented here.
Finally, on a false return, you need to make sure that you are setting a message as seen in this example:
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
In conclusion: the documentation has all the answers.
Put the call back function into Controller
<?php
class Attendees extends CI_Controller {
public function add($event_id) {
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->form_validation->set_rules('user_id', 'required|callback_check_userid_eventid');
if($this->form_validation->run() === FALSE){
$this->session->set_flashdata('attendee_not_added', 'You are already on the list.');
redirect('home');
} else {
$this->attendee_model->add_attendee($event_id);
// Set message
$this->session->set_flashdata('attendee_added', 'You have been added to this event.');
redirect('events');
}
}
// Check attendee exists in event
public function check_userid_eventid($event_id, $user_id){
$query = $this->db->get_where('attendees', array('user_id' => $user_id, 'event_id' => $event_id));
if(empty($query->row_array())){
return true;
} else {
return false;
}
}
}
I want update just one column of table I'm getting this error when updating a table rows:
Call to a member function load() on null
This is my action:
public function actionAddNote(){
$id = \Yii::$app->request->post('id');
$model = MainRequest::findOne($id);
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->update()){
echo "1";
}else {
print_r($model->getErrors());
}
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
My model:
class MainRequest extends ActiveRecord {
public static function tableName()
{
return "main_request";
}
public function behaviors()
{
return [
DevNotificationBehavior::className(),
];
}
public function rules() {
return [
[
['who_req',
'req_description',
'req_date',
'extra_note'
], 'safe']
];
}
The form will render properly and I can see my text but when I submit this the error occur:
<div>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'extra_note')->textInput(); ?>
<div class="form-group">
<?= Html::submitButton('save', ['class' => 'btn green']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Can anybody tell what is problem ? Thank you.
You should load the model and the use the model loaded for accessing attribute
and you should manage ythe initial situation where you d0n't have a model to update but need a model for invoke the update render form eg:
public function actionAddNote(){
$myModel = \Yii::$app->request->post();
$model = MainRequest::findOne($myModel->id);
if (isset($model)){
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->update()){
echo "1";
}else {
print_r($model->getErrors());
}
}
} else {
$model = new MainRequest();
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
Use Simple save function or updateAttributes of Yii2:
public function actionAddNote(){
$id = \Yii::$app->request->post('id');
$model = MainRequest::findOne($id);
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->**save**()){
echo "1";
}else {
print_r($model->getErrors());
}
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
If I remove the or die("MySQL ERROR: ".mysqli_error()); from the code below, it gives me no error. But it also doesn't write to the database.
What am I doing wrong?
ob_start();
session_start();
require ('openid.php');
function logoutbutton() {
echo "<form action=\"steamauth/logout.php\" method=\"post\"><input value=\"Logout\" type=\"submit\" /></form>"; //logout button
}
function steamlogin() {
try {
require("steamauth/settings.php");
$openid = new LightOpenID($steamauth['domainname']);
$button['small'] = "small";
$button['large_no'] = "large_noborder";
$button['large'] = "large_border";
$button = $button[$steamauth['buttonstyle']];
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'http://steamcommunity.com/openid';
header('Location: ' . $openid->authUrl());
}
//echo "<form action=\"?login\" method=\"post\"> <input type=\"image\" src=\"http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_".$button.".png\"></form>";
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
if($openid->validate()) {
$id = $openid->identity;
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
$_SESSION['steamid'] = $matches[1];
include_once("set.php");
$query = mysqli_query("SELECT * FROM users WHERE steamid='".$_SESSION['steamid']."'");
if (mysqli_num_rows($query) == 0) {
mysqli_query("INSERT INTO users (steamid) VALUES ('".$_SESSION['steamid']."')") or die("MySQL ERROR: ".mysqli_error());
}
if (isset($steamauth['loginpage'])) {
header('Location: '.$steamauth['loginpage']);
}
} else {
echo "User is not logged in.\n";
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
}
Here's a screen-shot of my database structure:
I am working on a project and stuck at a point. I have designed a form which insert a person's profile detail in database.... now I want that as the person submit the entries into database the next page after submission should be the preview of the entered profile like the person's image name and other details.
This is my controller code
public function listbusiness()
{
$this->load->model('client/Client_model');
$this->Client_model->checksession();
if($this->input->post("continue",TRUE)){
$ptype = $this->input->post('ptype');
$ftype = $this->input->post('ftype');
$peckage=array();
if($this->input->post('pktype1'))
{
$pk1=$this->input->post('pktype1');
$price1=$this->input->post('price1');
$peckage[$pk1]=$price1;
}
if($this->input->post('pktype2'))
{
$pk2=$this->input->post('pktype2');
$price2=$this->input->post('price2');
$peckage[$pk2]=$price2;
}
if($this->input->post('pktype3'))
{
$pk3=$this->input->post('pktype3');
$price3=$this->input->post('price3');
$peckage[$pk3]=$price3;
}
if($this->input->post('pktype4'))
{
$pk4=$this->input->post('pktype4');
$price4=$this->input->post('price4');
$peckage[$pk4]=$price4;
}
$sessiondata=array('ptype'=>$ptype,'ftype'=>$ftype,'pkage'=>$peckage);
$this->session->set_userdata($sessiondata);
$city = $this->input->post('City');
$this->session->set_userdata('city',$city);
}
if($this->input->post("submit",TRUE)){
//print_r($_POST);die;
//print_r($this->session->all_userdata());
//die;
$title = $this->input->post('title');
$desc = $this->input->post('desc');
$term = $this->input->post('term');
//$file = $this->input->files('files');
$add = $this->input->post('add');
//$name = $this->input->post('stud_name');
$bid = $this->session->userdata('logged_in');
//$file=str_replace(" ","_",$_FILES['stud_img']['name']);
$pp=implode($this->session->userdata('ptype'));
$ff=implode($this->session->userdata('ftype'));
$newdata=array("name"=>$title,
"detail"=>$desc,
"type"=>$pp,
"address"=>$add,
//"price"=>$price,
"facility"=>$ff,
"city"=>$this->session->userdata('city'),
"bussid"=>$bid['userid']);
//print_r($newdata);die;
$retval=$this->Client_model->save("listing",$newdata);
if($retval>0)
{
//print_r($newdata);die;
$apack=$this->session->userdata('pkage');
foreach($apack as $key=>$value)
{
$price=array("packtype"=>$key,"price"=>$value,'lid'=>$retval);
if($value!='')
{
$this->Client_model->save("price",$price);
}
}
if(isset($_FILES['files']))
{
$photoname=$_FILES['files']['name'];
$photopath=$_FILES['files']['tmp_name'];
$name=implode(",",$photoname);
$uploaddata=array("name"=>str_replace(" ","_",$name),"lid"=>$retval);
$retval1=$this->Client_model->saveupload("photo",$uploaddata);
if($retval1>0)
{
$size=count($photoname);
for($i=0;$i<$size;$i++)
{
$filename=str_replace(" ","_",$photoname[$i]);
move_uploaded_file($photopath[$i],$_SERVER['DOCUMENT_ROOT']."/clubhouz/upload/photo/".$filename);
}
}
}
//redirect("business/businessdetail");
//$insertid=base64_encode($value['id']);
// $insertid = $this->db->insert_id();
$insertid=base64_encode($value['id']);
redirect('viewlistdetail?id=$newid');
}
}
This is in the model:
function viewlistdetail($st)
{
//echo $st;die;
$data['page_title'] = 'List View';
$data['detail']=$this->getlistdetail($st);
$this->load->view('client/general/head',$data);
$this->load->view('client/general/header');
$this->load->view('client/listview',$data);
$this->load->view('client/general/footer');
}
and the listview displays the last inserted record,
but there is error of page not found after I submit the form.
Please check the following procedure and apply it in your project.
your controller file, I assume, its file name is persons.php
class Persons extends CI_Controller {
function view($id)
{
$this->load->model(array('Persons_model'));
$person = $this->Person_model->get_person($id);
$data['first_name'] = $person->first_name;
$data['last_name'] = $person->last_name;
$this->load->view('person_view', $data);
}
}
your model file, I assume, its file name is persons_model.php
Class Persons_model extends CI_Model
{
function get_person($id)
{
$result = $this->db->get_where('persons', array('id'=>$id));
return $result->row();
}
{
your view file, I assume, its file name is person_view.php
<div>First Name: <?php echo $first_name ?></div>
<div>Last Name: <?php echo $last_name ?></div>