Page 1 of 1

include a section?

Posted: Mon Aug 17, 2009 11:56 pm
by m5884
Hi!

sorry if the following question seem juvenile as i am new to php!

I have the following code which is used through out different pages of a website. Now because its so repetitive, i was wondering if there is a way to turn the highlighted red section into a variable so if i change say $cid to $cidentity it changes throughout the website?

Code: Select all

<?php 
    $sql ="SELECT * FROM my_db";
    $res =mysql_query($sql, $conn);
    $num = mysql_num_rows($res);
    if($num>0)
    {
        [color=#BF0000]$cid        =mysql_result($res,0,'Cid');[/color]
        [color=#BF0000]$cdate      =mysql_result($res,0,'Cdate');[/color]
        [color=#BF0000]$cname      =mysql_result($res,0,'Cname');[/color]
        [color=#BF0000]$cdesc1     =mysql_result($res,0,'Cdesc1');[/color]
        [color=#BF0000]$cdesc2     =mysql_result($res,0,'Cdesc2');[/color]
        [color=#BF0000]$cdesc3     =mysql_result($res,0,'Cdesc3');[/color]
        [color=#BF0000]$cdimen     =mysql_result($res,0,'Cdimen');[/color]
        [color=#BF0000]$cimage     =mysql_result($res,0,'Cimage');[/color]
        [color=#BF0000]$ccater     =mysql_result($res,0,'Ccater');[/color]
        [color=#BF0000]$ccater     =mysql_result($res,0,'Cnew');[/color]
        [color=#BF0000]$cother1    =mysql_result($res,0,'Cother1');[/color]
        [color=#BF0000]$cother2    =mysql_result($res,0,'Cother2');[/color]
        [color=#BF0000]$cother3    =mysql_result($res,0,'Cother3');[/color]
        
        echo "something something ";
        
    }
    ?>
the only way i know how to do for now is save the red section as a new file, i.e. called red.php, and include it into the php code, i.e.

Code: Select all

 
<?php 
    $sql ="SELECT * FROM my_db";
    $res =mysql_query($sql, $conn);
    $num = mysql_num_rows($res);
    if($num>0)
    {
        [color=#BF0000]include 'red.php' [/color]
        
        echo "something something ";
        
    }
    ?> 
 
but i'm sure there should be a more techy way of doing it, but i'm not sure how to search for this question on the internet.

I hope it makes sense!

Thank you for your help in advance!

Re: include a section?

Posted: Tue Aug 18, 2009 12:52 am
by AlanG
A variable is an identifier that will be used throughout your script. An include would be the only way of doing this from within the script (as far as I can think of). But, I would suggest a change.

Instead of all those mysql_result() functions, you should grab an associative array. It will grant you more freedom in your script.

Code: Select all

<?php 
    $sql ="SELECT * FROM my_db";
    $res =mysql_query($sql, $conn);
    $num = mysql_num_rows($res);
    if($num>0)
    {
        $data = mysql_fetch_assoc($res);
        
        // Now instead of all those variables, you have one array
        // $data['Cid'], $data['Cdate'], $data['Cname'], etc...
 
        echo "something something ";
        
    }
    ?>