user470760
user470760

Reputation:

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.

How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.

To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.

Upvotes: 1

Views: 1228

Answers (4)

Mr. Alien
Mr. Alien

Reputation: 157334

You need to do it like this...

First connect to your sql... Reference

Now make a query and assign it to a variable...

$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");

If you want to retrieve a single row use LIMIT 1

$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");

If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this

$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");

Now fetch the array out of it and loop through the array like this..

while($show_rows = mysqli_fetch_array($query)) {
   echo $show_rows['column_name1'];
   echo $show_rows['column_name2'];
}

If you don't want to include the column names in the while loop, you could do this:

while($show_rows = mysqli_fetch_array($query)) {
   foreach( $show_rows as $key => $val )
   {
       echo $show_rows[$key];
   }
}

Upvotes: 0

coderabbi
coderabbi

Reputation: 2301

What you've outlined requires 4 basic steps:

  1. Connect to the database.
  2. Query for a specific row.
  3. Remove the null values from the result.
  4. Create the html.

Step 1 is quite environment specific, so that we can safely skip here.


Step 2 - SQL

SELECT * from <tablename> WHERE <condition isolating single row>


Step 3 - PHP (assuming that $query represents the executed db query)

//convert the result to an array
$result_array = mysql_fetch_array($query);

//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');


Step 4 - PHP

foreach ($result_array as $key => $value)
{
    echo $value \n;
}

Upvotes: 2

taufique
taufique

Reputation: 2751

you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples

Upvotes: 0

user849137
user849137

Reputation:

Just SELECT * FROM table_name WHERE.... will do the trick.

To grab data from specific fields, it would be SELECT field_1,field_2,field_3....

Upvotes: 2

Related Questions