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.
Related
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
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!
I have a mysql statement which grabs just one record based on an id. I want to know if using mysql_fetch_row or something along the lines of that is better then using something such as mysql_fetch_array, for just grabbing one row in a database.
It may seem like common sense to go with the mysql_fetch_row but I just want to make sure.
An important thing to note is that
using mysql_fetch_array() is not
significantly slower than using
mysql_fetch_row(), while it provides a
significant added value.
Source
why don't you just use LIMIT 1 inside the mysql statement and no matter what you will have one row.
The two functions are almost identical, the name is just making you think it's different:
$r=mysql_query('SELECT name,email FROM tbl LIMIT 1');
var_dump(mysql_fetch_assoc($r));
// array('name'=>[dbName], 'email'=>[dbEmail]);
var_dump(mysql_fetch_row($r));
// array([dbName], [dbEmail]);
// It's a normal incremental integer index array
var_dump(mysql_fetch_array($r,MYSQL_ASSOC));
// same as mysql_fetch_assoc();
var_dump(mysql_fetch_array($r,MYSQL_NUM));
// same as mysql_fetch_row();
var_dump(mysql_fetch_array($r,MYSQL_BOTH));
// array(0=>[dbName], 1=>[dbEmail], 'name'=>[dbName], 'email'=>[dbEmail]);
The manual also suggests performance wise the two functions fared well. Local tests hint in the same direction. I'd suggest you not worry about the .0001 time/memory saved and find true bottlenecks in your applications.
I am trying to find out which is the proper way to fetch data from my database. Either way works, but what's the difference; an in-depth explanation?
$sql = mysql_query("SELECT * FROM _$setprofile");
while($row = mysql_fetch_array($sql)) {
$username = $row['user'];
$password = $row['pass'];
echo "$username:$password";
}
versus the function below...
$sql = mysql_query("SELECT user,pass FROM _$setprofile");
while($row = mysql_fetch_row($sql)) {
echo "$row[0]:$row[1]";
}
This is something I've always wanted to know.
The difference is you're re-assigning the variables in the first example. But you could just say:
while(list($username, $password) = mysql_fetch_array($sql)) {
echo "$username:$password";
}
Or you could pull out a hash
while($row = mysql_fetch_assoc($sql)) {
echo "{$row['username']}:{$row['password']}";
}
The right way depends on the application or your preference, I personally avoid the numeric indexed arrays unless I specifically need them. Who wants to try to keep a mental tab of what data is in which index?
The difference is that fetch_array extracts an array containing BOTH numerical and associative indexes (unless you provide an extra option to tell it otherwise), while fetch_row only gets numerical indexes and fetch_assoc only gets associative indexes. Usually, you don't want both.
Use fetch_assoc instead of fetch_array - that ONLY gets you an array with associative indexes. That means it'll run a bit faster (it has to do less work), but the code will be just as clear.
From a functional perspective, the difference is minimal. However, the former has the problem that you're fetching more from the database than you need (SELECT *). It's generally recommended not to select more than you actually need.
There's no much difference internally. Both ordinal positions and column names are available in the result set metadata within the MySQL client API, regardless.
Regarding usage, both can be handy in different circumstances. Referencing columns by name is more mnemonic, results in (semi-) self-documenting code, allows you to change the position or number of columns in the query without breaking your code, etc.
But fetching by ordinal is hand too sometimes. For example:
SELECT u.name, d.name FROM user u JOIN department d USING (dept_id)
Now you have two columns with the same name in the result set. If you fetch an associative array, one overwrites the other because an assoc array can only have one value per key. So $row["name"] is one of the names, and you don't necessarily know which it's going to be.
SELECT d.name, COUNT(*) FROM user u JOIN department d USING (dept_id) GROUP BY dept_id
Now you have a column that has no alias, and depending on the RDBMS brand you use, it could invent a funny-looking alias automatically, or else just use the whole expression as the key for the assoc array. So it's nice to be able to use ordinal position instead of column name in this case.
(It's funny how my writing style becomes more informal and chatty when I'm listening to the StackOverflow podcast while I'm writing.)
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).