tags:

views:

66

answers:

4

How can you display multiple values from the same mysql field using php and mysql

Here is the code I have already

<?php
if(!empty($skill) || !empty($years) || !empty($rating)){
 if (!empty($skill))
 {
  echo '<p>' . $skill . '</p>';
 }
 if (!empty($years))
 {
  echo '<p>' . $years . '</p>';
 }
 if (!empty($rating))
 {
  echo '<p>' . $rating . '</p>';
 }
 }
?>

What I'm trying to ask is that I want the above code to loop the above three echos contents and variables until the data entered into the database is fully displayed for example if the user entered 1-100... different skills, years and ratings display all the entered data.

I hope I'm explaing it right

A: 

If I understood well try to implement this meta-code:

while (FALSE!==$row=fetch_array()) {
   <do your echoes for every row>
}
AlberT
+1  A: 

Something like this:

Single Record:

<?php
// db connection 
// query
$resource = mysql_query("YOUR QUERY HERE");
// 1 record as a result
$aRow = mysql_fetch_array($resource);
foreach ($aRow as $sKey => $sValue) {
  show($sValue);
}

function show($var) {
  if (!empty($var)) {
    echo '<p>'.$var.'</p>';
  } 
}

Multiple Records:

<?php
// db connection 
// query
$resource = mysql_query("YOUR QUERY HERE");
// multiple records as a result
while ($aRow = mysql_fetch_array($resource)) {
  foreach ($aRow as $sKey => $sValue) {
    show($sValue);
  }
}

function show($var) {
  if (!empty($var)) {
    echo '<p>'.$var.'</p>';
  } 
}
Robert Cabri
this way you are displaying only one row.
AlberT
Added a multiple row example
Robert Cabri
A: 
// Make a MySQL Connection
$query = "SELECT * FROM example"; 

$result = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
    $skill  = $row['skill'];
    $years  = $row['years'];
    $rating = $row['rating'];

    // your code goes here.

}
Andrejs Cainikovs
A: 

You need to loop over each row returned by your MySQL query, for example:

$result = mysql_query("SELECT skill, years, rating, etc. FROM Table ..");
if (! $result) {
    die('Error ' . mysql_error());
}

while ($row = mysql_fetch_assoc($result)) {
    if (!empty($row['skill']) || !empty($row['years']) || !empty($row['rating'])) { 
        if (! empty($row['skill'])) {
            echo '<p>' , htmlspecialchars($row['skill']) , '</p>';
        }

        //etc.
    }
}

It is important to use htmlspecialchars() to prevent XSS attacks if the data is not guaranteed to be safe.

Tom Haigh