Zero (0 ) Database Result in Codeigniter - mysql

In view->new_entry.php
<?=form_open(base_url().'home/insert_entry/')?>
<p>Title: <?=form_input('title')?></p>
<p>Content: <?=form_textarea('content')?></p>
<p>Tags: <?=form_input('tags')?> (comma separated)</p>
<?=form_submit('submit', 'Insert')?>
In home/insert_entry:
public function insert_entry(){
login_site();
$entry = array(
'permalink' => permalink($this->input->post('title')),
'author' => $this->session->userdata('username'),
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'date' => date('Y-m-d H:i:s'),
'tags' => $this->input->post('tags')
);
$this->home_model->insert('ads', $entry);
redirect(base_url());
}
In home_model:
public function insert($table, $data){
return $this->db->insert($table, $data);
}
I am getting all result zero (0) on database.

Try checking the affected_rows if it is >= 1
public function insert($table, $data){
$this->db->insert($table, $data);
return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
}

Enable profiler in your controller.
eg:
$this->output->enable_profiler(TRUE);
See if your query is executed and if it's correct...

Related

API Create Multiple Input Laravel

I'm currently creating API for multiple inputs using laravel. The data will be stored into two tables : Order and Detail_Order. One order can have many detail orders.
But now, the data only stored into Order table, and got an error: ErrorException: Invalid argument supplied for foreach() in file. Does anyone know how? Thank you.
Here's my code :
public function createDetail($total_passenger, $id_trip, $id_users, Request $request){
$trip = Trip::where(['id_trip' => $id_trip])->get();
$seat = $request->id_seat;
if(Detail_Order::where(['id_trip' => $id_trip, 'id_seat' => $seat])
->where('status', '!=', 5)
->exists()) {
return $this->error("Seat has been booked");
}else{
$order = new Order();
$order_select = Order::select('id_order');
$order_count = $order_select->count();
if ($order_count === 0) {
$order->id_order = 'P1';
}else{
$lastrow=$order_select->orderBy('created_at','desc')->first();
$lastrow_id = explode('P', $lastrow->id_order);
$new_id = $lastrow_id[1]+1;
$order->id_order = 'P'.$new_id;
}
$order->id_trip = $id_trip;
$order->id_users = $id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = 'O4';
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'gender' => $request->gender[$key],
'departure' => $request->departure[$key],
'destination' => $request->destination[$key],
'phone' => $request->phone[$key],
'status' => 1
]);
}
return response()->json([
'status' => true,
'message' => "Successfully saved data",
'data' => $order
]);
}

Inserting variables in Yii2 to Database

I am trying to insert $product, $pric and $user to database table cart. Following is the function that I have created in SiteController.php.
public function actionCartadd($id)
{
$product = Additem::find()
->select('product')
->where(['id' => $id])
->one();
$pric = Additem::find()
->select('price')
->where(['id' => $id])
->one();
$user = Yii::$app->user->identity->username;
$connection = Yii::$app->getDb();
$result = Yii::$app->db->createCommand()
->insert('cart', [
'product' => '$product',
'price' => '$pric',
'user' => '$user',
])->execute();
if ($result)
return $this->render('custstore');
}
However, this end up in error. Can anyone suggest any fix
Try this following code
$result = Yii::$app->db->createCommand()->insert('cart', [
'product' => $product->product,
'price' => $pric->price,
'user' => $user
])->execute();
Look at this fragment:
'product' => '$product',
'price' => '$pric',
'user' => '$user',
Use double quotes in values or just variables without quotes
Also, better way to fetch product and price:
$productItem = Additem::findOne($id);
if ($productItem instanceof Additem) {
$product = $productItem->product;
$pric = $productItem->price;
}

How to use custom php function to filter in ActiveDataProvider

I have this problem: I need to get data from database and filter them. but then I need to use custom php function to filter those filtered results using data from it.
Clasic search function in ActiveDataProvider
public function search($params) {
$query = Passenger::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// I guess my function would go like here
Passenger::filterResultsEvenMore($dataProvider);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'passenger_id' => $this->passenger_id,
// ...
'version' => $this->version,
'status' => $this->status,
]);
return $dataProvider;
}
So my question is how to work with results of dataProvider because if I vardump the variable it looks like this and no actual data there.
yii\data\ActiveDataProvider Object
(
[query] => common\models\PassengerQuery Object
(
[sql] =>
[on] =>
[joinWith] =>
[select] =>
[selectOption] =>
[distinct] =>
[from] =>
[groupBy] =>
[join] =>
[having] =>
[union] =>
[params] => Array()
[_events:yii\base\Component:private] => Array()
[_behaviors:yii\base\Component:private] => Array()
[where] => Array
(
[status] => 1
)
[limit] =>
[offset] =>
[orderBy] =>
[indexBy] =>
[emulateExecution] =>
[modelClass] => common\models\Passenger
[with] =>
[asArray] =>
[multiple] =>
[primaryModel] =>
[link] =>
[via] =>
[inverseOf] =>
)
[key] =>
[db] =>
[id] =>
[_sort:yii\data\BaseDataProvider:private] =>
[_pagination:yii\data\BaseDataProvider:private] =>
[_keys:yii\data\BaseDataProvider:private] =>
[_models:yii\data\BaseDataProvider:private] =>
[_totalCount:yii\data\BaseDataProvider:private] =>
[_events:yii\base\Component:private] => Array()
[_behaviors:yii\base\Component:private] =>
)
UPDATE
I need to use function like this for each record:
if (myFunction(table_column_1, table_column_2)) {
result_is_ok_return_it
} else {
do_not_return_this_record
}
Why do you don't add your additional filters to query object used in DataProvider?
You can parse your conditions to $query->andFilterWhere(). If you need custom function for it just modify $dataProvider->query object inside function. After execute query in data provider you can only filter results by manually filter array of models stored in $dataProvider->models
To get result use models property or getModels()
For example,
$dataProvider->models;
OR
$dataProvider->getModels();
I think I came across a solution, (looks like it is working)
http://www.yiiframework.com/doc-2.0/yii-data-basedataprovider.html#setModels()-detail
After I do all my usual search stuff as described in question at beginning, I would do something like this using setModels() function
class PassengerSearch extends Passenger
public $status; // virtual attribute not present in database table
public function rules()
{
return [
// ... some other rules
[['status'], 'safe'],
];
}
// ...
$filtered_models = [];
$filter_models = false; // if you only want to filter if there is some value
foreach ($dataProvider->models as $model) {
// if ($model->status == 1) // example
if (!empty($this->status) && $model->status == $this->status) { // better approach, using virtual attribute $status
$filter_models = true;
$filtered_models[] = $model;
}
}
if ($filter_models)
$dataProvider->setModels($filtered_models);
return $dataProvider;
}

Yii2: What is the correct way to define relationships among multiple tables?

In a controller I have the following code:
public function actionView($id)
{
$query = new Query;
$query->select('*')
->from('table_1 t1')
->innerJoin('table_2 t2', 't2.t1_id = t1.id')
->innerJoin('table_3 t3', 't2.t3_id = t3.id')
->innerJoin('table_4 t4', 't3.t4_id = t4.id')
->andWhere('t1.id = ' . $id);
$rows = $query->all();
return $this->render('view', [
'model' => $this->findModel($id),
'rows' => $rows,
]);
}
See the db schema: https://github.com/AntoninSlejska/yii-test/blob/master/example/sql/example-schema.png
In the view view.php are displayed data from tables_2-4, which are related to table_1:
foreach($rows as $row) {
echo $row['t2_field_1'];
echo $row['t2_field_2'];
...
}
See: Yii2 innerJoin()
and: http://www.yiiframework.com/doc-2.0/yii-db-query.html
It works, but I'm not sure, if it is the most correct Yii2's way.
I tried to define the relations in the model TableOne:
public function getTableTwoRecords()
{
return $this->hasMany(TableTwo::className(), ['t1_id' => 'id']);
}
public function getTableThreeRecords()
{
return $this->hasMany(TableThree::className(), ['id' => 't3_id'])
->via('tableTwoRecords');
}
public function getTableFourRecords()
{
return $this->hasMany(TableFour::className(), ['id' => 't4_id'])
->via('tableThreeRecords');
}
and then to join the records in the controller TableOneController:
$records = TableOne::find()
->innerJoinWith(['tableTwoRecords'])
->innerJoinWith(['tableThreeRecords'])
->innerJoinWith(['tableFourRecords'])
->all();
but it doesn't work. If I join only the first three tables, then it works. If I add the fourth table, then I receive the following error message: "Getting unknown property: frontend\models\TableOne::t3_id"
If I change the function getTableFourRecords() in this way:
public function getTableFourRecords()
{
return $this->hasOne(TableThree::className(), ['t4_id' => 'id']);
}
then I receive this error message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'table_4.t4_id' in 'on clause'
The SQL being executed was: SELECT table_1.* FROM table_1 INNER JOIN table_2 ON table_1.id = table_2.t1_id INNER JOIN table_3 ON table_2.t3_id = table_3.id INNER JOIN table_4 ON table_1.id = table_4.t4_id"
You should have to define key value pair in the relation eg:
class Customer extends ActiveRecord
{
public function getOrders()
{
return $this->hasMany(Order::className(), ['customer_id' => 'id']); // Always KEY => VALUE pair this relation relate to hasMany relation
}
}
class Order extends ActiveRecord
{
public function getCustomer()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
// Always KEY => VALUE pair this relation relate to hasOne relation
}
}
Now in your forth relation use:
public function getTableFourRecords()
{
return $this->hasOne(TableThree::className(), ['id' => 't4_id']);
}
You can read more on ActiveRecord here
Based on the answer of softark the simplest solution can look like this:
Model TableOne:
public function getTableTwoRecords()
{
return $this->hasMany(TableTwo::className(), ['t1_id' => 'id']);
}
Model TableTwo:
public function getTableThreeRecord()
{
return $this->hasOne(TableThree::className(), ['id' => 't3_id']);
}
Model TableThree:
public function getTableFourRecord()
{
return $this->hasOne(TableFour::className(), ['id' => 't4_id']);
}
Controller TableOneController:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
The view table-one/view.php:
foreach ($model->tableTwoRecords as $record) {
echo ' Table 2 >> ';
echo ' ID: ' . $record->id;
echo ' T1 ID: ' . $record->t1_id;
echo ' T3 ID: ' . $record->t3_id;
echo ' Table 3 >> ';
echo ' ID: ' . $record->tableThreeRecord->id;
echo ' T4 ID: ' . $record->tableThreeRecord->t4_id;
echo ' Table 4 >> ';
echo ' ID: ' . $record->tableThreeRecord->tableFourRecord->id;
echo ' <br>';
}
A solution based on the GridView is also possible.
Model TableTwo:
public function getTableOneRecord()
{
return $this->hasOne(TableOne::className(), ['id' => 't1_id']);
}
public function getTableThreeRecord()
{
return $this->hasOne(TableThree::className(), ['id' => 't3_id']);
}
public function getTableFourRecord()
{
return $this->hasOne(TableFour::className(), ['id' => 't4_id'])
->via('tableThreeRecord');
}
The function actionView in TableOneController, which was generated with Gii for the model TableTwo was edited:
use app\models\TableTwo;
use app\models\TableTwoSearch;
...
public function actionView($id)
{
$searchModel = new TableTwoSearch([
't1_id' => $id, // the data have to be filtered by the id of the displayed record
]);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('view', [
'model' => $this->findModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
and also the views/table-one/view.php:
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
't1_id',
'tableOneRecord.id',
't3_id',
'tableThreeRecord.id',
'tableThreeRecord.t4_id',
'tableFourRecord.id',
],
]);
See the code on Github.

cakephp2:How to get two different datas with different conditions from the same Model

I'm new to cakephp2 and mysql and need some help.
I want to get the data from yesterday and daybefore yesterday date from the same Model in cakephp2,
However the conditions will be different so I am trying to get the data by making two different methods that contains the find() with different conditions. ,however,I'ts not working. Here is the sample below ↓
This method getYesterday() will return the data as a array but I want to add a condition
that will check if the pageview count is not 0, how will I do that ?
public function getYesterday() {
$yes = array();
$dt = date('Y-m-d', strtotime('-1 day'));
// $dy = date('Y-m-d', strtotime('-2 day'));
$yesterday = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as yesterday_pv'),
'conditions' => array('dt' => "2014/09/26", 'is_crawler' => 0,'count(page_view)>'=>0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($yesterday as $y) {
$yes[] = $y;
//$i++;
}
return $yes;
}
The function below will get the data from daybefore yesterday
public function getDBY() {
$dayyes = array();
$dt = date('Y-m-d', strtotime('-2 day'));
$daybefore = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as daybefore_pv'),
'conditions' => array('dt' => "{$dt}", 'is_crawler' => 0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($daybefore as $dby) {
$dayyes[] = $dby;
//$i++;
}
return $dayyes;
}
The probelem is I'm not sure about this way, Is there a better solution that you can get the different result with different conditions in mysql cakephp2 ? The main thing I want to do Is to get the yesterdays data and daybefore yesterdays data from the same model but I'm not sure how I can do this, I've checked cakes documents but cant find the solution. Sorry for my broken English.