0

I have a MySQL table which contains page content, each line of content has a page_id number

I want to load all the variables for the page I'm on, then display them where they need to be...

I'm naming the variables: div_1, div_2, div_3 etc etc

here's what I'm trying:

PHP

$home_p1 = mysql_query("select div_content from page_content where (page_id = '1');",$db);

$i=1;
while ($p1 = mysql_fetch_array($home_p1)){
$div_.$i = $p1[0];
$i++;
}

then throughout the page i can

echo $div_1;
blah blah blah
echo $div_2
blah blah blah
echo $div_3
etc etc

But I'm getting nothing back, I'm not even sure if this is the correct logic to do such a thing?

4 Answers 4

1

Use arrays.

$div[$i] = $p1[0];

And through the page you can:

echo $div[1];
blah blah blah
echo $div[2];
blah blah blah
echo $div[3];
etc etc

If you want to keep your structure structure then use:

$tempname = "div_".$i;
$$tempname=$p1[0];

For more details see this (first solution) and this (second solution).

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

Comments

0

organize it in arrays like this:

$home_p1 = mysql_query("select div_content from page_content where (page_id = '1');",$db);
$results = array();
$i=1;
while ($p1 = mysql_fetch_array($home_p1)){
    //$div_.$i = $p1[0];
    $results[] = $p1[0];
    $i++;
}

then you can access the first line by

echo $results[0]; // second by $results[1] and so on.

have fun!

Comments

0

You can't create variables like this:

$div_.$i = $p1[0];

You should put them into an array like this:

$div_array = array();

then

$div_array[$i] = $p1[0];

Now you can output them by referencing the array directly:

echo $div_array[1];

Or else you can expand the array into variables using extract:

extract($div_array, EXTR_PREFIX_ALL, 'div_');

Now you have your $div_$i variables.

Comments

0

In order to accopmlish what you are trying to, you should do something like next:

$home_p1 = mysql_query("select div_content from page_content where (page_id = '1');",$db);

$i=1;
while ($p1 = mysql_fetch_array($home_p1)){
  $name = 'div_' . $i;
  $$name = $p1[0];
  $i++;
}

You will get the list of variables with names $div_1, $div_2, etc. http://www.php.net/manual/en/language.variables.variable.php

But the best way, as it was said, to use arrays.

$home_p1 = mysql_query("select div_content from page_content where (page_id = '1');",$db);

$i=1;
$divs = Array();
while ($p1 = mysql_fetch_array($home_p1)){
  $divs['div_' . $i] = $p1[0];
  $i++;
}

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.