Jump to content

Arrays and Loops


scottybwoy

Recommended Posts

I am trying to get my head around while loops and also using array data with them, or with another kind of loop.  What I am trying to do isn't too hard, but is just out of my reach, so was hoping someone here could help.  I have two problems, but if I get help with one I may be able to work out the other.  Here goes :

First problem is for displaying the right content to users, for this I have templates made with comment blocks for the user sections.  Then I have an array containing the type of users and a corresponding integer like so :
[code]
<?php
$USER_TYPE = array('9' => 'Admin',
  '4' => 'Man',
'3' => 'Tech',
'2' => 'Acc',
'1' => 'Sale');
?>
[/code]
Then I have a function that is meant to find out which userLevel they are and to scan the template for the areas they are allowed and uncomment them, although I'm unsure how to put this into practice.  This is what I have so far :
[code]
<?php
function templateLevel($file)
{
global $template, $username;

$this->userLevel($this->getUserName());
$this->loadTemplate($file);

while ($USER_TYPE[$k] <= $user_level)
{
$type = $USER_TYPE[$k];
$template = str_replace("<!-- BEGIN " . $type . "", "", $template);
$template = str_replace("END " . $type . " -->", "", $template);

}

return $template;
}
?>
[/code]
As you can see, it is meant to scroll through the array like a foreach untill it reaches the $user_level in the $USER_TYPE key value.  Then I want it to replace the $type as the value in the $USER_TYPE array for each key upto $user_level.

My other problem, may be a little more complex but I still not got my head around while loops so it may not be ;) .  What I am trying to do here, is create a customer ID from the name, that bit works fine, however I want it to find a gap or the final id number for insertion in the database that is the problem.  Please take a look at my code :
[code]
<?php
function makeCustId($company)
{
global $company, $rowInt, $custId;

$comp = preg_replace('|[^A-Z]|i', '', $company);
  $comp = substr($comp, 0, 3);
echo $comp . "<br>";

  $this->appCon();

  $sql = mssql_query("SELECT custId FROM customers WHERE custId LIKE '" . $comp . "%'");
$rowcount = mssql_fetch_row($sql);

if (isset($rowcount)) {
$start = 1;
} else {
$start = 0;
}

echo $start;
$rowInt = sprintf("%03d", $start);
echo $rowInt . "<br>";

while (substr(mssql_fetch_row($sql), 4, 6) == $rowInt) {
$rowInt = substr(mssql_fetch_row($sql), 4, 6);
$rowInt = ++$rowInt;
$rowInt = sprintf("%03d", $rowInt);
echo $rowInt . "<br>";
}

  $custId = $comp . $rowInt;

  return $custId;
}
?>
[/code]
So as you can see $rowInt is a 3char integer that is appended to $cust to form the complete $custId.  I want it to go through the database where the $custId starts the same, and when it finds no incremental value, to create it and come out of the loop.  This has all just gone a little bit confusing for me, with my lack of experience.  But I'm really getting into this programming malarky so really want to nail this important thaught process.  Thanks for helping
Link to comment
Share on other sites

After working a little more, I think I have made a little more sense of it, but still have not got them working.  Here is the updated scripts :

Problem 1) user level display :
[code]
<?php
function templateLevel($file)
{
global $template, $user_level, $USER_TYPE;

$this->userLevel($this->getUserName());
$this->loadTemplate($file);

$USER_TYPE = array('9' => 'Admin',
  '4' => 'Man',
'3' => 'Tech',
'2' => 'Acc',
'1' => 'Sale');

foreach ($USER_TYPE as $k => $v)
{
if ($k <= $user_level)
{
$template = str_replace("<!-- BEGIN " . $v . "", "", $template);
$template = str_replace("END " . $v . " -->", "", $template);
}

}

return $template;
}
?>
[/code]
This seems to not uncomment the template at all, can I use an "if" within a foreach?

Problem 2) CustId Insert
[code]
<?php
function makeCustId($company)
{
global $company, $rowInt, $custId;

$comp = preg_replace('|[^A-Z]|i', '', $company);
  $comp = substr($comp, 0, 3);

  $this->appCon();

  $sql = mssql_query("SELECT custId FROM customers WHERE custId LIKE '" . $comp . "%'");
$custCount = mssql_fetch_row($sql);

if (isset($custCount))
{
$rowInt = sprintf("%03d", 0);
$custCount = $comp . $rowInt;

while ($custCount == mssql_fetch_row($sql))
{
$rowInt = substr($custCount, 4, 6);
$rowInt = $rowInt++;
$rowInt = sprintf("%03d", $rowInt);
$custCount = $comp . $rowInt;
echo $custCount . "<br>";
return $custCount;
}

  $custId = $comp . $rowInt;

} else {
$custId = $comp . sprintf("%03d", 0);
}

  return $custId;
}
?>
[/code]
This still does not increment the custId as when it returns, it still shows as "000".  Could this be due to the while loop executing the mssql_fetch_rows for the second time?  I tries using mssql_result for the first one, but it didn't like it.  Wrong Perameter Count.
Link to comment
Share on other sites

I think your approach is making this much more difficult than it needs to be. Including all content and removing comment tags is a bad design in my opinion. Every user could see all the content by viewing the source!

A better approach would be to redo the template to be dynamic based upon the user type and ONLY return the content relevant to the user. Such as:
[code]<?php
if ($usertype <= 5) { //Use the appropriate number in each section
echo //content for this section
}
?>[/code]

However, looking at your code above I don't see any blatant errors int he first section. However, I have no way of knowing what is in some of these variables to determine if something is happeing as it should.

Int he 2nd section, at least part of your problem is that you are not referencing the custID from the query correctly. After you retrieve the data for a record using "$custCount = mssql_fetch_row($sql);", the data in $custCount is in an array, so the value is in the form $custCount[0]. Plus, the way you have it written, the first record in the query results will not be used at all because you use mssql_fetch_row right after the query and at the begininng of the loop before you access the data the first time.
Link to comment
Share on other sites

Also rather than have arrays of user levels why don't you just store their level in the table with their username and when they login you can set their level automatically. Use sessions to keep the level set across all your pages. MUCH easier than manual arrays and such.

Ray
Link to comment
Share on other sites

Thanks, crayo, I already have that set up, already, the array was just a refrence for the template.

I like your idea mjdamato I didn't think of that.  But I still have trouble, grasping the concept.  Would I need to have diffrent templates for each user level, as that seems long.  How do you mean to set up the templates?

Lol after just getting that section working!  The problem was that I did not define $user_level & $template.

Yeah I realised your second points on Problem 2 and have been fidling with it, I now have it working this is code :
[code]
<?php
function makeCustId($company)
{
global $company, $rowInt, $custId;

$comp = preg_replace('|[^A-Z]|i', '', $company);
  $comp = substr($comp, 0, 3);

  $this->appCon();

  $sql = "SELECT custId FROM customers WHERE custId LIKE '" . $comp . "%'";
$result = mssql_query($sql);

if ($result == TRUE)
{
$rowInt = sprintf("%03d", 0);

while ($custCount = mssql_fetch_row($result))
{
$custCount = $custCount[0];
$custInt = substr($custCount, 3, 5);

if ($custInt != $rowInt)
{
break;
}

$rowInt = ++$custInt;
$rowInt = sprintf("%03d", $rowInt);
$custCount = $comp . $rowInt;
$custId = $custCount;
}

return $custId;

} else {
$custId = $comp . sprintf("%03d", 0);
}

  return $custId;
}
?>
[/code]
Link to comment
Share on other sites

This is what I mean.

If your template has this:
[code]<!-- BEGIN 2
This is some content in the "2" section
END 2 -->

<!-- BEGIN 4
This is some content in the "4" section
END 4 -->[/code]

change it to this:
[code]<?php
if ($user_level>=2) {
?>
    This is some content in the "2" section
<?php
}
if ($user_level>=4) {
?>
    This is some content in the "4" section
<?php
}
?>[/code]
Link to comment
Share on other sites

That's simpler than I thaught, great!!
However the parsing of the HTML thinks that the <?php if ($user... > is html code and so breaks the script.  Do I need a / or to parse my templates differently? This is my template loader :
[code]
<?php
function loadTemplate($file)
{
global $template;

$strfile = $file;

    if (!file_exists($strfile)) print"Loading template failed!";
    $thisfile = file($strfile);

    while(list($line,$value) = each($thisfile))
    {
        $value = ereg_replace("(\r|\n)","",$value);
        $template .= "$value\r\n";
    }

    return $template;
}
?>
[/code]
Then $template is echoed out into the page stucture I have formed.  This doesn't seem to implement the php code.  Any Ideas?
Link to comment
Share on other sites

Sorry mjdamato, that won't/doesn't work.  If you look at my loadTemplate function posted above, you will see that what it does is tack all the content out of it and print it into the $template var.  So I thaught your option would just work, however it's just being passed to the client-side browser, so would I need to edit that function to account for this?  If so what would you suggest I do.

Thanks
Link to comment
Share on other sites

Hmm, no I can't do that because of the construct of my site, this is how the page is loaded :
[code]
<?php
    function displayHome()
    {
    global $company, $product, $template;

    $content = $_REQUEST['content'];
    $company = $_REQUEST['company'];
    $product = $_REQUEST['product'];

    if (!empty($company))
    {
    require(COMPANY_SCR);

    } else if (!empty($product)) {
    include(PRODUCT_SCR);
   
    } else if ($content == "") {
    global $user_level;

    $user_level = $_SESSION["USER_LEVEL"];
//    $template = include(ADMIN_PAGE);
    $template = $this->loadTemplate(ADMIN_PAGE);

    } else {
$template = $this->LoadTemplate(TEMPLATE_DIR . "//" . $content . ".inc");
}

require_once(HEADER);

echo "<table width=100% valign='left'><tr><td rowspan='2' width=60%>";
print $template;
echo "</td><td width=40%>";
include(TEMPLATE_DIR . "/inform.php");
echo "</td></tr><tr><td>";
include(TEMPLATE_DIR . "/prodDisp.php");
echo "</td></tr><tr><td colspan='2'>";
  require_once(TEMPLATE_DIR . '/footer.php');
echo "</td></tr></table>";

}
?>
[/code]

Do you see what I mean?
Link to comment
Share on other sites

[code]I'm not going to tell you how to build your site, but creating templates with comments that need to be removed based upon the user level seems increadibly inefficient to me. Plus the user is getting all the content anyway.

here is my suggestion. Do with it what you want:

Instead of doing the LoadTemplate and then doing a print $template, simply put an include($templateFile) and do all the logic for determining what to show and what not to show inthe template itself.

The code above would look something like this:
{code}<?php
function displayHome()
    {
        global $company, $product, $template;

        $content = $_REQUEST['content'];
        $company = $_REQUEST['company'];
        $product = $_REQUEST['product'];

        if (!empty($company))
        {
            require(COMPANY_SCR);

        } else if (!empty($product)) {
            include(PRODUCT_SCR);
   
        } else if ($content == "") {
            global $user_level;
            $user_level = $_SESSION["USER_LEVEL"];
            $templateFile = ADMIN_PAGE;

        } else {
            $templateFile = (TEMPLATE_DIR . "//" . $content . ".inc");
        }

        require_once(HEADER);
        echo "<table width=100% valign='left'><tr><td rowspan='2' width=60%>";
        include ($templateFile);
        echo "</td><td width=40%>";
        include(TEMPLATE_DIR . "/inform.php");
        echo "</td></tr><tr><td>";
        include(TEMPLATE_DIR . "/prodDisp.php");
        echo "</td></tr><tr><td colspan='2'>";
        require_once(TEMPLATE_DIR . '/footer.php');
        echo "</td></tr></table>";
    }
?>[/code]

I also notice you are using a require in one instance and an include in another similar instance - any reason for that?
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.