How do I use Php inside Php?
Can someone tell / show me how to use PHP inside PHP. I am trying to change the url of an image depending on what the MySQL database is. Here is an example of what I am trying to do. Be aware that $ idx already has a value from the page url.
<?php
$query = "SELECT * FROM comment WHERE uname='$idx'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<img src='' name='comm' width='75px' height='60px' id='mainimage' />";
}
?>
How do I initialize an image from another table?
a source to share
In the loop, while
you would execute another SQL query. I love how you put it, "Php inside Php", that's pretty much what you do.
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$image_query = "SELECT image_url FROM your_table";
$image_result = mysql_query($image_query);
$image = mysql_fetch_assoc($image_result);
echo "<img src='" . $image['image_url'] . "' name='comm' width='75px' height='60px' id='mainimage' />";
}
Make sure the variable names for your query and result are different from the original query, because you are still using the variable $result
from the original query for each iteration of the loop. So here I am prefixing them with "image_".
a source to share
You can combine data from multiple tables in one SQL query. See: http://www.w3schools.com/sql/sql_join.asp
Example:
SELECT column_name(s)
FROM table_name1
JOIN table_name2
ON table_name1.column_name=table_name2.column_name
a source to share
Assuming under the random assumption that the other table might be called accounts
and uname
is its primary key, you can do JOIN
to grab data from both tables in one go. If you can match what you want to do in a single query, that is usually much faster than doing an additional query in a row
<?php
$result = mysql_query(
"SELECT comment.*, account.url AS imgurl ".
"FROM comment JOIN account ON comment.uname=account.uname ".
"WHERE comment.uname='".mysql_real_escape_string($idx)."'"
);
?>
<?php while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<img src="<?php echo htmlspecialchars($row['imgurl']) ?>" alt="" class="mainimage" />
<?php } ?>
Notes:
-
you need to avoid the text that you insert into the SQL query, or you have serious security issues. Use
mysql_real_escape_string
, or let parameterized queries be processed; -
Likewise, when text fits into an HTML string, you need
htmlspecialchars
or have other (less serious, but still good) security concerns; -
you shouldn't use the same
id
for an element more than once (which will be in a loop). The same can be said forname
on<img>
, although you have few reasons why you would really want to useimg name
; -
width="75px"
will not work on the attribute, sincepx
-general is CSS, not HTML. Omit the block, or better, set a rule in CSS (.mainimage { width: 75px; height: 60px; }
) to do it all at once.
a source to share