Codeigniter can't access colum from database - php

I tried to add 1 more column in my code, the column "itemid" to be used but I get strange error when I did everything how its supposed, the error message: "Undefined index: item_id".
My model:
function __construct() {
$this->proTable = 'web_store';
$this->transTable = 'purchases_users';
$this->GameRewards = 'users_items';
}
/*
* Fetch products data from the database
* #param id returns a single record if specified, otherwise all records
*/
public function getRows($id = ''){
$this->db->select('*');
$this->db->from($this->proTable);
$this->db->where('status', '1');
if($id){
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('Title', 'asc');
$query = $this->db->get();
$result = $query->result_array();
}
// return fetched data
return !empty($result)?$result:false;
}
/*
* Insert data in the database
* #param data array
*/
public function insertTransaction($data){
$insert = $this->db->insert($this->transTable,$data);
return $insert?true:false;
}
/*
* Insert data in the database
* #param data array
*/
public function insertGameRewards($data){
$insert = $this->db->insert($this->GameRewards,$data);
return $insert?true:false;
}
My Paypal controller:
function __construct(){
parent::__construct();
$this->load->library('paypal_lib');
$this->load->model('product');
}
function success(){
// Get user session (is it logged in the webpage)
$Session = $this->session->userdata("Player_Logged");
if($Session) {
// Get the transaction data
$paypalInfo = $this->input->post();
$data['item_name']= $paypalInfo['item_name'];
$data['item_number']= $paypalInfo['item_number'];
$data['item_idr']= $paypalInfo['item_idr'];
$data['txn_id'] = $paypalInfo["txn_id"];
$data['payment_amt'] = $paypalInfo["payment_gross"];
$data['currency_code'] = $paypalInfo["mc_currency"];
$data['status'] = $paypalInfo["payment_status"];
// Get user ID from 'users' table.
$IGN = $this->session->userdata['Player_Logged']['id'];
// Pass the transaction data to view
$this->load->view('paypal/success', $data);
// Insert the transaction data in the database
// This "custom" is old method by documentation, updated by me :P ('user_id' is 'UserID' [I changed column name in database])
//$datatobase['user_id'] = $paypalInfo["custom"];
$datatobase['UserID'] = $IGN;
$datatobase['PackageID'] = $paypalInfo["item_number"];
// ne barai taka e
$datatobase['itemid'] = $paypalInfo["item_idr"];
$datatobase['txn_id'] = $paypalInfo["txn_id"];
$datatobase['payment_gross'] = $paypalInfo["mc_gross"];
$datatobase['currency_code'] = $paypalInfo["mc_currency"];
$datatobase['payer_email'] = $paypalInfo["payer_email"];
$datatobase['payment_status'] = $paypalInfo["payment_status"];
// Insert the gamerewards data in the database
$rewardstobase['UserID'] = $IGN;
$rewardstobase['ItemID'] = $paypalInfo["item_idr"];
$rewardstobase['EnhID'] = "1957";
$rewardstobase['Equipped'] = "0";
$rewardstobase['Quantity'] = "1";
$rewardstobase['Bank'] = "0";
// Insert the transaction data in the database
$this->product->insertTransaction($datatobase);
// Insert the gamerewards data in the database
$this->product->insertGameRewards($rewardstobase);
} else {
echo '<div class="alert alert-warning alert-dismissible fade show" role="alert"><strong>Error</strong> Error :( ! You need to log in to your account first.
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>';
$this->output->set_header('refresh:5; url=http://192.168.1.14/web/Home');
}
}
function cancel(){
// Load payment failed view
$this->load->view('paypal/cancel');
}
function ipn(){
// Paypal posts the transaction data
$paypalInfo = $this->input->post();
if(!empty($paypalInfo)){
// Validate and get the ipn response
$ipnCheck = $this->paypal_lib->validate_ipn($paypalInfo);
// Check whether the transaction is valid
if($ipnCheck){
// Insert the transaction data in the database
$data['user_id'] = $paypalInfo["custom"];
$data['product_id'] = $paypalInfo["item_number"];
$data['txn_id'] = $paypalInfo["txn_id"];
$data['payment_gross'] = $paypalInfo["mc_gross"];
$data['currency_code'] = $paypalInfo["mc_currency"];
$data['payer_email'] = $paypalInfo["payer_email"];
$data['payment_status'] = $paypalInfo["payment_status"];
$this->product->insertTransaction($data);
}
}
}
My product controller:
function __construct() {
$this->proTable = 'web_store';
$this->transTable = 'purchases_users';
$this->GameRewards = 'users_items';
}
/*
* Fetch products data from the database
* #param id returns a single record if specified, otherwise all records
*/
public function getRows($id = ''){
$this->db->select('*');
$this->db->from($this->proTable);
$this->db->where('status', '1');
if($id){
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('Title', 'asc');
$query = $this->db->get();
$result = $query->result_array();
}
// return fetched data
return !empty($result)?$result:false;
}
/*
* Insert data in the database
* #param data array
*/
public function insertTransaction($data){
$insert = $this->db->insert($this->transTable,$data);
return $insert?true:false;
}
/*
* Insert data in the database
* #param data array
*/
public function insertGameRewards($data){
$insert = $this->db->insert($this->GameRewards,$data);
return $insert?true:false;
}
I tried to add new field 'item_idr' and get column 'itemid' with the same method how other fields are get by this library but it didn't work. I get error message. Even more details of the error message I get:
Severity: Notice
Message: Undefined index: item_idr
Filename: controllers/Paypal.php
Line Number: 20
Backtrace:
File: C:\laragon\www\web\application\controllers\Paypal.php
Line: 20
Function: _error_handler
File: C:\laragon\www\web\index.php
Line: 315
Function: require_once`

Maybe you don't have the control named "item_idr" in your view.
In Paypal.php at line
data['item_idr']= $paypalInfo['item_idr'];
it takes info from
$paypalInfo = $this->input->post();
As a side note, you can use CI form library (see CI documentation for form helper here) to extract the $_POST values, so you can benefit from form validation and sanitation of entries.
Anyways... coming back...
you are taking $_POST['item_idr'] and that is the error you get. So it is unrelated to your table and database, but related to the fact that your view doesn't have any
<input type="text" name="item_idr" id="item_idr">
or similar

Related

BadMethodCallException in Macroable.php line 81:Method update does not exist

I an developing a page to create, update, delete and view an event in which there is error while updating the event. There is a event table and a event_collection table. In that event_collection table there is event_id which is id of an event and a collection_id which is from other table collection.
When i create an event, all the data gets stored in event table except the collection one. in the collection table data gets stored in one by one manner like if I check 2 items in collection, it will generate 2 ids with same event_id and 2 collection_ids.
There is problem in update, when i try to update the code, it gives me error as
BadMethodCallException in Macroable.php line 81:
Method update does not exist.
Update method is:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
$checkbox_selection = Input::get('agree');
$choosen_checkbox = $id;
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
// return $collection_event;
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
// $collection_id = $id;
foreach($collection_event as $k){
// return $k;
if($k->event_id == $choosen_checkbox){
$data = $request->all();
$data['event_id']= $choosen_checkbox;
$data['collection_id'] = $collection;
$collection_event->update($data);
}
}
}
}
My store method is:
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
// return $checkbox_collection;
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
$event_id = $query->id;
$pro_id = $query->provider_org_id;
/*For the checkbox selection, if they are multiple store each separately*/
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
$collection_id = $query->id;
if($collection_id){
$data = $request->all();
$data['event_id']= $collection_id;
$data['collection_id'] = $collection;
$create_collection = EventCollection::create($data);
}
}
}
return view('event.pic_upload',compact('event_id','pro_id'));
}
Store method works properly! Can someone please tell any solution? I am badly stucked in this.
I do not think the 'update' method works on collections.
This line will return a collection
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
You do not want a collection, rather a query. As given in the docs:
`App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);`
Try removing the '->get()' from the statement.

Cannot get data from mysql query to controller

Hello I am using codeigniter framework for a project, I have a controller which is calling the data from a model function. Here is the controller.
public function getThirdPartyRR($token){
if ($this->input->is_ajax_request()){
// $data = json_decode(file_get_contents('php://input'), true);
// Following is loaded automatically in the constructor.
//$this->load->model('user_profile');
$userid = $this->myajax->getUserByAuth($token);
if ($userid){
$this->load->model("riskrating_page");
/* If we have an impersonated user in the session, let's use him/her. */
if (isset($_SESSION['userImpersonated'])) {
if ($_SESSION['userImpersonated'] > 0) {
$userid = $_SESSION['userImpersonated'];
}
}
// $resultList value could be null also.
$result = $this->riskrating_page->getThirdPartydata($userid);
/* Little bit of magic :). */
$thirdpartylist = json_decode(json_encode($result), true);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($thirdpartylist));
} else {
return $this->output->set_status_header('401', 'Could not identify the user!');
}
} else {
return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
}
}
And here is the query function in the model where I get the data from.
function getThirdPartydata($id){
$query = 'SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = \'user_thirdparty_rr\'
WHERE a.Owner = '.$id. ' and
a.UPDATE_DT is null;';
}
But when I debug it using netbeans, its shows that in my controller in the $result function I get null meaning I couldnt grab any data from mysql.
Here is the search result from mysql.
You only write your query not fetch any data from your query result
function getThirdPartydata($id){
$query = "SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = 'user_thirdparty_rr'
WHERE a.Owner = '$id' and
a.UPDATE_DT is null";
$this->db->query($query);// execute your query
return $query->result_array();// fetch data
}

MySQLi get last insert ID and pass it true function

In my I am trying to retrieve the last_insert (ID) from a query true calling a function here is where i call my function:
$lead = $_leadh->addLead($lead_data, $call_data['number'], $user);
$LeadID = $lead['id'];
I am not getting any result? This is my addLead function:
function addLead(array $lead_data, $number, $user) {
//check if lead with same number and name exist in db
if ($checker = >= 1)
{
//return lead id as existed
$data = $query->fetch_array(MYSQLI_ASSOC);
return array('id'=>$data['lead_id'], 'exists'=>true);
}
else
{
//insert new lead into db
if ($query = $this->QueryDB("INSERT", "INTO leads (lead_name)
VALUES ('".$this->EscapeString($lead_data['lead_name'])))
{
//return lead id as new
return array('id'=>$this->insert_id, 'exists'=>false);
}
else
{
//output error if insertion fail
return false;
}
}}
You are returning array from addLead function but while calling you are not getting in any variable:
$_leadh->addLead($lead_data, $call_data['number'], $user);
$LeadID = $lead['id'];
should be like below:
$lead = $_leadh->addLead($lead_data, $call_data['number'], $user);
$LeadID = $lead['id'];

Exception information: Message: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

I have a code here that, has to search and post back information selected in a table above the add button, the search works but im having a problem with the post back to the table function. These are the lines it shows to have errors.
C:\xampp\htdocs\portal-gep-2\application\models\ServiceProviders.php(68): Zend_Db_Table_Abstract->fetchRow(Object(Zend_Db_Table_Select))
public function getName($id)
{
$select = $this->select();
$select->where('service_provider_id = ?', $id);
$result = $this->fetchRow($select); //this line
return $result['service_provider_name'];
}
#6 C:\xampp\htdocs\portal-gep-2\application\modules\admin\controllers\AjaxController.php(1104): Model_ServiceProviders->getName(NULL)
public function postserviceproviderAction()
{
$form = new Form_IndustrialTable();
$this->view->form = $form;
if(!$form->isValid($_POST))
{
$values=$form->getValues();
}
$sp = $this->getRequest()->getPost('serviceprovider', null);
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id); //this line
$rtn_array= array( 'sp' => $sp,
'serviceprovider ' => $serviceprovider);
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
echo Zend_Json::encode($rtn_array);
}
You don't put any initial value to $id so it's null which causes error.
You want SQL query to look something like SELECT * FROM service_providers WHERE service_provider_id = 50, but for this you have to provide id which you want to find (50 in this example). You need to add some value to variable $id before using in $select->where('service_provider_id = ?', $id);, but your code you never put any value to variable $id.
If I'm guessing your idea then you need to change line:
$serviceprovider = $mdlserviceprovider ->getName($id);
to:
$serviceprovider = $mdlserviceprovider ->getName($sp);
Also this part of your code probably unnecessary as it does nothing:
$form = new Form_IndustrialTable();
$this->view->form = $form;
if(!$form->isValid($_POST))
{
$values=$form->getValues(); //you never use $values
}

get query results from cdbcommand Yii

I've been trying to get the results from my query for the past two hours, in my model I have this
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select fromm from city_fare_final');
$data->queryRow();
return $data ;
}
in the controller
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$model=new QuoteForm();
if(isset($_POST['QuoteForm']))
{
$model->attributes=$_POST['QuoteForm'];
if ($model->validate())
{
$priceTable=new CityFareFinal;
$priceTable->fromm=$model->pickupL;
$priceTable->too=$model->dropoffL;
$priceTable->type_of_car=$model->type;
this->render('result',array('model'=>$priceTable))
}
}
else
{
$this->render('index',array('model'=>$model));
}
}
and in the view
<div id="moduleResult">
<span><?php echo $model->getQuotes() ;?><------ Here</span>
</div>
but it always give me an error saying "Object of class CDbCommand could not be converted to string ", what can I do to get the results of my query made in the model???
Regards
Gabriel
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select fromm from city_fare_final');
$data->queryRow();
return $data ;
}
Your getQuotes() return Object of class CDbCommand:
+ You returned $data in the function instead of $data->queryRow().
By the way, you cannot use echo for array data.
The below example is used for fetching data from DB to view by using DAO with Yii: I suppose you have Person model and Person controller
In your Person model:
function getData() {
$sql = "SELECT * from Person";
$data = Yii::app()->db
->createCommand($sql)
->queryAll();
return $data;
}
In your controller:
function index(){
$data = Person::model()->getData();
$this->render('your_view',array(
'data'=>$data,
));
}
In your view: you can foreach your data to echo items in the array data:
<?php foreach($data as $row): ?>
//show something you want
<?php echo $row->name; ?>
<?php endforeach; ?>
$data->queryRow(); returns result in array format. Your code is returning $data which is an object not result of query. That's why you are getting this error.
If you want to fetch single value you can use $data->queryScalar();
In case of queryRow() your code will be
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select * from city_fare_final');
$result = $data->queryRow();
return $result ; //this will return result in array format (single row)
}
for a single field value you code will be
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select xyz from city_fare_final');
$result = $data->queryScalar();
return $result; //return single value of xyz column
}
I hope this will help.
below sample code to traverse rows returned by queryAll
$connection = Yii::app()->db;
$command = $connection->createCommand("Select * from table");
$caterow = $command->queryAll(); //executes the SQL statement and returns the all rows
foreach($caterow as $retcat )
{
echo $retcat["ColumnName"] ;
}
Returns Arrary of rows with fields
Model: Notices.php:
---------------------------------
public function getNoticesBlog($offset = 0){
$dataResult = Yii::app()->db->createCommand()->select('*')->from($this->tableName())
->andWhere("delete_flg=:delete_flg",array(':delete_flg'=>0))
->andWhere("publish=:publish",array(':publish'=>1))
->limit(3)->offset($offset)->order('created_on DESC')->queryAll();
return $dataResult;
}
Controller: NoticesController.php
$firstNotices = Notices::model()->getNoticesBlog(0);
$secondNotices = Notices::model()->getNoticesBlog(3);
$thirdNotices = Notices::model()->getNoticesBlog(6);
$this->render('Notices',array(
'firstNotices'=>$firstNotices,
'secondNotices'=>$secondNotices,
'thirdNotices'=>$thirdNotices,
)
);

Categories