November 25th, 2012, 12:39 PM
How to ger $id in foreach command
I have a piece of code:
<?php foreach($movies as $movie): ?>
<td><a href='$_SERVER[PHP_SELF]?id=$id'><?=$movie->moviename ?></a></td>
<?php endforeach; ?>
I would like to turn moviename into link on webpage and when i click that link i get that movie id from my database. At the moment i get in addressbar: My functions are in different file and i also want to sort and search by categories so that situation confuses me. I can sort and sear at the moment.
Thanks very much for help
November 25th, 2012, 12:56 PM
I'm not too familiar with the colon type layout of loops, but from what you have, it seems you're already doing what you need, just not for the $id. I'm assuming moviename, categoryname, and description are all columns just like id would be. Why not call/reference it the same as the rest?
November 25th, 2012, 01:35 PM
The problem is when i hover mouse on that link instead of .../catalog?id=2
I get on addressbar .../catalog/$_SERVER[PHP_SELF]?id=$id
November 25th, 2012, 01:45 PM
Your variables are in an HTML area. PHP hasn't been defined...
November 25th, 2012, 02:01 PM
TN is right, instead of this:
Originally Posted by Triple_Nothing
You need to do:
Please remember to wrap your code with PHP tags
<a href='<?= $_SERVER[PHP_SELF] . '?id=' . $id ?>'>
November 25th, 2012, 02:16 PM
And if you are going to be using variable throughout your HTML, you can avoid opening and closing PHP all the time by writing this within an echo.
Sorry if I kinda got the single/double quotes backwards...
foreach($movies as $movie):
<td><a href='" . $_SERVER[PHP_SELF] . "?id=" . $id . "'>" . $movie->moviename . "</a></td>
<td>" . $movie->categoryname . "</td>
November 25th, 2012, 05:26 PM
I've certainly done it the way that TN showed, but I think if you are sprinkling php into html opening and closing makes it a bit easier to read in most code editors. Plus code editors will be able to match opening and ending tags. Obviously it depends on the context of what you are doing, but if you look at most frameworks, if you are working in the view (where most of the html is), you open and close just what you are echoing out, control structures like your foreach, etc.