/    Sign up×
Community /Pin to ProfileBookmark

PHP variable in Select

Simple problem here I just can’t get it…

I have 2 session variables

$cat1 = $_SESSION[‘catCheck1’];
$cat2 = $_
SESSION[‘catCheck2’];

In my SELECT, I have a for loop. All I want to do is get the variable names $cat1 and $cat2 passed to it like this:

[code]
for ( $i = 1; $i <= 2; $i++) {
$query = mysql_query(“SELECT * FROM category WHERE categoryID = $cat”.$i.” ORDER BY categoryName”);
[/code]

However, my select doesn’t like it and it select nothing. But if I put in the actual variable name like this, it works just great!

[code]
for ( $i = 1; $i <= 2; $i++) {

$query = mysql_query(“SELECT * FROM category WHERE categoryID =”. $cat1.” ORDER BY categoryName”);
while ($getName = mysql_fetch_array($query)) {
etc….
[/code]

What in the devil am I doing wrong with this select to get it to read the variable name right?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@bejitto101Nov 04.2008 — I don't believe you can call a variable by adding two variables together. Here's what your select is processing. It first looks at the $cat. Since this variable doesn't exist, you get nada. The $i returns either one or two. So your query is "SELECT * FROM category WHERE categoryID = 1 ORDER BY categoryName".

Here's a way to accomplish what I think you want:

[code=php]
$cat[] = $_SESSION['catCheck1'];
$cat[] = $_SESSION['catCheck2'];

for ($i = 0; $i <= 1; $i++) {
$query = mysql_query("SELECT * FROM category WHERE categoryID = ".$cat[$i]." ORDER BY categoryName");[/code]


Or keep the $cat the same and use:

[code=php]
foreach ($cat as $sub_cat) {
$query = mysql_query("SELECT * FROM category WHERE categoryID = $sub_cat ORDER BY categoryName");[/code]
Copy linkTweet thisAlerts:
@Patty5authorNov 05.2008 — Putting $cat in an array and using the for loop worked like a charm! You are brilliant! Problem solved!

Thanks so much!
×

Success!

Help @Patty5 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...