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
Related
I'm using PHP but that's not important. I have a variable that contains a standard array of positive int IDs. And I want to do a SELECT query with this array against a MySQL table to find out what IDs are not already existing in the data table. My first thought was to use IN() but then I realized that doing it that way I can only get a list of IDs that do exist not ones that don't. Of course with a list of IDs that do exist, I could compile it into a second array and then use array_diff() but I can't help wondering if there's another way to do it.
I decided to use unset()
SELECT QUERY
where (row) {
unset(id)
}
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'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).
One of my fields in my data base is an array which has been converted to a string using the implode() function.
How do I retrieve the contents of this field (LESSONS) from the database and store it to a string when a user entered value is equal to the the value of the field NAME?
Thanks in advance for any help you may be able to provide.
Here you go:
$r = mysql_query('SELECT LESSONS FROM TABLE WHERE NAME=\'user_string\'');
$rows = mysql_fetch_assoc($r);
echo $rows['LESSONS'];
I don't know if I understood your question but... Take a look about Stored Procedures
If you used the implode function to convert your array into a string, then this data has lost any information about the array keys.
As far as you want to convert the data back, use the explode function:
$array = explode(',', $columnData);
But You can therefore not search for array keys within the database.
Next to that, the MySQL database (I assume you're using MySQL) can not search for array keys anyway.
You need to store the data in some other way into the mysql to search for it in an SQL later on.
For example, you can create a table that stores key/value combinations with a grouping index.
However MySQL has some string functions that can help you searching within the (now) string data in the MySQL database.
When searching for a value, before the comparison add a comma at the beginning and one at the end of the string. There is a MySQL string function that can concatenate strings. Then search within that expression for your value with a comma added in front and back as well.
Then you can lookop a single array element within the mysql database. MySQL String Functions.
This is a quick solution only, this won't work on large databases performant. However it might solve your problem w/o changing your database structure.
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).