user1022772
user1022772

Reputation: 651

How to apply CSS to dynamically generated PHP database results

I'm trying to work out how I can break up a large block of text with CSS or PHP into paragraphs or line breaks. My PHP script queries a MYSQL database and returns a random number of entries (sentences) depending on the number selected by user. The results are echoed out in one large paragraph.

Is there anyway I can break up this one paragraph into smaller paragraphs? I don't want a line break after each result.

I can do this with fixed text in HTML with <p> tags or <br> tags but how can I do it with dynamically generated results when I have no idea how long the block of text will be? I'm quite new to PHP. Any suggestions appreciated.

Here is the code:

<?php
$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name="db"; // Database name 
$tbl_name="sentence"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$sn=$_POST['numberofsentences'];


$query="SELECT line FROM `sentence` ORDER BY rand() LIMIT $sn";
$result = mysql_query($query);

while ( $row = mysql_fetch_array($result) ) {
// do something with $row. The following echos the results and adds a space after each sentence.
echo $row['line'], "&nbsp";
}

// Close the database connection
mysql_close();

 ?>

Upvotes: 2

Views: 1386

Answers (4)

Ozzah
Ozzah

Reputation: 10701

Unfortunately the only thing you can do is use HTML (and optionally CSS) to do this.

Also you have some problems with your example code. '&nbsp' should have a ; at the end. I assume you mean mysql_fetch_assoc() and not mysql_fetch_array() since you're referencing the $row array with a string index rather than numerical?

$results = 0;
$max_results = 26;

while ($row = mysql_fetch_assoc($result))
{
  $results++;
  echo $row['line'] . "&nbsp;";

  if ($results % max_results == 0)
    echo "<br /><br />";
}

This will print out up to 25 space-separated results per line. This is very crude, but will work in the browser. Ideally, you should add supporting HTML tags such as html, body, etc...

Also, as a side note: I understand that you are still learning, but please please PLEASE remember that whenever you accept any sort of external input in your SQL strings, you must must MUST sanitize them first. What if $_POST['numberofsentences'] was equal to 0;DROP DATABASE db;?

If you're expecting the POST variable to be an integer, use mysql_real_escape_string() followed by intval().


Edit: I didn't want to remove the mistake I made in my post about dot vs. comma since it's referenced in the comments below, but it seems it may cause some confusion if I leave it in here. You can echo string1 . string2 or echo string1, string2. These both give the same output but work quite differently under-the-hood. To see the original post just look at the history.

Upvotes: 1

Yes Barry
Yes Barry

Reputation: 9846

One quick and easy way would be to set a static amount of sentences per paragraph like 4 or 5 and use that in your loop like so:

$count = 0; 
while ($row = mysql_fetch_array($result)) { 
    // do something with $row. The following echos the results and adds a space after each sentence. 
    echo $row['line'], "&nbsp"; 
    if ($count >= 4) { 
        echo '<br />&nbsp;&nbsp;&nbsp;&nbsp;'; 
        $count = 0; 
    } else { 
        $count++; 
    } 
}

Upvotes: 0

Maxime Pacary
Maxime Pacary

Reputation: 23041

Untested

define('NB_SENTENCE_PER_PARAGRAPH', 5);

// after the query...

$paragraphs = array();
$i = 0;

// prepare data

while ($row = mysql_fetch_array($result))
{
  $index = floor(%i / NB_SENTENCE_PER_PARAGRAPH);

  if (!isset($paragraphs[$index]))
    $paragraphs[$index] = array();

  $paragraphs[$index][] = $row['line'];
  $i++;
}

// display

foreach ($paragraphs as $sentences)
{
  echo '<p>'.implode('&nbsp;', $sentences).'</p>';
}

Note that it is generally a good idea to separate data retrieving from display (offers more flexibility).

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77956

Try this:

<?php
$host     = "localhost"; // Host name 
$username = "";          // Mysql username 
$password = "";          // Mysql password 
$db_name  = "db";        // Database name 
$tbl_name = "sentence";  // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$sn           = $_POST['numberofsentences'];
$s_count_orig = $s_count = 1; // Sentence counter
$p_count      = 1;            // Paragraph counter
$per_para     = 4;            // 4 sentences per paragraph
$paras        = array();      // Array to hold the paragraphs
$para         = array();      // Array to hold the sentences

$query  = "SELECT line FROM `sentence` ORDER BY rand() LIMIT $sn";
$result = mysql_query($query);

while ( $row = mysql_fetch_array($result) ) {
    // do something with $row. The following echos the results and adds a space after each sentence.

    // If there is room in the paragraph array for a sentence...
    if($s_count <= $per_para) {

        // Add the sentence to the array
        $para[$p_count] = $row['line'];

        // Next sentence
        $s_count++;
    }
    else {
        // We have a full paragraph, add it to our master array
        $paras[] = $para[$p_count];

        // Next paragraph
        $p_count++;

        // Reset sentence counter
        $s_count = $s_count_orig;
    }
}

// Iterate our master array of paragraphs
foreach($paras as $p){

    // Echo each paragraph, and each sentence in each paragraph separated by two spaces
    echo '<p>' . implode('&nbsp;&nbsp;',$p) . '</p>';
}

// Close the database connection
mysql_close();

 ?>

Upvotes: 0

Related Questions