mysql result fetching comparison using php - php

Which one is better to fetch data from mysql database using PHP and why?
mysql_fetch_row()
mysql_fetch_assoc()
mysql_fetch_array()

mysql_fetch_row()
It returns array with numeric index/key. Usually it is the faster compare with two other methods.
mysql_fetch_assoc()
It returns array with column name as key. It is slightly slower than mysql_fetch_row().
mysql_fetch_array()
It returns returns essentially two arrays. One with an associative based key index and one with a numeric index. mysql_fetch_array() without specifying which method you want (either MYSQL_NUM or MYSQL_ASSOC) always returns a double array. And it is considerably more inefficient as compared to mysql_fetch_row() or mysql_fetch_assoc(). You can set the result type as second parameter.
I think, actually those method has no significant difference.

Actually, each of them has a different method of returning data, so the question is more like "wich one is more suitable for your needs".
mysql_fetch_row() returns arrays like this :
$row[0];
mysql_fetch_assoc() :
$row["table_field"];
mysql_fetch_array() :
$row[0];
// or
$row["table_field"];
The "heaviest" here is perhaps the fetch_array, since it accepts an optional parameter for you to specify if you want your data returned as an associative or numeric-key array.
There's also this one :
mysql_fetch_object() :
$row->table_field;
Personally, I'd use them all according to my needs in every query, but if you work with OOP in php, this last option is perhaps the "niciest".

That depends on how you want to access the row data.
If you want to use numerical indexes, use fetch_row
If you want to use the field name as the index, use fetch_assoc
If you don't need to use the indexes (say, you pass the row through a foreach), or you don't care, using fetch_row should result in a slightly smaller overhead (although this is very minimal). If you don't have a preference, prefer using field names, as this tends to make the code easier to read.
Never use fetch_array, which essentially combines fetch_row and fetch_assoc. Using both numerical and associative is almost certain to make the code less clear. (You may use fetch_array if you supply the $result_type parameter as something other than MYSQL_BOTH, but you might as well use the appropriate function, as your code will be just as clear, but more concise).
Note that if you do want to use the field name, make sure that you don't have two fields with the same name in your query. If you do, you will have to provide an alias for that column in your query (and use that as the field name when accessing the array)

None of them is inherently superior to the other - they are just different. The _assoc() and _row() functions are really just convenience functions for different ways of calling mysql_fetch_array().
From the documentation
Returns an array of strings that
corresponds to the fetched row, or
FALSE if there are no more rows. The
type of returned array depends on how
result_type is defined. By using
MYSQL_BOTH (default), you'll get an
array with both associative and number
indices. Using MYSQL_ASSOC, you only
get associative indices (as
mysql_fetch_assoc() works), using
MYSQL_NUM, you only get number indices
(as mysql_fetch_row() works).

Related

Unserializing PHP array in SQL

One of the former developers in an old system I'm working on used PHP serialize() to flatten one array of data into one column of a MySQL table.
I need to write a complex query that involves this column. Is there a way to unserialize the data (even if it's into a comma separated string) within the SQL query or do I need to pass the results back to PHP?
Serialized PHP data is just a string, so for "simple" searches, you can use basic MySQL string operations.
e.g. The serialized array has a name parameter and you need to match against that, so
... WHERE LOCATE(CONCAT('s:', LENGTH('foo'), ':foo') ,serializeddatafield) > 0
which would produce
WHERE LOCATE('s:3:foo', serializeddata) > 0
But then, this would find ANY strings whose value is foo anywhere in the data, and not necessarily in the particular array field you want.
e.g. you're probably better off yanking out the whole field, deserializing in PHP, and then doing the search there. You could use the above technique to minimize the total number of strings you'd have to yank/parse, however.

Remove duplicate values from PHP array preferring text keys

When I retrieve the results from a database query in PHP, I receive duplicated values, where ones is an integer, and one has the column name. array_unique(), in sorting the array, would in most cases end up with the numeric key before the string, meaning that would be the key kept. Right now, I use a function that removes from the array anything with a numeric key, but I don't really care for this approach. Does anyone have a better way to do this?
Change the command you use to retrieve the values from the database (eg. mysql_fetch_assoc instead of mysql_fetch_array). No matter which api you use now, there is an alternative that does exactly what you want.
update:
In PDO you would write:
$nonumindexes = $res->fetch(PDO::FETCH_ASSOC);
I suspect you're using mysqli_fetch_array() to retrieve the results?
If so, the 2nd parameter allows you to retrieves results as an associative array, numeric array or both. Or you can simply use mysqli_fetch_row or mysqli_fetch_assoc to get the results in the format you want.
http://www.php.net/manual/en/mysqli-result.fetch-array.php

Loop in query function without "while"

Is it possible to show all rows with the properties from my query using only different last function. Something different from fetch_object();?
here is my query:
$dbo_training = $db->query("select * from tabela where id='$tr'")->fetch_object();
which is showing me only one row...
Not sure i completley understand you but if what you want is an array of all the results, the method fetch_object() only returns the first row by definition. try using fetch_assoc() to get an array containing all the results.
I guess you are using mysqli::fetch_object(). If so, you might want to have a look at mysqli::fetch_all which »Fetches all result rows as an associative array, a numeric array, or both« (but apparently not as array of objects…) If you need the objects, you'll probably have to stick to a while loop. (And there is nothing bad about a while loop per se)
I don't know what ORM you are using but with PDO (the PHP standard database accessor) you have to call fetchAll() to do that. If you are using your own library you should have a look to PDO which is very powerful!

PHP Can the order of array elements (as initialized) be counted on as a behavior?

I'm using numeric keys that are part of my data, if I can count on the order as initialized my solution is easier, friendlier to read, and cleaner code!
Probably obvious but: Between array initialization and the foreach() outputting the data no other array functions will be touching the array.
PHP arrays are implemented as hashes. Even for numeric keys, the keys actually exist and values are associated with them, unlike lists or sets in other languages. You can count on the order to never change on its own, because that would mean actually changing the values associated with the (numeric) keys.
You can count on it. PHP only changes the order after a sort() or similar function call.
You could have found out by var_dump()ing the array yourself, by the way.
If you are asking if:
array("a","b","c")
will always put a into key 1, b into key 2, and c into key 3, then yes, it can be counted on (hence the name array).

mysql fetch assoc VS mysql fetch array

Below are two methods commonly used in most php codes for fetch mysql data .
mysql_fetch_array()
mysql_fetch_assoc()
Now, I have a big database. For fetching data in loops (while) what's faster and better ?
I found this benchmark.
Which is your choice?
It depends on how your tables are setup:
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.
So using mysql_fetch_array() without specifying MYSQL_ASSOC or MYSQL_NUM, or by specifying MYSQL_BOTH will return two arrays (basically what mysql_fetch_assoc() and mysql_fetch_row() would return) so mysql_fetch_assoc() is faster.
If you have your table setup right and query written properly mysql_fetch_assoc() is the way to go, code readability wise $result['username'] is easier to understand than $result[0].
This Is the result of
mysql_fetch_array()
$row['fieldname'] = 'some value';
or
$row[0] = some value';
This Is the result of mysql_fetch_assoc() will only return
$row['fieldname'] = 'some value';
I prefer fetch_assoc. It returns an "associative array" (like a python dictionary). This means your array is indexed by string (in my usual case).
The default for fetch_array gives both numbered indices and associative indices.
But I never use the numbered indices, so I like to get it a tiny bit faster with fetch_assoc
The benchark shown in your example uses mysql_fetch_array() without any argument to specify MYSQL_ASSOC or MYSQL_NUM, so it defaults to MYSQL_BOTH... this will rather skew the result as it has to load twice as many array elements as mysql_fetch_assoc(). So I'd suggest it isn't a valid benchmark.
In reality, there should be very little to differentiate between mysql_fetch_array() with MYSQL_ASSOC and mysql_fetch_assoc(), and it cerayinly won't be the biggest overhead in your script.
The "size" of the query results don't matter in this case.
mysql_fetch_array() generally produces overhead by returning an associative array plus indexed results.
One should decide on the type of query and the desired results on whether to use mysql_fetch_array() or mysql_fetch_assoc().
If the overhead is "neglectable" and I'm sure the query succeeds and I know there's only a single result, I occasionally do:
$q = mysql_query('SELECT `column1`,`column2` FROM `table` WHERE `id` = 123');
list($column1,$column2) = mysql_fetch_array($q);
mysql_free_result($q);
For iterative proceedings (like a while loop), this just doesn't cut it. When there's no need for "quick-extracting" results (via a list operator) and the result has to be further processed in code, I always use mysql_fetch_assoc()*.
* When forced to actually use the quite out-dated procedural data retrieval functions of PHP. There are alternatives.
mysql_fetch_assoc() would probably be the better choice. There is a slight performance hit (the mysql extension needs to look up the column names, but that should only happen once, no matter how many rows you have), but probably not enough to justify using mysql_fetch_array() instead. mysql_fetch_array() can be useful if you're only selecting one column though.
I suppose it depends on your definition of big. From that benchmark you can see that it is only before you perform upwards of 1,000,000 million fetches that you actually get a measurable difference? Is your database that big? If not, then go with what is easier for you to use (which is probably to fetch an associative array).
Another point to consider, if it is so big that there is a measurable difference then I would be getting a way from using functions like that all together. Consider using MySQLi or even better use PDO!
Well http://php.net/manual/en/function.mysql-fetch-assoc.php states
Note: Performance
An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.
So the difference shouldn't be something to worry about.
An additional point to keep in mind is that fetch_assoc() may not return every column you expect. If 2 output columns would have the same name, only the last instance of that column will be retrieved by fetch_assoc(). For example, the following query:
SELECT * FROM orders LEFT JOIN line_items ON orders.id = line_items.order_id
Assuming both tables have a column called id, the resulting associative array would have a key called id whose value is set to line_items.id and you would not be able to retrieve orders.id from the result!
You can circumvent this duplicate column names issue and continue to use fetch_assoc() by manually aliasing your SELECT columns, giving each column a unique alias:
SELECT
o.id AS order_id, #unique alias
i.id AS line_item_id, #unique alias
o.date,
i.qty,
i.price
FROM orders o
LEFT JOIN line_items i ON i.order_id = o.id
Or you can switch to using fetch_array(), which will allow you to access either id by index instead of by key
mysql_fetch_array() vs mysql_fetch_assoc()
mysql_fetch_array(): Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
for better documentation click here! to learn more
mysql_fetch_assoc(): is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

Categories