Jump to content

variables from array dissappear in while looped query


turpentyne

Recommended Posts

I'm pushing variables into an array, based on a selection. The page reloads, and the array is one longer. Then I have a little bit of code that and then I want to loop through the array to print out the selections to the page.

 

First of all, is there a more sensible, shorter way to write this? Second, my variables $val and $q_cat aren't getting inserted into the query. If I switch those variables out and use hard values, the query works fine,

 

Here's what I have:

 


foreach($results_done as $key => $val) {

$q_cat = "";

if ($key == "1") { $q_cat = "4";}
elseif ($key == "2") { $q_cat = "1";}
elseif ($key == "3") { $q_cat = "11";}
elseif ($key == "4") { $q_cat = "2";}
elseif ($key == "5") { $q_cat = "10";}
elseif ($key == "6") { $q_cat = "9";}

$query_cats = mysql_query("SELECT tbl_component_categories.ID, tbl_component_categories.folder_path, tbl_component_categories.comp_cat_name, tbl_components.component_name FROM tbl_components JOIN tbl_component_categories on $q_cat = tbl_component_categories.ID
where tbl_components.ID = $val");

   if (!$query_cats) {
      $message  = 'Invalid query: ' . mysql_error() . "\n";
      $message .= 'Whole query: ' . $query_cats;
      die($message);
   }


    while ($row = mysql_fetch_array($query_cats)) { 
    echo $row['comp_cat_name'].": ".$row['component_name']."<br />";
    }
}

 

 

Link to comment
Share on other sites

The way I understood what I'm doing, I need to query the database each time, because the next selection is contingent on what they chose.

 

Scenario.. choose between A1 or A2.

 

If you choose A, the page reloads with options B1, B3, and B4

If you choose B, the page loads from the database with options B2, B3 or B5

 

And it continues on from there, using a many-to-many link table to add what I want to each page.

 

I'm sure there's a better way, but in the meantime, can somebody tell me why the variables aren't getting into the query?

Link to comment
Share on other sites

Second, my variables $val and $q_cat aren't getting inserted into the query.

$q_cat = "";

if ($key == "1") { $q_cat = "4";}
elseif ($key == "2") { $q_cat = "1";}
elseif ($key == "3") { $q_cat = "11";}
elseif ($key == "4") { $q_cat = "2";}
elseif ($key == "5") { $q_cat = "10";}
elseif ($key == "6") { $q_cat = "9";}

 

First off, you provide no default for $q_cat. I assume that the issue lies with $key.

You can also make the logic sexier by using a switch statement.

 

switch($key) {
    case 1:
        $q_cat = 4;
        break; // Without this statement, the page would continue checking the other cases, albeit, they would all get evaluated as false
    case 2:
        $q_cat = 1;
        break;
    case 3:
        $q_cat = 11;
        break;
    case 4:
        $q_cat = 2;
        break;
    case 5:
        $q_cat = 10;
        break;
    case 6:
        $q_cat = 9;
        break;
    default: // If the key is not 1-6, have a fallout. You can log the error, or do whatever you want.
        $q_cat = -1;
}

 

You do not need to enclose the number in quotes. PHP automatically converts variable types. Keep it clean.

 

As far as $val, if $key is messed up, it is as likely that $var will be too.

 

Enter this before the foreach and copy the results so we can see.

print_r($results_done);

Link to comment
Share on other sites

Yeah, that was the part I was thinking - that there has to be a way to run the query once, but I couldn't think how.

 

I do have the $results_done printing out to the page, i just didn't put it in here. Sorry about that. I'm getting this:

 

When the page first loads, it prints out:

Array ( [0] => )

 

When they make a selection, the page reloads and $results_done = Array ( [0] => [1] => 34 )

 

 

I'm sure my entire page is all screwy but I don't really know how else to do this page. I've been going in circles on it. Such a simple concept, but not easy for my artist brain to understand.

Link to comment
Share on other sites

If you want one SQL, try this.

 

<?php
$beginning = true;
$sql_where = '';
foreach($results_done as $key => $val) {
switch($key) {
    case 1:
        $q_cat = 4;
        break; // Without this statement, the page would continue checking the other cases, albeit, they would all get evaluated as false
    case 2:
        $q_cat = 1;
        break;
    case 3:
        $q_cat = 11;
        break;
    case 4:
        $q_cat = 2;
        break;
    case 5:
        $q_cat = 10;
        break;
    case 6:
        $q_cat = 9;
        break;
    default: // If the key is not 1-6, have a fallout. You can log the error, or do whatever you want.
        $q_cat = -1;
}

if(!$beginning) {
	$sql_where .= ' OR';
} else {
	$beginning = false;
}

$sql_where .= ' WHERE tbl_components.ID = \'' . $val . '\'';
}

$sql = 'SELECT
		`tbl_component_categories.ID`,
		`tbl_component_categories.folder_path`,
		`tbl_component_categories.comp_cat_name`,
		`tbl_components.component_name`
	FROM
		`tbl_components`
	JOIN `tbl_component_categories` on $q_cat = tbl_component_categories.ID';
$sql .= $sql_where;

$query_cats = mysql_query($sql);

if (!$query_cats) {
  $message  = 'Invalid query: ' . mysql_error() . "\n";
  $message .= 'Whole query: ' . $query_cats;
  die($message);
}


while ($row = mysql_fetch_array($query_cats)) { 
echo $row['comp_cat_name'].": ".$row['component_name']."<br />";
}

Link to comment
Share on other sites

If you want one SQL, try this.

 

<?php
$beginning = true;
$sql_where = '';
foreach($results_done as $key => $val) {
switch($key) {
    case 1:
        $q_cat = 4;
        break; // Without this statement, the page would continue checking the other cases, albeit, they would all get evaluated as false
    case 2:
        $q_cat = 1;
        break;
    case 3:
        $q_cat = 11;
        break;
    case 4:
        $q_cat = 2;
        break;
    case 5:
        $q_cat = 10;
        break;
    case 6:
        $q_cat = 9;
        break;
    default: // If the key is not 1-6, have a fallout. You can log the error, or do whatever you want.
        $q_cat = -1;
}

if(!$beginning) {
	$sql_where .= ' OR';
} else {
	$beginning = false;
}

$sql_where .= ' WHERE tbl_components.ID = \'' . $val . '\'';
}

$sql = 'SELECT
		`tbl_component_categories.ID`,
		`tbl_component_categories.folder_path`,
		`tbl_component_categories.comp_cat_name`,
		`tbl_components.component_name`
	FROM
		`tbl_components`
	JOIN `tbl_component_categories` on $q_cat = tbl_component_categories.ID';
$sql .= $sql_where;

$query_cats = mysql_query($sql);

if (!$query_cats) {
  $message  = 'Invalid query: ' . mysql_error() . "\n";
  $message .= 'Whole query: ' . $query_cats;
  die($message);
}


while ($row = mysql_fetch_array($query_cats)) { 
echo $row['comp_cat_name'].": ".$row['component_name']."<br />";
}

 

That will result in malformed SQL; WHERE tbl_components.ID = '1'  WHERE tbl_components.ID = '2'  WHERE tbl_components.ID = '3'

 

selection, the page reloads and $results_done = Array ( [0] => [1] => 34 )

 

Well, that's your problem. $val is going to be an Array.

 

I can't really help because I still don't have any idea what you're trying to do. I don't know where $results_done is coming from, and I don't know what method you are using to get data to your script.

Link to comment
Share on other sites

If you want one SQL, try this.

 

<?php
$beginning = true;
$sql_where = '';
foreach($results_done as $key => $val) {
switch($key) {
    case 1:
        $q_cat = 4;
        break; // Without this statement, the page would continue checking the other cases, albeit, they would all get evaluated as false
    case 2:
        $q_cat = 1;
        break;
    case 3:
        $q_cat = 11;
        break;
    case 4:
        $q_cat = 2;
        break;
    case 5:
        $q_cat = 10;
        break;
    case 6:
        $q_cat = 9;
        break;
    default: // If the key is not 1-6, have a fallout. You can log the error, or do whatever you want.
        $q_cat = -1;
}

if(!$beginning) {
	$sql_where .= ' OR';
} else {
	$beginning = false;
}

$sql_where .= ' WHERE tbl_components.ID = \'' . $val . '\'';
}

$sql = 'SELECT
		`tbl_component_categories.ID`,
		`tbl_component_categories.folder_path`,
		`tbl_component_categories.comp_cat_name`,
		`tbl_components.component_name`
	FROM
		`tbl_components`
	JOIN `tbl_component_categories` on $q_cat = tbl_component_categories.ID';
$sql .= $sql_where;

$query_cats = mysql_query($sql);

if (!$query_cats) {
  $message  = 'Invalid query: ' . mysql_error() . "\n";
  $message .= 'Whole query: ' . $query_cats;
  die($message);
}


while ($row = mysql_fetch_array($query_cats)) { 
echo $row['comp_cat_name'].": ".$row['component_name']."<br />";
}

 

That will result in malformed SQL; WHERE tbl_components.ID = '1'  WHERE tbl_components.ID = '2'  WHERE tbl_components.ID = '3'

 

selection, the page reloads and $results_done = Array ( [0] => [1] => 34 )

 

Well, that's your problem. $val is going to be an Array.

 

I can't really help because I still don't have any idea what you're trying to do. I don't know where $results_done is coming from, and I don't know what method you are using to get data to your script.

 

if(!$beginning) {
	$sql_where .= ' OR';
} else {
	$beginning = false;
}

Link to comment
Share on other sites

That will result in malformed SQL; WHERE tbl_components.ID = '1'  WHERE tbl_components.ID = '2'  WHERE tbl_components.ID = '3'

 

Not only that, but concatenating a bunch of WHERE clauses for conditions against the same field is unnecessary. Just use the "IN" operator.

Link to comment
Share on other sites

Welll, I've been avoiding this, because I know it's frightening to look at my beginner's mess, but here's the whole code. I have a table of all components, a table of all categories, and a table that shows which components are compatable. The page pulls 2 options. They choose one or the other, and the page reloads after php queries the database and selects the new information to show. The whole thing is a mess, but I've got it mostly working. I just can't get the 'rolling' results of what they've chosen to work.

 

<?php 
session_start();

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

if(isset($_POST['reset'])){

// set to empty if they've pressed the reset button.
unset($_SESSION['options_picked']);
unset( $_POST['chosen'] );

$results_done = '';

$page = $_SERVER['http://www.website.com/build-your-own.php'];

$sec = "1";

} 

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */


if(!isset($_SESSION['options_picked'])){
// set my empty session at the beginning of everything - This is the array that I use to fill the results variable.
$_SESSION['options_picked'] = array();
} 

if (!isset($_POST['chosen'])) {
// set my $var at the beginning of everything
$var = "4";


$query_text = "SELECT tbl_component_categories.ID, tbl_component_categories.folder_path, tbl_component_categories.comp_cat_name, tbl_components.component_name, tbl_components.image_filepath, tbl_components.component_category, tbl_components.ID AS comp_id
FROM tbl_components JOIN tbl_component_categories ON tbl_components.component_category = tbl_component_categories.ID AND tbl_component_categories.ID = $var ORDER BY tbl_components.component_category";
// $_SESSION['options_picked'] = array();

} 


elseif(isset($_POST['chosen']))  {


$choicetest = $_POST['chosen'];


// echo "and it is ".$choicetest;

// print_r($_SESSION['options_picked']); // for testing . delete at completion.



// below section is hard coded for the moment.
// maybe I query the database for categories and category id, then I can loop to create the below statements
// so it would be like: if post == 'row[x] { var =  row[y];




	$var = "";

 	if((isset($_POST['what_category'])) && ($_POST['what_category'] == 'Buttstocks')){ 
 	$var = "1";

 	} else if((isset($_POST['what_category'])) && ($_POST['what_category'] == 'Accessory_Rail_Mounts')){
 	$var = "11";
 	} else if((isset($_POST['what_category'])) && ($_POST['what_category'] == 'Caliber')){
 	$var = "2";
 	} else if((isset($_POST['what_category'])) && ($_POST['what_category'] == 'Barrel_length')){
 	$var = "10";
 	} else if((isset($_POST['what_category'])) && ($_POST['what_category'] == 'Suppressors')){
 	$var = "9";
	 	}



$query_text = "SELECT DISTINCT tbl_component_to_component.component_ID, tbl_component_to_component.compatible_component_ID, tbl_component_categories.ID, tbl_component_categories.folder_path, tbl_component_categories.comp_cat_name, tbl_components.component_name, tbl_components.image_filepath, tbl_components.component_category, tbl_components.ID AS comp_id
FROM tbl_components
JOIN tbl_component_categories ON tbl_components.component_category = tbl_component_categories.ID
AND tbl_component_categories.ID = $var
JOIN tbl_component_to_component ON $choicetest = tbl_component_to_component.component_ID AND tbl_components.ID = tbl_component_to_component.compatible_component_ID";

}


// echo $query_text;



array_push($_SESSION['options_picked'],$choicetest);
// need to add in category.
// choice test =  e.g. tactical buttstock



include("database connection link");

$query = $query_text;

$result = mysql_query($query)
or die(mysql_error());


// create templates
$ExpandTemplate = <<<OutHTML

		<img style="position:relative;top:-2px;" src="images/structural/red-plus.gif" /> %1\$s <!--</a>-->
		<br><form name="aliasbuilder" id="aliasbuilder" action="" method="post">

OutHTML;


$ExpandImageTemplate = <<<OutHTML	
				<button type="submit" name="chosen" id="chosen" value="%5\$s">
				<img src="%3\$s" width="147" height="34" alt="image to come" title="choice" />
				</button>
				<input type="hidden" name="what_category" value="%2\$s">
				<!-- this hidden field is what I can use to determine what category, I compare it to -->

OutHTML;


$Output = '';

//output section and sprintf

while ($row = mysql_fetch_assoc ($result)) { 

	if ($category != $row['component_category']) { 
	$category = $row['component_category'];	
	if (!$firstime) { 

			$Output .= '<br><br>';

			} else { 
			$firstime = true;
			}


	$Output .= sprintf ($ExpandTemplate, htmlspecialchars ($row['comp_cat_name']), htmlspecialchars ($row['folder_path']));
	}


$Output .= sprintf ($ExpandImageTemplate, htmlspecialchars ($row['comp_cat_name']),htmlspecialchars ($row['folder_path']),htmlspecialchars ($row['image_filepath']),htmlspecialchars ($row['component_name']),htmlspecialchars ($row['comp_id']));

// when I get a chance, I need to figure out how to escape the /s in the image_filepath in code line above. It wasn't working when it was written: htmlspecialchars (rawurlencode($row['image_filepath'])). it just put %s

}


?>







<script language="javascript">AC_FL_RunContent = 0;</script>
<script src="js/AC_RunActiveContent.js" language="javascript"></script>
<link href="includes/mcm.css" rel="stylesheet" type="text/css" />
<div id = 'content'>
<table width="800" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class='subnavbg' width="148" align="left" valign="top">

<? 

$sublinks = '2';
$sublinks2 = '2';
$nav='branch2';

include ('content/subnav-alias2'.$test.'.php');?>


        </td>
        <td align="center" valign="top"><table width="652" border="0" cellspacing="0" cellpadding="0">
            <tr>
        <td align="center" valign="top" class='contentbody'>
        <table width="625" border="0" align="center" cellpadding="0" cellspacing="0">
	<tr>
                  <td ><p class="contenttitlered">BUILD YOUR OWN ALIAS</p>
                  <p class="">Aasdfasdfasdf S</p></td>
			  <td colspan="2" align="right" valign="top"><span class="topictitle">
			   

			  </span></td>
                </tr>
                <tr>
            <td align="left" valign="top" class='contenttext' colspan='2' >
<?php

echo $Output;
echo "<br><br><input id='reset' name='reset' type='submit' onClick='window.location.reload()' value='Start over!'></form>";
echo "</div>";

?>


<!-- now show the results of what they've picked so far   --------------   This Is The Section I've Been Asking About. -->
<?php

$query_cats  = "SELECT ID, folder_path, comp_cat_name FROM tbl_component_categories";

// echo $query_cats;

$result = mysql_query($query_cats)
or die(mysql_error());

$results_done = $_SESSION['options_picked'];


echo "<div style='background-color:#000;width:170px;padding:15px; margin:10px;float:left;posiiton:absolute;Top:-100px; right:10px;'><font color='#ffffff'> <h3>You've chosen</h3>";
   
print_r($results_done);


// adding suggested switch solution. 


foreach($results_done as $key => $val) {
echo $key." and ".$val;

switch($key) {
 case 0:
        $q_cat = 4;
        break; // Without this statement, the page would continue checking the other cases, albeit, they would all get evaluated as false	

    case 1:
        $q_cat = 4;
        break; 
    case 2:
        $q_cat = 1;
        break;
    case 3:
        $q_cat = 11;
        break;
    case 4:
        $q_cat = 2;
        break;
    case 5:
        $q_cat = 10;
        break;
    case 6:
        $q_cat = 9;
        break;
    default: // If the key is not 1-6, have a fallout. You can log the error, or do whatever you want.
        $q_cat = -1;


}

$query_cats = mysql_query("SELECT tbl_component_categories.ID, tbl_component_categories.folder_path, tbl_component_categories.comp_cat_name, tbl_components.component_name FROM tbl_components JOIN tbl_component_categories on $q_cat = tbl_component_categories.ID
where tbl_components.ID = $val");

if (!$query_cats) {
	   $message  = 'Invalid query: ' . mysql_error() . "\n";
	   $message .= 'Whole query: ' . $query_cats;
	   die($message);
}


	while ($row = mysql_fetch_array($query_cats)) { 

	echo $row['comp_cat_name'].": ".$row['component_name']."<br>";
	}

}

function RecursiveWrite($results_done) {
    	foreach ($results_done as $vals) {
        echo $vals['0'] . "\n";
        RecursiveWrite($vals['1']);
    	}


}
echo "</font></div>";

// Print_r($results_done);
   
   ?>



</td>
            </tr>
            <tr><td colspan=2><a name="b" id="b"></a><br />
            <span class="anchor">(<a href="#header">Return to Top</a>)</span><br />
		  <br />
		  <br />         </td></tr>
        </table></td>
      </tr>
    </table></td>
  </tr>
</table>

</div>

</body>
</html>


Link to comment
Share on other sites

Woa... You weren't kidding, that code is quite messy indeed. Not the worst I've seen, but it clearly shows that this has been a learning process for you. With some parts you've forgot along the way, such as separation of concerns (HTML output and PHP processing). :P

 

What I'd recommend you to do, is to refactor this code. Which means that you should take a step back, sketch out what you want it to do. (List of keywords on a piece of paper.) Then take the code, and rewrite it to smaller more atomized sections. Use functions to cluster code that's intrinsically linked, and utilize the added flexibility they give you to control the execution flow in detail.

For example: Have one function that shows the form, one that fetches the options (with any user-selections), and one that calculates the results.

 

Don't be afraid to completely rewrite your code, nor to define more functions. The trick is to reduce the task into the smallest individual "problems", but no further, then to solve each of those problems individually. All the while keeping track of what it does with the whole. It takes a bit of practise, but in my experience it's one of the most valuable skills in programming. ;)

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.