PHP Mysqli fetch_assoc - php

The MySQLi feature of PHP is great.
Prepared Statements are great for injecting parameters in a query.
However, if you use Statements, it seems you dont have access to the fetch_assoc feature anymore. You have to manually bind all your results. This mean my SQL query has to list all the fields, then I have to list all the variables in advance when getting the results (using bind_result). This can become very annoying and time-wasting.
Is there an alternative?
Thanks

Yes, it's called PDO and is generally preferred to MySQLi. It offers statements with the regular fetch options, and doesn't force you to explicitly bind all parameters. A typical query might look like this:
$stmt = $db->prepare("SELECT * FROM foo WHERE a = ?");
$stmt->execute(array($a));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
PDO is very flexible, so it can be used in other ways as well. There's a lot of great examples in the manual. Take a look!

MySQLi does provide methods for dealing with this, have a look at result_metadata function.
I've written a class to allow hassle-free parameterised MySQLi queries - a download and basic usage info is available here: http://www.robpoyntz.com/blog/?p=191

Related

Which database access aproach is used in CI?

I have heard, (thanks to SO) that mysql_* family of functions is vulnerable to SQL injections, so it is always recommended to use mysqli_* OR PDO approach.
So, I tried to trace out which of these approaches is used in Codeigniter as I have been using CI since 4 months. But I could not get it out.
Can anybody tell me which of these or any other approach is used in CI?
Thanks in advance.
CodeIgniter uses whichever method you choose, based on your config/database.php file. For example, if you choose mysqli as your driver, it will use the mysqli family of functions. If you choose mysql, it will use the mysql family, and so on.
There is a PDO driver, but it's not the most stable thing in the world in the current releases.
If you're using the "active record" functions in CodeIgniter (which should really be called "query builder" functions, since they don't follow the Active Record pattern), then all of your data is automatically sanitized with the appropriate functions. If you say, for example, $this->db->where('field', $value), and you're using the mysqli driver, CodeIgniter will automatically call mysqli_real_escape_string on the $value input you pass to it, rendering the query safe.
I should also note that this automatic sanitization only applies to the active record helper functions, like $this->db->get and the like. If you try to run your own query using $this->db->query("SELECT * FROM table WHERE field = '" . $field . "'") then you need to take care to protect yourself, since you're bypassing CodeIgniter's security mechanisms. Running a query directly with the query() method is like saying "don't worry, I know what I'm doing." You need to specifically ask CodeIgniter to sanitize certain values for you by calling $this->db->escape() or its related functions. If you just concatenate variables into your query, then you're going to open yourself up to SQL injections.

PHP/MySQLI select multiple columns

Hello all,
This query below contains the prepared statement that I would like to have mysqli processed
"SELECT password, salt FROM accounts WHERE username=?"
So far there seems to be no documentation on how fetch_array() works in OO-style with prepared statements. The closest thing I can find is http://php.net/manual/en/mysqli-result.fetch-array.php
Is there a particular "correct" way of doing it with mysqli prepared statements (the OO way)? thanks!
You won't get Objects directly out of the database with prepared statements.
Use fetch http://php.net/manual/en/mysqli-stmt.fetch.php to loop through the results, creating the required class instances and assigning them the data.
A model class will typically have a read method that does this. The method returns a instance, or an array of instances.
(Have a look at symfony models: http://www.symfony-project.org/book/1_0/08-inside-the-model-layer There are so-called peer models that provide static methods "to retrieve records from the tables. Their methods usually return an object or a collection of objects of the related object class".)

Is Propel's fromArray/fromJSON feature safe from SQL injection?

The Propel ORM documentation mentions a neat import/export feature using functions like fromArray and fromJSON, that should allow something like this:
$foo = new Widget();
$foo->fromArray($_POST);
$foo->save(); /* Aaand you're done! */
...but the documentation doens't mention if using fromArray this way is supposed to be safe, i.e. if fromArray can handle untrusted input. My guess would be that it's all right - the default setters are injection-proof, and the whole deal is based on PDO - but I'd like to be sure.
Propel not only uses PDO for the queries, it also utilizes Prepared Statements via PDO, which are pretty good when it comes to mitigating SQL Injection attacks (and performance enhancing).
Note that just using PDO does NOT guarantee any protection against SQL Injection, always use Prepared Statements.
So as an answer to your question, yes, Propel fully utilizes PDO's abilities to protect from SQL Injection.
Propel is safe as Adnan said, but when you decide to use the fromArray() method, never pass the $_POST global variable directly. Otherwise, you open the door to the mass assignment attack.
You always have to check input data, in other words, you should never trust your users.

Escaping Characters from MySQL from PHP Framework

I was wondering if when using the database library in Codeigniter there was a way to automatically escape all the inputs to prevent injection. I know I can use mysql_real_escape_string() to do it, but I wondered it this was already setup to do this automatically, if not are there any frameworks that have this included?
Thanks!
In order to use prepared statements, you can simply use query bindings with CodeIgniter.
$query = 'SELECT id, name FROM user WHERE name = ?';
$bind = array('Jake');
$this->db->query($query, $bind);
More info found here.
CakePHP runs all model queries through its own methods, if you use the model methods it automatically sanitizes any data passed to the query for you. i.e
$options['conditions'] = array('Product.status'=>$status);
$this->Product->find('first',$options);
Right, pretty much all frameworks that implement any sort of database abstraction/ORM layer will automatically mysql_real_espace your queries. If you don't want to use an entire framework, consider a generic ORM library like Propel or Doctrine. Alternatively, look into prepared statements.

Good extension/wrapper for mysqli that returns a associated array for a prepared sql statement

Can anyone recommend a good wrapper class or extension to PHP's mysqli extension that allows the equivalent of
mysql->fetch_assoc()
for a prepared statement. That is ideally it condenses down into a single statement the tedious complexity of the init/prepare/bind/fetch-loop.
try dalmp.com code.dalmp.com currently on beta but maybe you can help to test it
Write a class that extends mysqli and adds that functionality!!!!
Here's a start
http://us.php.net/manual/en/mysqli-stmt.fetch.php#72720
This is PHP 5 class that does just that: http://www.aplweb.co.uk/blog/php/mysqli-wrapper-class/
Just put in your settings and call one of the static functions.
It's actually really easy to write wrappers for or extend PDO.
$this->setAttribute(self::ATTR_STATEMENT_CLASS, array('yourClassName', array($this)));
Something like that will let you specify a class to replace PDOStatement.
Zend_DB is a great wrapper for database functions including mysqli.
It has options to retrieve table data as associative arrays, or as objects if you desire. It also includes support for prepared statements.
You don't have to use the entire zend framework to use Zend_DB, you can use it on its own.

Categories