it's just fetching the first element from the table.
Table name is categories which contains 2 columns : id, category
I cant understand why is it fetching just first row from the table.
<?php
$sql = "SELECT category FROM categories";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
//print_r($row);
?>
You need to iterate through the result set in order to retrieve all the rows.
while($row = mysql_fetch_assoc($result)) {
print($row);
}
Also, stop using mysql_ functions. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
Use this in while loop :
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Just like you wrote mysql_fetch_assoc($result); will get only one row. You have to use loop to get it all.
If you call mysql_fetch_assoc just once, you'll get only the first row...
while(false !== $row = mysql_fetch_assoc($result)) {
print_r($row)
}
The function you are using only does one record.
Try. ..while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['category'];
echo "";
}
For retrieve result set Use loop as per your need
foreach
Use when iterating through an array whose length is (or can be) unknown.
as
foreach($row as $val)
{
echo $val;
}
for
Use when iterating through an array whose length is set, or, when you need a counter.
for(i=0;i<sizeof($row);i++)
{
echo $row[$i];
}
while
Use when you're iterating through an array with the express purpose of finding, or triggering a certain flag.
while($row=mysqli_fetch_array($query))
{
echo $row['flag'];
}
Related
I am making a mysql query . I want to add result to an array. suppose I am selecting all user from user table. I want to get everyones name. if the row=5 i want to save every name according to the row index.
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
//echo ($row);
$num=mysql_num_rows($query);
echo ($num);
for ($i=1; $i<=$num;$i++){
//here I want to save all name to an array.
}
Please help.
You might be looking for something like this:
$rows = array();
// while there are more records, add them to `$rows`
while($row = mysql_fetch_assoc($result)) {
$rows []= $row;
}
Note that mysql_fetch_assoc() will just return false if there are no (more) records in the result set. So you don't need the call to mysql_num_rows()
$num = mysql_num_rows($query);
if($num > 0)
{
while($row = mysql_fetch_array($query)
{
$names[] = $row['name'];
}
}
That will create an array called $names which you can loop through later. Also, it's a good time to look into mysqli_* functions, or PDO.
Here is my PHP MySQL query:
$query = "SELECT falsegoto FROM timeconditions WHERE [timeconditions_id] = 0";
$result = mysql_query($query);
There should be only a single result from this query, and I'm not sure how display it in PHP?
mysql_result() seems to only work with larger data sets?
Any help or explanation would be valued.
As Peeha mentiod, your using mysql, but it's better to use mysqli
So the code will then look like this:
$query = "SELECT falsegoto FROM timeconditions WHERE [timeconditions_id] = 0";
$result = mysqli_query($query);
while($row = myslqi_fetch_assoc($result){
// DO STUFF
}
I use this for everything. It just loops through every row in the result. and if there's just one row, it while's only one time....
use it like this :
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
You have to fetch the row, there are a few methods of doing it: mysql_fetch_object, mysql_fetch_row, mysql_fetch_array and mysql_fetch_assoc.
These methods will read a single line from the result and remove it from the handler, so if you loop the call it will read all the rows, one by one until it reaches the end and returns false.
example:
while($obj = mysql_fetch_object($result)){
echo $obj->name;
}
PHP.net documentation:
mysql_fetch_object,
mysql_fetch_row,
mysql_fetch_array,
mysql_fetch_assoc
I am a novice at PHP and i have encountered a problem with the following code...
<?php
// Connects to Database
mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT country_id, country_name FROM country, channels WHERE channels.channel_id = country.channel_id AND channels.channel_id = '1'")
or die(mysql_error());
echo "<table border=0 cellpadding=15>";
echo "<tr align = center bgcolor=white>
<td><b>Country ID</b></td><td><b>Country Name</b></td>" ;
while (mysql_fetch_row($data)) {
$cid = mysql_result($data, 1);
$cname = mysql_result($data, 2);
# inserts value into table as a hyperlink
echo "<tr align = center bgcolor=white><td>$cid</td><td><a href=view_country_detail.php?cid=$cid>$cname</td>";
}
# displays table
print '</table>';
?>
to explain the problem i am getting, i am after generated hyperlinks to drill down to the companies which share the to be clicked country's id from the code above to then display a similar layout on the 'view_country_detail' page. i cant work out why the output for the table gives me a repeated row for the first two id's for the country column in the db. any help would be greatly appreciated as i am totally lost here. Thanks
I don't understand why you use mysql_fetch_row and then don't want to actually use the row you fetch.
You should not be using mysql_result here. What you are doing is fetching data from row 1 of the result set and then data from row 2 regardless of which row the pointer is on in your while loop.
Try this:
while ($row = mysql_fetch_assoc($data)) {
$cid = $row['country_id'];
$cname = $row['country_name'];
}
I personally find it much more readable in code to reference the fields by the associative keys used when using mysql_fetch_assoc or mysql_fetch_array.
Try structuring your while loop as follows:
while($row = mysql_fetch_array($data)){
$cid = $row[0]; //if you have the column names, replace 0 with 'column_name'
$cname = $row[1];
//then echo statement
}
Also, mysql_* functions have started the deprecation process and should no longer be used, even the php manual pages state the use of mysql_* is discouraged. Look into using the similar mysqli_* functions or PDO.
Try this:
while ($row = mysql_fetch_row($data)) {
$cid = $row[0];
$cname = $row[1];
...
}
mysql_fetch_row returns an array.
HOWEVER
You should look at stopping using the mysql_* functions - they're being deprecated. If you switch to PDO or mysqli, it helps make your code more secure, too.
I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;
i have a query that should return 40 results:
$test = mysql_query(" SELECT fname FROM online_all WHERE verify_status = 'v' LIMIT 40 ");
if (!$test ) {print " - Mysql Error - ";echo fns_et_mysql_error(mysql_error());}
if i echo mysql_num_rows($test); i get 40. which means that i get the results
but when i print_r $roww = mysql_fetch_array($test); i get only one result.
there are no php errors.
You have to loop through the results with:
while($row = mysql_fetch_array($test)) {
// awesomeness with $row
}
Try using a loop.
while($row = mysql_fetch_array($test)){
}
mysql_fetch_array returns one row at a time. If you want to loop through all of them you do the following:
while ($row = mysql_fetch_array($test))
//Do something
http://php.net/manual/en/function.mysql-fetch-array.php
Check the documentation. mysql_fetch_array only fetches one row of data at a time. To get the data for all 40 rows you need a loop (like a for loop conditioned by mysql_num_rows).
You need to iterate the results from the query.
while($row = mysql_fetch_array($test))
{
// This is how you print fname.
echo $row[0];
}
Please refer to the documentation where there's also many useful tips of how you can use this function.
http://php.net/manual/en/function.mysql-fetch-array.php
You should also know that there exist another useful function for fetching results from mysql queries that fetches results as an associative array.
http://php.net/manual/en/function.mysql-fetch-assoc.php
You have to loop thru the rows:
while($row = mysql_fetch_array($test)){
var_dump($row);
//etectera
}