3

I'm trying to breakdown a paragraph, retrieved from a database array, into separate words. Is this the right way to go about doing it because it is currently giving an error saying explode() expects 2 parameters, so it must not be picking up the $row array.

function words() {
        $query = mysql_query("SELECT text FROM table WHERE textID = 1");
        while($row = mysql_fetch_array($query)) {
            $e[] = explode(" ", $row);
            foreach($e as $r) {
                echo $r;
            }
        }
    }

4 Answers 4

3
function words() {
        $query = mysql_query("SELECT text FROM table WHERE textID = 1");
        while($row = mysql_fetch_array($query)) {
            $e[] = explode(" ", $row[0]);
            foreach($e as $r) {
                echo $r;
            }
        }
    }

$row is array. Choose first element to explode. Read documentation for Explode.

Sign up to request clarification or add additional context in comments.

1 Comment

I missed that part. Thank you very much.
0
function words() { 
        $query = mysql_query("SELECT text FROM table WHERE textID = 1"); 
        while($row = mysql_fetch_array($query)) { 
            $e[] = explode(" ", $row[0]); 
            foreach($e as $r) { 
                echo $r; 
            } 
        } 
    } 

2 Comments

mysql_fetch_assoc will return to you array with "text" field
Oops didnt notice that he is using mysql_fetch_array.
0

You are using wrong functions architecture here.
You don't need words() function at all. explode is enough.
While you strongly need a function to get data from mysql, which is apparently unrelated to your explode needs.
Also note that a function should never do any output but retirn values only (save for the functions intended for the output only).

So, the function could be

function dbgetvar($query){
  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return FALSE;
  }
  $row = mysql_fetch_row($res);
  if (!$row) return NULL;
  return $row[0];
}

And your code become as simple as

$text  = dbgetvar("SELECT text FROM table WHERE textID = 1");
$words = explode(" ",$text);
foreach ($words as $w) echo $w;

Comments

-1
function words() {
        $query = mysql_query("SELECT text FROM table WHERE textID = 1");
        while($row = mysql_fetch_array($query)) {
            $e = explode(" ", $row);
            foreach($e[0] as $r) {
                echo $r;
            }
            }
    }

The $row is populated entirely with the field value therefore $e[0] is the right variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.