I am editing somebody else's code and I am a PHP beginner.
I want to access the contents of a column called "email" in the database "tga_purchase_items" where the "id" of the row is "14". I want to save the output to a variable "$sp_email".
The code I have is thus:
$sp_email = $this->db->select("email")->from("tga_purchase_items")->where("id", 14)->get();
The variable is coming out empty although the database field is definitely populated.
What am I doing wrong? I am not used to this "->" syntax at all.
The syntax used in your database leans towards Codeigniter and active record.
If this is the case, the following code will retrieve the email column.
$result_set = $this->db->select("email")->from("tga_purchase_items")->where("id", 14)->get();
$result_object = $result_set->row();
$sp_email = $result_object->email;
What you're missing is retrieving the data from the result set which you get. The get() functions return a result set which is similar to the native MySQLi Result class. This means that you need to retrieve the data you want from this set. There are various functions available in CodeIgniter to do this, namely row(), row_array(), result() and result_array() which you can read about on their manual page.
I haven't done too much with CodeIgniter and the Active Record (I prefer Zend Framework) but I think something like this would do the trick:
$this->db->select('email');
$sp_email = $this->db->get_where('tga_purchase_items', array('id' => '14'));
Look at this for a more detailed explanation: http://codeigniter.com/user_guide/database/active_record.html
Related
So, I have the following code:
$homepage = Homepage::first();
if (!$homepage) {
$homepage = new Homepage;
}
$homepage->first_presta_title = $request->first_presta_title;
$homepage->first_presta_content = $request->first_presta_content;
$homepage->second_presta_title = $request->second_presta_title;
$homepage->second_presta_content = $request->second_presta_content;
$homepage->third_presta_title = $request->third_presta_title;
$homepage->third_presta_content = $request->third_presta_content;
$homepage->shiatsu_text = $request->shiatsu_text;
$homepage->shiatsu_image = $request->shiatsu_image;
$homepage->doin_text = $request->doin_text;
$homepage->doin_image = $request->doin_image;
$homepage->save();
Everything works, but I wanted to see if there weren't any better way to save datas without asigning every single element to its column, then I found out someone answering to a question by using the following code:
$homepage->save($request->all());
So I tried it by myself, but nothing happened: no error, but also nothing saved in my database.
So, is there any fastest way to save datas ? Is it possible to use a loop to save everything?
Thank you in advance
When you use save(), you are actually using Mass assignment. So, either you explicitly define all the fields in your model to be mass assignable or you could use create() instead.
However, in your particular case, the whole method could be cleaned up to just one line:
return Homepage::updateOrCreate($request->all());
If you want the model to autofill based on a given array you need to create a new model entity Like this
$homepage = HomePage::create($request->all());
$homepage->save()
If you give an array to save() it expects the options for saving not for values to assign
Source:
laravel api docs for model/save()
laravel api docs for model::create()
What is the easiest way to retrieve the value of a single field from a MySQL database using Fat-Free Framework? I have been able to do it with the following code which returns an array but am wondering how to improve this:
$result = $db->exec('SELECT id FROM admins WHERE username = ?',$f3->get('POST.username'));
This query returns the id field that we are seeking in an array which is accessible via $result[0]['id'] - can we avoid assigning this to an array and read it directly to a string variable?
Depending on which version of PHP you're using you could possibly do this..
$result = $db->exec('SELECT id FROM admins WHERE username = ?',$f3->get('POST.username'))[0]['id'];
or if you were using pure PDO you could use fetchColumn(), but you're using a framework. The only way to change the returned value is to edit the framework code.
I realise this is an old question but I ran into the same problem recently and came up with the findone() function. I wanted to share it as it had not been mentioned before in case anyone else is looking for a solution.
$f3=\Base::instance();
$f3->set('DB',new DB\SQL('sqlite:db/database.sqlite'));
$admins = new \DB\SQL\Mapper($f3->get('DB'), 'admins');
$username = $admins->findone(['username = ?', $f3->get('POST.username')])->username;
Line 1-3 are just preliminaries. You'll need a table mapper to use this function. Line 4 is a one-liner which will set the $username to hold the actual value of the username.
You should use Cursor/Mapper.
Something Like:
\Base::instance()->set('DB',new DB\SQL('sqlite:db/database.sqlite'));
$admins_mapper = new \DB\SQL\Mapper(\Base::instance()->get('DB'), 'admins');
$admin = $admin_mapper->load(array('username = ?', \Base::instance()->get('POST.username'));
You can also use Cortex which is build on top of Cursor.
I want to save results to cache but datamapper result objects is huge array.
I want to get only my query results without other data that referenced codeigniter data (models/configs/languages/etc..)
How can do this?
I searched on SO, internet and manual page (http://datamapper.wanwizard.eu/) but i couldnt find anything..
If you just want to access the core information about your records, try using the array extension here: http://datamapper.wanwizard.eu/pages/extensions/array.html
This allows you to run something like:
$objects-> all_to_array();
... which returns an array of objects, with all properties, but without the models/configs/languages &c. that you mention.
I want to addition some tips on #sevenpointsix answer
If you are using include_related, you have to specify columns like following (relation_column):
$fields = array('id', 'title', 'user_firstname', 'user_lastname', 'category_name');
$posts->get()->all_to_array($fields);
hii..I want to edit single row.i used
$this->data = $this->BuildingProperty->read(null,$id);
but it didnt fetch the values of this id.
so what can i do. Give me any suggestion.
Why did you pass null as the first parameter? It should be a string on array of fields that you want to retrieve.
Anyway, try this instead:
$this->BuildingProperty->id = $id;
$this->data = $this->BuildingProperty->read();
The syntax which you are using is correct. First check if the $id is integer. (echo $id). Then if so, check your database if it has such record in building_properties table check if this ID exist. Finally check if the variable $this->data is populated with the proper values.
All those checks return you proper values then the problem is not in Model->read() function.
Another hint, try to clear the cache /app/tmp/cache/modules and /app/tmp/cache/persistent
Are you calling the method from a controller that knows about BuildingProperty? i.e. BuildingPropertiesController. If not, have you included a
var $uses = array('BuildingProperty');
statement in the class definition or explicitly loaded the model with, for example,
loadModel('BuildingProperty')
Your syntax is correct and the only other explanation if there is no warning or error message is that the returned array is empty, i.e. the record does not exist.
Check that you have debug turned on:
Configure::write('debug', 1); // or higher.A 2 will output SQL queries as well
then try
debug($this->BuildingProperty->read(null,$id));
You should at least get some output telling you the line of the debug call.
The thing is that you have classes and then you have the database data. When you create an object how do you set the objects properties to contain the data in the database ?
I saw something like this and I'm wondering if this is really the best way to do it. I'm sure this is a fairly common issue, but I don't know what are the most accepted solutions on how to handle it.
In this example when the object is created you pass an id as a parameter and then you run a query to the database with the id and you assing the returned values to the object properties. I don't have much PHP experience and haven't seen this used much.
Is this an acceptable way to achieve this purpose ? Is there a better or more accepted way ?
public function __construct($id = null){
if($id != null){
$sql = "SELECT *
FROM users
WHERE user_id = $id";
$res = Db::returnRow($sql);
// $res contains an associative array with database columns and values
if($res){
$this->user_id = $res['user_id'];
$this->user_name = $res['user_name'];
//and so on...
}
}
}
Could somebody provide some sample code or pseudocode to illustrate what is the correct way to do this ?
It could be an acceptable way for a homework maybe. But architecturaly it is not.
Your class that is representing your business data (a user in your example) must be loosely coupled with your database access logic. In the end the PHP class acting as a user should not be aware that the data come from a database, a file or any other resource. Following that you will be able to reuse your user php class in other projects without having to change anything to it! If you have your data access logic inside it you are stuck.
Conclusion: I would suggest to read some resources on Design Pattern (in your situation take a look at DAO pattern) ;) Hint: the one from Head First series is extremely accessible and enjoyable.
You could create a function to do this for you automatically, by looping over the associative array's key/value pairs. Or you could look into using an ORM library.
Yes, you can semi-automate this by having a parent class all objects inherit from. On load, it queries, "SHOW FIELDS FROM [my tablename]" and populates an associative array with the names. If an id has been passed in, it looks for a valid object in that table with that id and assigns the values to the array.
Side note: don't pass your id directly into your query like that. Parametize the sql and wrap a function around any user input to sanitize it.
If it's mysql, you can just do:
$obj = mysql_fetch_object($query);
PDO the ability to use arbitrary classes as the target for a fetch, but beware that they assign the variable data before running the constructor:
$pdo->query($stmt, PDO::FETCH_CLASS, "MyClass", array('foo'=>'bar'));
...where the final parameter contains arguments for your class constructor.