Trying to get property of non-object on codeigniter in ajax error access - ajax

I have a code to cek if the user is exist. I return some data to display to user. This is my code
Model
public function cek_exist_master($no_eir){
$this->db->select('REPAIR_ESTIMATE_ID, EIR_REF');
$this->db->where('EIR_REF', $no_eir);
$query = $this->db->get('tb_master_repair_estimate');
return $query;
}
CONTROLLER
$cek_master =$this->m_surveyor->cek_exist_master($this->input->post('EIR_REF'));
echo $cek_master->row()->REPAIR_ESTIMATE_ID;
And this is the database looked like :
mysql> desc tb_master_repair_estimate;
+--------------------+-----------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+-----------------------+------+-----+-------------------+-----------------------------+
| REPAIR_ESTIMATE_ID | int(11) | NO | PRI | NULL | auto_increment |
| EIR_REF | varchar(30) | YES | UNI | NULL | |
| NO_TANK | int(11) | YES | MUL | NULL | |
| COSTUMER_ID | int(11) | YES | MUL | NULL | |
| TANK_ID | int(11) | YES | MUL | NULL | |
+--------------------+-----------------------+------+-----+-------------------+-----------------------------+
24 rows in set (0.01 sec)
CI gives me an error like this,
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: surveyor/c_surveyor.php
Any help it so appreciate
Update,
Sorry, have bad copy paste on stackoverflow. I still get those error untill Now

You forgot the $ sign in your controller. It should be:
$cek_master = $this->m_surveyor->cek_exist_master($this->input->post('EIR_REF'));

Maybe a typo?
$cek_master = this->m_surveyor->...
Should be
$cek_master = $this->m_surveyor->...

First check that you load your model "m_surveyor" into controller.

CONTROLLER.. Change in controller code
$cek_master =this->m_surveyor->cek_exist_master($this->input->post('EIR_REF'));
echo is_object($cek_master->row()) ? $cek_master->row()->REPAIR_ESTIMATE_ID : '';

Related

Does Go Gorm provide any method to auto map existing tables in Mysql database

I am a newcomer to Go. I have an old tool to check and compare data in the Mysql database to my device, and I want to rewrite the tool in Go.
Since the tables and data have been already in the Mysql, I try to use GORM to auto map the existing tables. But I am not sure how to do that? I did not find any description of automapping an existing table in the GORM documentation.
I redeclare the existing table model and try to query data. The procedure is as below:
For example one of my tables is like this:
MariaDB [neutron]> desc lbaas_loadbalancers;
+---------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+-------+
| project_id | varchar(255) | YES | MUL | NULL | |
| id | varchar(36) | NO | PRI | NULL | |
| name | varchar(255) | YES | | NULL | |
| description | varchar(255) | YES | | NULL | |
| vip_port_id | varchar(36) | YES | MUL | NULL | |
| vip_subnet_id | varchar(36) | NO | | NULL | |
| vip_address | varchar(36) | YES | | NULL | |
| admin_state_up | tinyint(1) | NO | | NULL | |
| provisioning_status | varchar(16) | NO | | NULL | |
| operating_status | varchar(16) | NO | | NULL | |
| flavor_id | varchar(36) | YES | MUL | NULL | |
+---------------------+--------------+------+-----+---------+-------+
11 rows in set (0.002 sec)
MariaDB [neutron]> select * from lbaas_loadbalancers \G;
*************************** 1. row ***************************
project_id: 346052548d924ee095b3c2a4f05244ac
id: f6638d02-29f8-41aa-9433-179bf49f5fbd
name: test1
description:
vip_port_id: 21cebbd5-fa4c-4d20-9858-d14ba3eacea8
vip_subnet_id: 0916f471-afcd-48ee-afc5-56bcb0efa963
vip_address: 172.168.1.6
admin_state_up: 1
provisioning_status: ACTIVE
operating_status: ONLINE
flavor_id: NULL
1 row in set (0.003 sec)
Then I try to use GORM mapping the table. I just chosen two fields ID and Name for the test.
package main
import (
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// declare only two attribute in the model for test purpose
type Lbaas_loadbalancers struct {
ID string
Name string
}
func main() {
var lb Lbaas_loadbalancers
dsn := "test:test#tcp(192.168.0.17:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("connection error")
}
test := db.Take(&lb)
log.Println("test err is ", test.Error)
log.Println(test.RowsAffected)
// this line report error: ./db.go:25:6: test.ID undefined (type *gorm.DB has no field or method ID)
log.Println(test.ID)
// if I comment the above line, this print out 'mysql', but the actual name is 'test1'.
log.Println(test.Name())
}
Finally, I run go run db.go, I got this error:
➜ test git:(main) ✗ go run db.go
# command-line-arguments
./db.go:27:20: cannot convert test.Config.Dialector.Name (type func() string) to type string
It seems not the right way to do it. what is the correct way to auto map an existing database in Mysql by using GORM module?
If the below code is the correct way, why I cannot get the ID attribute from the return value of db.Take method directly? Do I need to do data conversion?
Please give me some hints, thanks.
I know what is wrong here, I should not get ID and Name from the db.Take return, It takes the address of lb variable, and change the lb.
I am so silly, just realized the problem. :)

Laravel get value from db with columns key/value

I have a table on my DB with these columnns:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| value | varchar(255) | NO | | NULL | |
+-----------------+---------------------+------+-----+---------+----------------+
I would access to value values by name.
For example I have these datas:
+----+------------+------------+
| id | name | value |
+----+------------+------------+
| 1 | start_date | 2020-01-01 |
| 2 | end_date | 2021-01-01 |
+----+------------+------------+
I would to get '2020-01-01' by 'start_date'.
I tried this code, but I'm not satisfyed because with this code I get all values of the row, not only the value expected.
Configuration::get()->keyBy('start_date');
I'm not sure I was clear.
Let me know.
Thanks a lot!!
Assuming you want to get an array of key/value pairs, and each key in the name column is unique, you can simply use pluck() (https://laravel.com/docs/8.x/collections#method-pluck):
$configuration = Configuration::pluck('value', 'name');
dd($configuration);
// ['start_date' => '2020-01-01', 'end_date' => '2021-01-01']
Then, you'd use simply array access to use these configuration settings where applicable:
$startDate = $configuration['start_date']; // '2020-01-01'
$endDate = $configuration['end_date']; // '2021-01-01'
...

Undefined binding(s) detected when compiling SELECT query

I am following a tutorial for strapi and am stuck at a part where I query for dishes belonging to a restaurant. I'm sure everything is set up properly with a one(restaurant) to many(dishes) relationship defined but the query doesn't work. I've traced it to the actual query which is:
query {
restaurant(id: "1") {
id
name
dishes {
name
description
}
}
}
which returns an error when I run it in playground. The query doesn't show any issues while I write it and doesn't allow me to write anything like:
query {
restaurant(where:{id: "1"}) {
id
name
dishes {
name
description
}
}
}
My database is mysql and the two tables look like this:
mysql> describe dishes;
+-------------+---------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | MUL | NULL | |
| description | longtext | YES | | NULL | |
| price | decimal(10,2) | YES | | NULL | |
| restaurant | int(11) | YES | | NULL | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
| updated_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+---------------+------+-----+-------------------+-----------------------------+
7 rows in set (0.00 sec)
mysql> describe restaurants;
+-------------+--------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | MUL | NULL | |
| description | longtext | YES | | NULL | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
| updated_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+--------------+------+-----+-------------------+-----------------------------+
5 rows in set (0.00 sec)
These tables where auto generated by strapi.
The full error in playground is this:
{
"errors": [
{
"message": "Undefined binding(s) detected when compiling SELECT query: select `restaurants`.* from `restaurants` where `restaurants`.`id` = ? limit ?",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"restaurant"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"Error: Undefined binding(s) detected when compiling SELECT query: select `restaurants`.* from `restaurants` where `restaurants`.`id` = ? limit ?",
" at QueryCompiler_MySQL.toSQL (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/query/compiler.js:85:13)",
" at Builder.toSQL (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/query/builder.js:72:44)",
" at /Users/redqueen/development/deliveroo/server/node_modules/knex/lib/runner.js:37:34",
"From previous event:",
" at Runner.run (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/runner.js:33:30)",
" at Builder.Target.then (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/interface.js:23:43)",
" at runCallback (timers.js:705:18)",
" at tryOnImmediate (timers.js:676:5)",
" at processImmediate (timers.js:658:5)",
" at process.topLevelDomainCallback (domain.js:120:23)"
]
}
}
}
],
"data":
Any idea why this is happening?
It seems this was a bug with the alpha.v20 and alpha.v21 versions of strapi. A bug fix has been published to solve it, an issue thread on github is here.

mysql timestamp error with time.Now() golang

How to save time.Now() in mysql table, column name as created_at timestamp null.
I am getting error :
Error:Error 1292: Incorrect datetime value: '2017-08-05 19:06:14.190 +0000' for column 'created_at' at row 1
More Information as asked :- ( I am using fragmenta cms, so all reference code with their line number is given below )
Table schema :-
mysql> describe users;
+----------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| status | int(11) | YES | | NULL | |
| role | int(11) | YES | | NULL | |
| name | varchar(250) | YES | | NULL | |
| email | varchar(250) | YES | | NULL | |
| title | varchar(250) | YES | | NULL | |
| summary | text | YES | | NULL | |
| text | text | YES | | NULL | |
| image_id | int(11) | YES | | NULL | |
| password_hash | varchar(250) | YES | | NULL | |
| password_reset_token | text | YES | | NULL | |
| password_reset_at | timestamp | YES | | NULL | |
+----------------------+--------------+------+-----+---------+----------------+
Code that is running it to save :-
At line no. 62 here ( https://github.com/fragmenta/fragmenta-cms/blob/master/src/pages/actions/setup.go#L62 )
It calls code
user := users.New()
in Line no. 51 at file here ( https://github.com/fragmenta/fragmenta-cms/blob/master/src/users/query.go#L51 )
New() function is setup.
Which is like :-
func New() *User {
user := &User{}
user.CreatedAt = time.Now()
user.UpdatedAt = time.Now()
user.TableName = TableName
user.KeyName = KeyName
user.Status = status.Draft
return user
}
and their connecting / mysql opening pattern is located here ( https://github.com/fragmenta/query/blob/master/adapters/database_mysql.go#L23 ) .
There is a bug in https://github.com/fragmenta/query. The TimeString method in query/adapters/database.go is not valid for all DBMS adapters.
// TimeString - given a time, return the standard string representation
func (db *Adapter) TimeString(t time.Time) string {
return t.Format("2006-01-02 15:04:05.000 -0700")
}
It's not valid for a MySQL timestamp: MySQL 5.7 Reference Manual, 11.3.1 The DATE, DATETIME, and TIMESTAMP Types. The MySQL TimeString method in query/adapters/database_mysql.go should be:
// TimeString - given a time, return the MySQL standard string representation
func (db *MysqlAdapter) TimeString(t time.Time) string {
return t.Format("2006-01-02 15:04:05.999999")
}
You are trying to insert it using a string query.go:36:
now := query.TimeString(time.Now().UTC())
that is generated by the package that you are using database.go:59:
return t.Format("2006-01-02 15:04:05.000 -0700")
MySQL expects it to be in the pattern of yyyy-MM-dd hh:mm:ss, use the following snippet to apply the pattern to you current Time.time object:
now := time.Now().UTC().Format("2006-01-02 03:04:05")
Anyway, why not to use the SQL function NOW() when inserting the record ?

Return filtered records from a returned set of data from two tables

I have three tables:
- Venue
- Space (belongs to Venue)
- Included Space (belongs to Space)
I receive the id of a Venue in the route and return all the related spaces that I know have Included Spaces(a field called num_included_spaces__c on the Space record that maintains a count of its children). Now that I have all the related parent Spaces for that Venue, I need to find all of the Included Spaces for them.
An Included Space is still a Space, it just happens to have a parent that resides in the same table. I'm trying to turn this:
Venue = Rockdog
- Space = Upstairs
- Space = Media Room
- Space = Courtyard
- Space = Downstairs
- Space = Front Patio
- Space = Indoor Bar
Into this:
Venue = Rockdog
- Space = Upstairs
-- Included Space = Media Room
-- Included Space = Courtyard
- Space = Downstairs
-- Included Space = Front Patio
-- Included Space = Indoor Bar
The Included Spaces table has belongs_to__c and space__c as fields, where belongs_to__c is the id of the parent space and space__c is the id of the child. So i'm looking to find all the Included Spaces where belongs_to_c matches the id of any #spaces returned below
#sub_spaces = Space.where("venue__c = ? AND num_included_spaces__c = ?", params[:venue],0)
#spaces = Space.where("venue__c = ? AND num_included_spaces__c > ?", params[:venue],0)
How would I write this Active Record Query for #included_spaces?
my database schema.
mysql> describe venues;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0,00 sec)
mysql> describe spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| venue_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
mysql> describe included_spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| space_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
Below function will somehow give you the result you need (in console ofcourse ) however it's not a good solution - it queries database more than needed. However it is the easy -))
def foo id
v = Venue.find(id)
puts v.name
v.spaces.each do |space|
puts space.name
space.included_spaces.each do |spis|
puts spis.name
end
end
end
You can also try a more complex query sth like,
mysql> SELECT spaces.name, included_spaces.name FROM `spaces` INNER JOIN `venues` ON `venues`.`id` = `spaces`.`venue_id` INNER JOIN `included_spaces` ON `included_spaces`.`space_id` = `spaces`.`id` WHERE `spaces`.`venue_id` = 1
-> ;
+------------+-----------+
| name | name |
+------------+-----------+
| Upstairs, | Front |
| Upstairs, | Patio, |
| Upstairs, | Indoor |
| Upstairs, | Bar |
| Downstairs | Media |
| Downstairs | Room, |
| Downstairs | Courtyard |
+------------+-----------+
7 rows in set (0,00 sec)
which should be translated to active record as
Space.joins(:venue)
.joins(:included_spaces)
.where(venue_id: 1)
.select('spaces.name, included_spaces.name')

Resources