I've written the code below:
$release_id = intval(filter_var($_GET["rid"],FILTER_SANITIZE_STRING));
$query = "select * from press_releases where id = {$release_id}";
$result = $db->query($query);
$row = $result->fetch_assoc();
list($id, $short_description, $description, $created_date) = $row;
$db->close();
and I am using the variables such as $description, $short_description inside of the html tags but nothing shows. If I use the code below which is same except for the list() function:
$release_id = intval(filter_var($_GET["rid"],FILTER_SANITIZE_STRING));
$query = "select * from press_releases where id = {$release_id}";
$result = $db->query($query);
$row = $result->fetch_assoc();
$id = $row["id"];
$short_description = $row["short_description"];
$description = stripslashes(html_entity_decode($row["description"]));
$created_date = $row["created_date"];
$db->close();
it works perfectly. Basically list() function cannot assign the values coming from the $row array.
I don't understand why?
According to the PHP docs for list():
list() only works on numerical arrays
and assumes the numerical indices
start at 0.
I don't believe the list() function works with associative arrays. Try fetching your query results normally (numerical indices) and see if that resolves the issue for you.
You want to use extract() instead of list().
This is the one that's appropriate for associative results. And you shouldn't use it with SELECT * but a concrete list of SELECT varname1,varname2,varname3 so you don't get unexpected local variables.
It's also possible to use extract(array_intersect_key(..)) to get a filtered list of variables to be extracted, but that's overkill for database result sets that you can control anyway.
A rather easy solution to this is as follows:
list($id, $short_description, $description, $created_date) = array_values($row);
Or simply don't fetch as assoc, but as a normal array.
I must say I don't really recommend doing this. Since your SQL query is fetching with *, it will break very easily - Let's say for whatever reason one of the columns gets shuffled around so it appears at some other position in the table. Bam.
Assuming you were to define each column separately in your query, then it would be fine.
My guess is that list() expects a numerically indexed array. Try using
$row = $result->fetch_row(); instead
list() expects an indexed array, not an associative one. Try using fetch_row().
Use array_values like this:
list($id, $short_description, $description, $created_date) = array_values($row);
Read the comment by kevin in here on php.net.
list does only work with numerically indexed arrays. Switch fetch_assoc to fetch_row or use array_values on $row before the assignment:
$row = $result->fetch_row();
or
list($id, $short_description, $description, $created_date) = array_values($row);
Use fetch_row rather than fetch_assoc, see the example. AssociativeHash arrays have no well-defined element order!
Related
This is how I get one record with MySQLi:
$result = $db->query("...");
$image = $result->fetch_object();
Now I need to get the comments and pass it to the view. I'm using the following snippet right now, but it doesn't seem right:
$result = $db->query("...");
while ($row = $result->fetch_object())
$comments[] = $row;
I'm wondering if there's a way to remove the loop?
Is there something like:
$image = $result->fetch_object(((s)))
So then my code would look like:
$result = $db->query("...");
$comments = $result->fetch_objects();
The mysqli_result class provides a fetch_all method to collect the full result set. However, that method will only return associative or numeric arrays (or a hybrid), not objects.
It's not possible to get an array of objects using mysqli_fetch_all(). The available options are: indexed array, associative array, or both.
Consider using the PHP Data Objects (PDO) interface, which has many more fetch modes and is thus superior to MySQLi in that regard.
Without seeing your SQL, it's tough to say. There may be a better query you could use. Post your SQL and I'll take another look.
In terms of your SQL query, if your query returns multiple rows, then you have already fetched them with one db call.
I don't see a way to collect into an array all of the comments, but you can clean up your code with a custom function.
function get_all_rows_as_array(&$result)
{
foreach($result as mysql_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
$result = $db->query("...");
$comments = get_all_rows_as_array($result);
I try to retrieve a array from one table What is wrong with this code?
$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1' ");
$fbexcludearray= mysql_fetch_array($_fbexclude);
// Convert the array
$excludes = implode(',', $fbexcludearray);
From echo $excludes; It only gives me just the following response: 1000033xxx161,1000033xxx161 Twice the same fbempfang
See if the following gives you what you want (FIXED):
$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1'");
$fbexcludearray = array();
while ($row = mysql_fetch_assoc($_fbexclude)) {
$fbexcludearray[] = $row['fbempfang'];
}
// Convert the array
$excludes = implode(',', $fbexcludearray);
mysql_fetch_array() and it's siblings (_assoc, _row) only retrieve one row at a time. This means that your original code will only give you the first returned row - to work around this, we use the loop you see above.
The reason you see the same data twice is because mysql_fetch_array() returns a mixed indexed and associative array, which contains all the data twice over. For this reason, it is much better to use mysql_fetch_assoc() or mysql_fetch_row(), as you rarely need both formats.
In fact, it is much better to use mysqli, but the same information applies to that as well.
Use right SQL query:
SELECT GROUP_CONCAT(`fbempfang`) as imploded from `fbinvite` WHERE fbreturn = '1'
It's return string as PHP implode(',', array(…));
Try this on for size:
$implode_arr = array();
$_fbexclude = mysql_query("SELECT fbempfang
FROM fbinvite
WHERE fbreturn = '1'");
while($row = mysql_fetch_array($_fbexclude)) {
$implode_arr[] = $row['fbempfang'];
}
// Convert the array
$excludes = implode(',', $implode_arr);
You need to loop over the mysql_fetch_* functions because they only return one of the result rows at a time. For more information and examples see the manual page for mysql_fetch_assoc().
I'm selecting a single column from a MySQL table with mysql_query(). Is there already a function for getting the results into an array, or will I have to iterate through all the results with something like mysql_fetch_array()?
You have to iterate.
If you moved into the 21st century, and used mysqli, there's a mysqli_fetch_all() function.... and you'd be able to use prepared statements
you can do this with mysqli_fetch_all and array_column
$r = mysqli_query($c,"SELECT bug_name FROM bugs WHERE color='red'");
$bug_names = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"bug_name");
Nothing like that built in, you will need to do this manually.
you can use mysql_result function still need to do some coding
mysql_result($result,$row_num,$fieldname) ;
retrieves $row_num 'th columes $field_name field .
and following snippet can be taken as an example
$con =mysql_connect($host,$uname,$passwd);
mysql_select_db($dbname,$con);
$result = mysql_query($query,$con);
$arr = array();
$numrows = mysql_num_rows($result);
for($i=0;$i<$numrows;$i++) {
$arr[] = mysql_result($result,$i,$fieldname);
}
this stores every elements of column $fieldname to
array $arr
i've just changed from ASP to php and i'm a bit confused about the way php is handling recordsets.
i'd like to know if there's an easier way to iterate a recordset by creating a php class.
here's the ASP syntax to show what i mean:
sq = "select * from myData"
set rs = db.execute(sq)
do while not rs.eof
response.write rs("name") // output data (response.write = echo)
rs.movenext
loop
any ideas?
thanks
You'd pretty much do the same thing...
$sql = "select * from myData";
$result = mysql_query($sql) or die(mysql_error()); //executes query
while($row = mysql_fetch_array($result)){ //will automatically return false when out of records
echo $row['name'];
}
You're probably looking for a function contains word fetch in it's name.
E.g. mysql_fetch_assoc() or $pdo->fetchAll().
Most of database API functions in PHP returns some sort of pointer variable called "resource", which can be passed to the fetch-family function, like this:
$res = mysql_query();
while($row = mysql_fetch_assoc($res)){
echo $row['name'];
}
However, some of them (like PDO's fetchAll method) returns but regular PHP array, which you can iterate using as regular foreach operator.
Is there a PHP function to get the full result with a mysql query in a multidimensional array?
SELECT * FROM table
Usually I would make something like this:
$query = mysql_query = ("SELECT * FROM table");
while ($result = mysql_fetch_array($query){
echo $result[0];
}
You can create your own function like mysql_fetch_array_complete() and imagine that it's builtin ;-)
If you are using PDO to access mysql there is.
http://www.php.net/manual/en/pdostatement.fetchall.php
Otherwise you need to do it yourself.
$query = mysql_query = ("SELECT * FROM table");
$all_results = array();
while ($result = mysql_fetch_array($query){
$all_results[] = $result;
}
print_r($all_results);
The $all_results variable will be a multi-dimensional array with all the records.
You could always write your own function to do this, but it would often lead to an unnecessary iteration through the result set (once when you call your function, another time when you actually USE the resulting array).
Since you're in php5, you could create a database result class that implements the Iterator interface. Then, you can use your class in foreach () loops and have much of the ease-of-use that you get from an array.
As of PHP 5.3 there is a built in function:
fetch_all