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
Related
I am having a problem.
I know I am using deprecated MySQL, but I am working on a website for school and security is not necessary(as long as it works). I am trying to get all the Id's from a table called Reviews. This should be stored in a array. For some reason it only shows the first one. How to get all of them stored in 1 array? This is my code which is not working:
$sql1 = "SELECT Klanten_id FROM Reviews";
$res1 = mysql_query($sql1);
$r = mysql_fetch_assoc($res1)['Klanten_id'];
1.Don't use outdated mysql_* library.Turn to mysqli_* or PDO.
2.mysql_fetch_assoc: Fetch a result row as an associative array. So you need to apply loop to get all data
Like below:-
$ids = array(); //created an array
while ($row = mysql_fetch_assoc($res1)) {
$ids[] = $row['Klanten_id']; // assign each id to the array
}
print_r($ids);// print array
3.To start working on mysqli/PDO check basic example here:- mysqli/PDO example
I'm working on a piece of code that's meant to be implemented in Google Charts, however, not all values I'm looking for are being returned.
I need a couple of dates selected from my database, and I select them as follows:
$dates = mysql_fetch_row(mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'")) or die(mysql_error());
Then I use a for-loop to echo them:
for ($i = 0; $i <= count($dates); $i++)
{
echo $dates[0].' ';
}
In my database there are 3 (distinct) dates: 24-03-2013, 25-03-2013 and 26-03-2013, however the piece of code returns 2x 24-03-2013. What am I doing wrong here?
P.S. I also tried a while-loop but that loops infinitely or crashes my page. Besides that, I tested the query by running it in the database itself and it returns the right results, so the query works fine.
Help is much appreciated!
You need to use mysql_fetch_row() inside a loop in itself:
$result = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($date = mysql_fetch_row($result))
{
echo $date[0];
}
You should also note that the mysql_* family of functions are not deprecated. You should avoid using them if possible, and look into alternatives such as MySQLi or PDO.
Try this: mysql_fetch_row() fetches only one row, If you need all the rows use mysql_fetch_assoc()
$sql = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($dates = mysql_fetch_assoc() ($sql)){
print_r($dates);
}
Ref: http://php.net/manual/en/function.mysql-fetch-row.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
mysql_fetch_row only returns one record from the actual result of your query. You have to call it several times, ontil it returns null :
$res = mysql_query(...);
while (($record = mysql_fecth_row($res)) !== null) {
print_r($record[0]);
}
Please note mysql_* function are deprecated and should not be used anymore, too.
I'm having trouble getting values out of my array returned from a MySQL query.
The results that are being returned are a table with these columns:
|team_id|name|pos|available|
There are multiple rows in the result. I need to go through each row and extract name and pos into their respective variables.
Here is my code:
$query = sprintf("SELECT * FROM `player_user` WHERE team_id = '$teamID[0]'");
$answer = mysql_query($query);
if ($answer === FALSE)
die(mysql_error());
while($row = mysql_fetch_assoc($answer))
{
$pname = $row['name'];
$pos = $row['pos'];
... do something with $pname and $pos
}
The example above should work, as long as the mysql query will return data. You should verify this using var_dump($row); inside the loop.
Although you should use the mysqli extension or PDO to access mysql databases. mysql_* functions as you currently use are deprecated and will once being dropped from PHP
You should use mysqli_fetch_array instead of mysql_fetch_assoc. That should return the results as you want.
http://php.net/manual/en/mysqli-result.fetch-array.php
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'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!