I recently added a new column to a MySQL database (featured), then added that column into my associative array. Rather than calling the data for the new column, I simply get 'null' in place of each entry, even after specifically requesting the column to be 'not null'.
I thought I may have been calling the data incorrectly, however, my array seems fine:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($blogs, array('title' => $row['title'], 'content' => $row['content'], 'featured' => $row['featured']));
}
And this is the response I get:
{"blogs":[{"title":"test-title","content":"test-content","featured":null}]}
I'm guessing this must be a MySQL issue, but I've no idea what it could be.
My guess is that the SQL query executed doesn't select this new column, or uses another name as the one you're expecting:
select title, content from ...
or
select title, content, feature as f from ...
You're using $row['...'] instead of $result['...']
Related
I'm trying to insert an array of data into a table in database but an error said Array to string conversion error
This is the post function in my controller, first i post an array of data. The values of the array will be the names, and numbers, they are not id. The id is only kodejdwl. This will be pass to my model
function index_post() {
$data = array(
'kodejdwl' => $this->post('kodejdwl'),
'tahun_akad' => $this->post('kode_tahun_akad'),
'semester' => $this->post('semester'),
'mk' => $this->post('mk'),
'ruangan' => $this->post('ruangan'),
'nama_dosen' => $this->post('nama_dosen'),
'namakelas' => $this->post('nama_kelas'),
'jam_mulai' => $this->post('jam_mulai'),
'jam_selesai' => $this->post('jam_selesai'),
);
}
After the data from above code is passed to the model. I created some new variables which are the id of each the name of the value in the array data. e.g if the value of data['mk'] is Website then the id will be 1 and that id will be stored in variable $kodemk and i do it to each value in the data. Then i created new_data which stores array of the id's which i previously made. Then i insert that array into one table in my database. I thought it would be fine but it said Array to string conversion error. What should i do so i could insert that array into the table in my database?
public function insert($data){
$this->db->select('thn_akad_id');
$tahunakad_id = $this->db->get_where('tik.thn_akad',array('tahun_akad'=>$data['tahun_akad'],'semester_semester_nm'=>$data['semester']))->result();
$this->db->flush_cache();
$this->db->select('kodemk');
$kode_mk = $this->db->get_where('tik.matakuliah',array('namamk'=>$data['mk']))->result();
$this->db->flush_cache();
$ruangan = $this->db->get_where('tik.ruangan', array('namaruang' => $data['ruangan']), 1)->result();
$this->db->flush_cache();
$this->db->select('nip');
$nip_dosen = $this->db->get_where('tik.staff',array('nama'=>$data['nama_dosen']))->result();
$this->db->flush_cache();
$this->db->select('kodeklas');
$kodeklas = $this->db->get_where('tik.kelas',array('namaklas'=>$data['namakelas']))->result();
$this->db->flush_cache();
$this->db->select('kode_jam');
$kode_mk = $this->db->get_where('tik.wkt_kuliah',array('jam_mulai'=>$data['jam_mulai'],'jam_selesai'=>$data['jam_selesai']))->result();
$this->db->flush_cache();
$new_data = array(
'kodejdwl' => $data['kodejdwl'],
'thn_akad_thn_akad_id' => $tahunakad_id,
'matakuliah_kodemk' => $kode_mk,
'ruangan_namaruang' => $ruangan,
'staff_nip' => $nip_dosen,
'kelas_kodeklas' => $kodeklas,
);
$insert = $this->db->insert('tik.jadwal_kul', $new_data);
return $this->db->affected_rows();
}
You probably want to use row() instead of result() because it'll contain only one result that you want. If you want to use result() and store multiple values then you'll have to use implode to concatenate them and store it as a string.
I've written a possible solution for your problem; Some things were missing, so I've mentioned them in the comments. See if this helps you.
public function insert($data){
$this->db->select('thn_akad_id');
$tahunakad_id = $this->db->get_where('tik.thn_akad',array('tahun_akad'=>$data['tahun_akad'],'semester_semester_nm'=>$data['semester']))->row(); // use row here
$this->db->flush_cache();
$this->db->select('kodemk');
$kode_mk = $this->db->get_where('tik.matakuliah',array('namamk'=>$data['mk']))->row();
$this->db->flush_cache();
// remove your_ruangan_column with your desired column name
$this->db->select('your_ruangan_column');
$ruangan = $this->db->get_where('tik.ruangan', array('namaruang' => $data['ruangan']), 1)->row();
$this->db->flush_cache();
$this->db->select('nip');
$nip_dosen = $this->db->get_where('tik.staff',array('nama'=>$data['nama_dosen']))->row();
$this->db->flush_cache();
$this->db->select('kodeklas');
$kodeklas = $this->db->get_where('tik.kelas',array('namaklas'=>$data['namakelas']))->row();
$this->db->flush_cache();
// Not sure where this ↓↓ is being used but you can use it the same way as others
$this->db->select('kode_jam');
// duplicate variable name here ↓↓ (fix this)
$kode_mk = $this->db->get_where('tik.wkt_kuliah',array('jam_mulai'=>$data['jam_mulai'],'jam_selesai'=>$data['jam_selesai']))->row();
$this->db->flush_cache();
$new_data = array(
'kodejdwl' => $data['kodejdwl'],
'thn_akad_thn_akad_id' => $tahunakad_id->thn_akad_id, // {$tahunakad_id} consists an object with the key {thn_akad_id}-- table_column_name
'matakuliah_kodemk' => $kode_mk->kodemk, // ...
'ruangan_namaruang' => $ruangan->your_ruangan_column, // ...
'staff_nip' => $nip_dosen->nip, // ...
'kelas_kodeklas' => $kodeklas->kodeklas // ...
);
$insert = $this->db->insert('tik.jadwal_kul', $new_data);
return $this->db->affected_rows();
}
Your are making a total of 7 separate trips to the database. Best practice recommends that you always minimize your trips to the database for best performance. The truth is that your task can be performed in a single trip to the database so long as you set up the correct INSERT query with SELECT subqueries.
I don't know what your non-English words are, so I will use generalized terms in my demo (I've tested this successfully in my own CI project). I am also going to reduce the total subqueries to 3 to reduce the redundance in my snippet.
$value1 = $this->db->select('columnA')->where('cond1', $val1)->get_compiled_select('childTableA');
$value2 = $this->db->select('columnB')->where('cond2', $val2)->get_compiled_select('childTableB');
$value3 = $this->db->select('columnC')->where('cond3', $val3)->get_compiled_select('childTableC');
return (int)$this->$db->query(
"INSERT INTO parentTable
(column1, column2, column1)
VALUES (
($value1),
($value2),
($value3)
)"
);
// to mirror your affected rows return... 1 will be returned on successful insert, or 0 on failure
Granted this isn't using the ActiveRecord technique to form the complete INSERT query, but this is because CI doesn't allow subqueries in the VALUES portion (say, if you were to use the set() method). I am guessing this is because different databases use differing syntax to form these kinds of INSERTs -- I don't know.
The bottom line is, so long as you are fetching a single column value from a single row on each of these sub-SELECTs, this single query will run faster and with far less code bloat than running N number of individual queries. Because all of the variables involved are injected into the sql string using get_compiled_select() the stability/security integrity should be the same.
I have a dropdown on my site that allows for multiple selections:
$this->Form->input('systems', array('label'=>'System Assignments', 'empty'=>'', 'default'=>'', 'div'=>false, 'multiple'=>true, 'class'=>'chosen',
'options'=>$systems));
This code from my controller populates the $systems variable:
$systems = $this->Discrepancy->find('list', array('fields' => array('id', 'description'),
'conditions'=>array('Discrepancy.deleted_record' => 0),
'order'=>array('Discrepancy.display_order'=>'ASC')));
$this->set(compact('systems'));
When the user makes their selection(s), the row ID's are stored as an array in a table called Users in a field called systems.
$system_string = implode(',', $this->request->data['User']['systems']);
$this->request->data['User']['systems'] = $system_string;
systems
-------
50,22
On my Edit screen, I would like to be able to use that array of values as my list of ID's for retrieving and displaying the user's system choices, by adding a 'value' parameter to the dropdown.
'value'=>array_key($chosen_systems);
How can I use these stored values in a $this->Model->find statement?
Got it. Guess I needed to write it all out first.
Put the following line in the $this->Model->find statement:
'conditions'=>array('Discrepancy.id'=>explode(',',$var_for_systems_from_db))
Here is my code -
$updatecompany = DB::table('Companies')
->where('ID', (int)$companyid)
->update(array(
'CompanyName' => $companyname,
'CompanyAddress' => $companyaddress,
'CompanyEmail' => $companyemail,
'ContactName' => $contactname,
'CompanyCity' => $companycity,
'CompanyState' => $companystate,
'CompanyZip' => $companyzipcode,
'CompanyPhone' => $companyphone,
));
$updatecompany is always 0. What might be the problem?
One of most possible reasons is that you are updating with the same data in the database.
There needs one out of the box solution, of course if you can do it.
So, no rows are updating, even if the SQL is correct.
Here is my suggestion:
Add a new column updatedOn in DB Table Companies.
The type should be TIMESTAMP and add attribute ON UPDATE CURRENT_TIMESTAMP.
This way you will always get row affected and hence you get return value other than 0.
You don't need to cast $companyId to an integer there. It does not help Laravel's query builder.
Use dd($companyId) and dump the variable before you run the query and find out what it is.
i nead to make a search with full text index and this code work:
$cursor=$collection->find(array('$text'=>(array('$search'=>$s))),
array("score"=> array('$meta'=>"textScore"))
);
i try to sort the cursor with:
$cursor =$cursor->sort(array("score"=>1));
when i try to read
var_dump($cursor->getNext());
i gave me this error
Uncaught exception 'MongoCursorException' with message 'localhost:27017: Can't canonicalize query: BadValue can't have a non-$meta sort on a $meta projection'
any idea?
You are attempting to sort on a meta field, not a normal fieldname.
The second argument to $collection->find() determines which fields of the document you (do/do not) want to be returned by the query.
This is similar to SELECT *... vs SELECT field1, field2 ... in SQL databases.
Now, in MongoDB 2.6 there is an additional keyword you can use here, $meta. This keyword allows you to "inject" fieldnames into the return document (that otherwise would not actually exist). The value of this injected fieldname would come from some sort of "meta data" of the document or query you are executing.
The $text query operator is an example of an operator that has more information available about the matched document.. Unfortunately, it has no way of telling you about this extra information since doing so would manipulate your document in unexpected way. It does however attach a metadata to the document - and it is up to you to decide if you have need for it or not.
The meta data the $text operator creates uses the keyword "textScore". If you want to include that data, you can do so by assigning it to a field name of your choice:
array("myFieldname" => array('$meta' => 'keyword'))
For example, in the case of $text search (textScore) we can inject the fieldname "score" into our document by passing this array as the 2nd argument to $collection->find():
array("score" => array('$meta' => 'textScore'))
Now we have injected a field called "score" into our return document which has the "textScore" value from the $text search.
But since this is still just meta data of the document, if you want to continue to use this value in any subsequent operations before executing the query, you still have to refer to it as $meta data.
This means, to sort on the field you have to sort on the $meta projection
array('score' => array('$meta' => 'textScore'))
Your full example then becomes:
<?php
$mc = new MongoClient();
$collection = $mc->selectCollection("myDatabase", "myCollection");
$string = "search string";
$cursor = $collection->find(
array('$text' => array('$search' => $string)),
array('score' => array('$meta' => 'textScore'))
);
$cursor = $cursor->sort(
array('score' => array('$meta' => 'textScore'))
);
foreach($cursor as $document) {
var_dump($document);
}
With CI, I want to insert one record in User table and one in Post table. Below is a brief of my code (two tables will have multiple columns, and I just use one as example).
$this->username=$user;
$this->db->insert('User',$this);
$this->title='my first post';
$this->db->insert('Post', $this);
However, the second insert will be something like "insert into Post (user, title) values ('$user', 'my first post'). And an error is reported that unknown column user in Post.
How can I clear the members in $this before inserting the next records (in another table)?
This happening becouse of
$this->username=$user;
You probably need to use
$this->db->insert('Post', $this->title);
And before you insert, set in title anything you want, but not
$this->db->insert('Post', $this);
However if you still want to work with an object, more information how to do this properly you can find here, http://ellislab.com/codeigniter/user-guide/database/active_record.html#insert
CI used array as the second argument in the insert method. The index will be the column name and the value referred by the index will be the value to be inserted. What you did was you just keep adding into the $this array.
When you first add username the array will look like this(neglecting the db) inside $this :
array( 'username' => $user );
When you add the title, it will become like this:
array( 'username' => $user, 'title' => 'my first post');
See how the previous entry still in there.
You can just unset($this->username);
or you can use another variable to hold your data instead of $this. Example:
$data = array('username' => $user);
$this->db->insert('User',$data);
$data = array('title' => 'my first post');
$this->db->insert('Post',$data);
And you can insert into two columns like this:
$data = array('username' => $user, 'description' => 'i am sleepy');
$this->db->insert('User',$data);
Hope my answer can help you.