I have recently started using codeigniter and I am a bit stuck as it is all rather new to me.
I use to have a config file with database conection and this on it:
$qset = "select * from re_settings";
$rset = mysql_query($qset) or die(mysql_error());
$aset = mysql_fetch_array($rset);
and this would allow me to pull words from database by simply putting this on the site
<?=$aset['SiteTitle']?>
How can I do this in codeigniter? Do I need to have a controller to do this or is it something much simpler than that.
You'll need to become familiar with the concepts of MCV which is how Codeigniter is built on and your ORM framework.
There's a bunch of helpful resources on http://tutorialcodeigniter.com/ or the official docs http://ellislab.com/codeigniter/user-guide/database/examples.html
as an example
$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['email'];
}
I strongly recommend to use Datamapper along with CodeIgniter.
You will be surprised on how it is easy to work with your MySQL database.
Say goodbye to "mysql_fetch_array" 's and such.
Have a look : http://datamapper.wanwizard.eu/pages/getadvanced.html
Related
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 make a list of Best selling prints in my store.
I have a table (print_for_sale) which has fk_sale_id and fk_print_id where I can see how many prints have been bought.
I came up with this code to print out an organized list, from most bought to least (not sure it is entirely correct):
<?php
$sql = "SELECT fk_print_id as printId, COUNT(print_for_sale_id) as saleCount
FROM print_for_sale
GROUP BY fk_print_id
ORDER BY saleCount DESC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['printId']; echo $row['saleCount']; }
?>
I'm trying to make a transition of this to my model, controller and view (mvc) but I'm having a lot of trouble. I'm new to this and I've tried in so many different ways, none of which seem to work. I'm lost. Right now I have it like this (and it prints out nothing) or the only thing it prints out is "Notice undefined variable arr" when I make an echo in my view
model.php
function getBestSelling() {
$sql = "SELECT fk_print_id as printId, COUNT(print_for_sale_id) as saleCount
FROM print_for_sale
GROUP BY fk_print_id
ORDER BY saleCount DESC";
$result = $this->conn->query($sql);
return $this->buildArr($result);
}
controller.php
function bestselling() {
$arr = $this->model->getBestSelling();
print_r($arr);
include 'view.php';
}
view.php
<?php echo $arr['printId'] ?>
I want to print out the result of the query but nothing is working. I'm sorry if this isn't an appropriate question but I could really use some help understanding this.
I'm not using any framework.
In my model I do have a class model { }, a function __construct() and a function __destruct(). I also have a function to build the arrays.
function buildArr($result) {
$arr = array();
while ($row = $result->fetch_assoc()) {
array_push($arr, $row);
}
return $arr;
}
In my controller I include 'model.php'; and have a class Controller {} and function __construct() { $this->model = new model();}.
I also have a index.php where I start the session and define("BASE_URL", 'http://' . $_SERVER['SERVER_NAME'] . '/printstore/index.php/');
The app is working. I can already register users, login and make purchases. I just can't seem to get this part of the code right.
Would appreciate some help! Sorry for the long post and thank you in advance.
The included file is not behaving as you expect it to. To pull this off you will have to create a global out of the variable (but don't do it!). You can print_r() the array in the controller, because you're fetching it from the model. But after that you include the view. When you place that array in an included file, without defining it in the file itself, you're not going to get a result because only the including file has access to any defined variables. Not the other way around.
So if you want this to work you're going to either have to make the variable $arr global (not recommended), or include the controller in view.php. (Note that this is not MVC!) If you want this to be MVC you'll have to use classes for the controllers and use those objects in the view. To find a better explanation for this please refer to the links down below.
I am personally fond of using of a templating engines (also not MVC related). I'm quite fond of Smarty, but I've heard good stories about mustache too.
These templating engines provide you with a way to pass variables to your templates, without including the controller file. For example in Smarty:
PHP:
$variable = 'Hello World!';
$smarty->assign('variable', $variable);
$smarty->display('helloworld.tpl');
Smarty, helloworld.tpl:
{$variable}
Output:
Hello World!
I'd also recommend you to read these, they might help you out more than I've been able to explain.
Setting up MVC in PHP: http://www.sitepoint.com/the-mvc-pattern-and-php-1/
Including files in PHP: Passing a variable from one php include file to another: global vs. not
Edit
Teresko is right that you should not be using globals. I just specified them here, because it's possible to use them (definitely not recommended).
Read this question for a couple of why's: Stop using `global` in PHP
I'm working to create a function that call a field in joomla database.
Is that a good usage to prevent sql injection?
// Get std objects
if (strlen($urlparams)<5) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('params');
$query->from($db->quoteName('#__template_styles'));
$query->where($db->quoteName('id')." = ".$db->quote($urlparams));
$db->setQuery($query);
$row = $db->loadResult();
}
else {
echo 'Something is going worng.';
}
Thank you and best regards.
You current method is perfectly fine as it uses the most up to date Joomla coding standards.
The only thing I would do it use quoteName() in your select clause which is used to escape field names. So you would end up with the following:
$query->select($db->quoteName('params'));
If you are ever in doubt, have a look at Joomla's:
Secure Coding Guidelines and
Documentation for Accessing the Database
I'm making a school project on which I have to create a web app based on a Oracle database, and after testing some php frameworks I'm currently using CodeIgniter. I'm pretty new to the MVC and php, so excuse me if I make any mistake..
I understand that (beeing a MVC framework), on my Model, it's possible to run queries like
$query = $this->db->query("SELECT * FROM tablename");
But on my studies I read that it's good practice to, everytime we want to run a query/insert/etc, we should open a connection and end it after making the operation. I believe that's supposed to prevent 'inconsistencies'..Something like
<?php
$conn = oci_connect('user', 'pass', 'dbname');
$query = 'select * from tablename';
$stid = oci_parse($conn, $query);
oci_execute($stid, OCI_DEFAULT);
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
foreach ($row as $item) {
echo $item." | ";
}
echo "
\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Is that so? If it is, then the that command I'm making on my Model is correct or not?
I can only think of running this php script on a view.php file but by doing so I guess I'm not implementing the MVC 'concept', just calling this kind of php script...right?
I'm getting the results with the two method, but im not sure which's the best way to do it..
Thanks in advance!
You don't have do such loads of work. It's MVC. Mode-View-Controller . Everthing is all done and managed. You have to provide the connection details in database.php file kept in config folder. And ci will automatically make a connection with database.
And call these all queries in model. Make a function in model for your requirement and call it in controller. And, hence you can get your result in controller and pass it to the view.
Since you are using the Codeigniter MVC framework then adding your own database routine would definitively be an overkill and not good practise. CI has a well developed and secure DB library and using CI Active record syntax greatly simplifies db queries. So look into this and learn the great benefits of a thought trough framework.
http://ellislab.com/codeigniter/user-guide/database/active_record.html
I have some legacy DB with many tables (around 100) the old system is run using php and have so many operation with data used in NLP.
I was a bit curious how thing could be done with Rails. I read that ActiveRecord is no good for legacy systems! but I sow some people used it with no problems, So why some clime that?
Also considering the following php code, with many If & SQL statements, some clime that such case is considered as typical data/database task not OO one, so it's better to stay away from AcriveRecord or any other ORM. Is this true? if not, can it be done easily by Rails's ActiveRecord?
Assuming all variables are submitted from a web form. we have some text to be annotate and we have to see if there're any other users that agree with this user who submitted the form. Then we'll update the agree table.
if ($submitted_id !=""){
$sql = "SELECT * FROM annotation WHERE relation_id = $relation_id";
$result = open_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$user_id = $row["user_id"];
$line = "";
$sql = "SELECT * FROM agree WHERE user_id = $user_id AND user_id_agree = $submitted_id LIMIT 1";
$result = open_query($sql);
$line = mysql_fetch_array($result, MYSQL_ASSOC);
if ( $user_id != $submitted_id ) {
if ( $line == "" ) {
mysql_query ("INSERT INTO agree VALUES ('$user_id' , '$submitted_id', '1', CURRENT_TIMESTAMP)");
} else {
$total = $line["total"];
$new_total = $total+1;
mysql_query ("UPDATE agree SET total = $new_total WHERE user_id = $user_id AND user_id_agree = $submitted_id LIMIT 1");
}
}
}
}
Regards
Well, using legacy database schemas with ActiveRecord makes you lose some of its advantages. For instance, Rails takes a "convention over configuration" approach to many things, and ActiveRecord inherits this. For instance, if you have a model called Product, Rails assumes your table will be called "products". For this reason, you don't have to configure the table name. The same holds through for foreign keys, URL conventions, etc. The more you are willing to make your application work the way Rails works, the easier a time you will have. If your goal going in is not "build an application that does X", but rather "convert this application to Ruby and ActiveRecord", the resulting code will not be as clear or idiomatic.
If you try to write an application in the way that is conventional for the tool you are using, you will likely get clearer, more maintainable code as a result.
As for the code you provided, it's not entirely clear to me what it is supposed to do (since I do not have the context to know what "submitted_it", "user_id_agree", "annotation", and so on mean in your application.