Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Php inside Php?

Can someone tell/show me how to use PHP inside PHP. I'm trying to make the URL of an image change depending on what value is in a MySQL database. Here's an example of what I'm trying to do. Bear in mind that $idx already has a value from the URL of the page.

<?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 would I make the source value, for the image, come from a different table?

like image 575
Joey Morani Avatar asked Aug 11 '26 23:08

Joey Morani


2 Answers

You can join data from multiple tables in a single 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
like image 107
Kris Avatar answered Aug 14 '26 14:08

Kris


You'd do another SQL query inside the while loop. I like 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 your original query, because you're still using the $result variable from the original query each iteration of the loop. So here I've prefixed them with "image_".

like image 28
Paige Ruten Avatar answered Aug 14 '26 12:08

Paige Ruten