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?
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
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_".
Assuming at a random guess that the other table might be called accounts, and uname is its primary key, you can do a JOIN to grab the data from the both tables in one go. If you can fit what you want to do in a single query that's typically much faster than doing an extra query per 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 escape text you insert into an SQL query, or you've get serious security problems. Use mysql_real_escape_string, or let parameterised queries handle it;
similarly when putting text into an HTML string, htmlspecialchars is needed or you've got other (less serious, but still not good) security issues;
you mustn't use the same id on an element more than once (which it will be, in a loop). The same goes for name on <img>, although there's little reason you'd really ever want to use img name;
width="75px" won't work in an attribute as px-unit measurements are CSS not HTML. Omit the unit, or, better, set a rule in CSS (.mainimage { width: 75px; height: 60px; }) to do them all at once.
How would I make the source value, for the image, come from a different table?
You have to simply ask the different table. You can ask by creating subquery (or join) or create second query inside loop.
Related
I have this code:
<?php
$data = mysql_query("SELECT * FROM repin WHERE new_pin_id LIKE ".$pinDetails->id) or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
?>
Obtained thanks to this article: Check field for identical number
I'm trying to use the detail I pulled: ".$info['from_pin_id']." to get data from another table. I'm looking for the best way to do this.
I thought about making it a variable and then running a second statement within the same <?php?> which would look something like this:
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
$newdata = "".$info['from_pin_id']."";
// new statement here.
?>
But 1. it won't work and 2. it looks messy.
What is the best way to achieve it?
FYI, what I need to do is use ".$info['from_pin_id']." to match a field in another table where the data is the same ID, then pull more info based on the match.
Use the following query:
"SELECT *
FROM repin r
LEFT JOIN otherTable o
ON o.someColumn = r.from_pin_id
WHERE r.new_pin_id LIKE '".$pinDetails->id."'"
Also, the argument to LIKE must be a string; you need to put quotes around it.
I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.
I'm sure my inability to solve this problem steams from a lack of knowledge of some aspect of php but I've been trying to solve it for a month now with no luck. Here is a simplified version of the problem.
In my database I have a members table, a childrens table (the children of each member), and a friend requests table (this contains the friend requests children send to each other).
What I'm attempting to do is display the children of a particular parent using the following while loop....
$query = "SELECT * From children " . <br>
"WHERE parent_member_id = $member_id"; <br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_children = mysql_num_rows($result);<br>
echo $num_children;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
<div>echo $first_name<br>
}
This while loop works perfectly and displays something like this...
1) Kenneth
2) Larry
What I'm attempting to do though is also display the number of friend requests each child has next to their name...like this
Kenneth (2)
Larry (5)
To do this I attempted the following modification to my original while loop...
$query = "SELECT * From children " .<br>
"WHERE parent_member_id = $member_id";<br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_movies = mysql_num_rows($result);<br>
echo $num_movies;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
echo $first_name; include('counting_friend_requests.php') ;
}
In this version the included script looks like this...
$query = "SELECT <br>children.age,children.child_id,children.functioning_level,children.gender,children.parent_member_id,children.photo, children.first_name,friend_requests.request_id " .
"FROM children, friend_requests " .
"WHERE children.child_id = friend_requests.friend_two " .
"AND friend_requests.friend_one = $child_id"; <br>
$result = mysql_query($query)<br>
or die(mysql_error());<br>
$count = mysql_num_rows($result);<br>
if ($count==0)<br>
{<br>
$color = "";<br>
}<br>
else<br>
{<br>
$color = "red";<br>
}<br>
echo span style='color:$color' ;<br>
echo $count;<br>
echo /span;<br>
Again this while loop begins to work but the included file causes the loop to stop after the first record is returned and produces the following output...
Kenneth (2)
So my question is, is there a way to display my desired results without interrupting
the while loop? I'd appreciate it if anyone could even point me in the right direction!!
Avoid performing sub queries in code like the plague, because it will drag your database engine down as the number of records increase; think <members> + 1 queries.
You can create the query like so to directly get the result you need (untested):
SELECT child_id, first_name, COUNT(friend_two) AS nr_of_requests
From children
LEFT JOIN friend_requests ON friend_one = child_id OR friend_two = child_id
WHERE parent_member_id = $member_id
GROUP BY child_id, first_name;
It joins the children table records with friend_requests based on either friend column; it then groups based on the child_id to make the count() work.
You don't need to include the php file everytime you loop. Try creating a Person class that has a method getFriendRequestCount(). This method can all the database. This also means you can create methods like getGriendRequests() which could return an array of the friend requests, names etc. Then you could use count($myPerson->getFriendRequests()) to get the number. Thousands of options!
A great place to start, http://php.net/manual/en/language.oop5.php
Another example of a simple class, http://edrackham.com/php/php-class-tutorial/
Eg.
include ('class.Person.php');
while(loop through members)
$p = new Person(member_id)
echo $p->getName()
echo $p->getFriendRequestCount()
foreach($p->getFriendRequests as $fr)
echo $fr['Name']
In your Person class you want to have a constructor that grabs the member from the database and saves it into a private variable. That variable can then be accessed by your functions to proform SQL queries on that member.
Just to clarify whats happening here.
"include" processing is done when the script is parsed. Essentially its just copying the text from the include file into the current file. After this is done the logic is then parsed.
You should keep any include statements separate from you main logic. In most cases the "include"d code will contain definitions for one or more functions. You can then call these functions from the main body of your program at the appropriate place.
I have an existing recordset that retrieves all the information from a table in mysql called $rrows. What I am hoping to do is to use this existing recordset within a new mysql query.
For example I have the following line that retrieves the "product code" from one table:
<?php echo $rrows['productcode']; ?>
I am trying to then gather the respective images from a new table using this productcode by something similar to:
<img src="<?php
mysql_select_db("dbname", $con);
mysql_set_charset('utf8');
$result = mysql_query("SELECT * FROM furnimages WHERE productcode='$rrows['productcode']'");
while($row = mysql_fetch_array($result))
{
echo '' . $row['photo'] . '';
}
mysql_close($con);
?>">
Can this be done? Originally I was going to LINK tables together to get all the information, but this doesnt work as some of the product codes in the main do not have corresponding data in the 'furnimages' table.....
Thanks in advance!
JD
sprintf() is your best friend here.
$sql = <<<sql
SELECT * FROM furnimages
WHERE productcode=%d
sql;
$result = mysql_query(sprintf($sql, $rrows['productcode']));
So, %d is the placeholder in the string to swap in the second argument in the call to sprintf();
%d denotes an integer placeholder; if $rrows['productcode'] is a string, use %s.
This is better than simply quoting value of the variable as it adds a type constraint which reduces the risk of nasty sql injection.
It also makes it eminently more readable.
Check out the PHP Data Objects extension, though, because that really is the only way forward for this type of thing.
I actually have a few questions here: My end goal is to write a script that will automatically display all the images that i have saved inside my database(If i add new images to my database(image URLs), each time i refresh the page i would like those "new" images to be instantly displayed as well).
What is the proper way to save an image URL inside MySQL? Currently i set my input type to VARCHAR; is that okay for image URLs?
Also, at the moment i'm working with WAMP server just to test how the site is working; so i put an image inside the www folder(within the same folder as my php script) and inside the database table i simply put the URL as follows: image.png is this the correct way to enter an image URL inside my database?
What is the best way to display these images in a sequence? The following code is what i have so far:(the image widths will take up about 70% of the page so the images will not be next to each other; they will be in a column form.)
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
for($count = 0; $count < $num; $count++)
{
//output the rows one by one(the actual images, not the URLs)
mysql_fetch_row($result);
echo("<br/>");
}
?>
I don't know if i should be using mysql_fetch_row in there..
I want my images to have some space in between; i was thinking the best way to accomplish that would be to add a "br" tag at the end of my loop so that every time a new image is displayed, a line break will be added to the end of the page.. Is that the best way to do it?
Thanks a bunch in advance!
To your first question, yes. To your second, also yes, if all your images are stored in the same directory. Mostly it's a matter of preference though.
Your for loop should look like this:
for($count = 0; $count < $num; $count++) {
$row = mysql_fetch_assoc($result);
echo "<img src='". htmlspecialchars($row["image"]) ."' alt='image' />";
}
br tags would probably be a bad idea. Set the images' display property to block in your CSS file. There are plenty of CSS manuals online.
With
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
you do some things twice. You do not want $query to be the result of a mysql_query() call and then apply mysql_query() again.
In this case, the second call would happen with a resource object instead of a string - you got informed about it. By putting "" around, you turn it into a string again, but one which doesn't make sense to mysql.
To verify that, try to put or die(mysql_error()) to the problematic calls.
And to fix that, you can try
$query = "SELECT * FROM tablename";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
BTW: you don't need $num when you replace the for loop with
while ($row = mysql_fetch_row($result))
// do stuff with $row
}
I've done a previous project based on image storage in a SQL database. the best way to store the images would be as a link, ie, '/stored_images/imagefilename.png'. When you need to reference the images just get the images into a while loop for each row in the table.
ie.
to get the images
<?php
$query = mysql_query("SELECT * FROM tablename");
while ($row = mysql_fetch_array($query)) {
echo '<img src="' . $row['column of url storage in SQL'] . '" />';
}
That will output all the images in the database, just change 'column of url storage in SQL' with the actual column name that you store in the SQL DB. also replace 'tablename' in the SQL query with the name of the table the images are being stored in.