Display image with URL from MySQL - php

I am using this code to display image from URL, but it is not working,
<?php
echo 'me'.'<br/>';
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
echo $result;
$row = mysql_fetch_row($result);
for ($i=0; $i<6; $i++){
//calling rows
echo '<td>';
//calling rows value for debugging purpose so that i can learn the process and check the output
echo $row[$i].'<br/>';
echo '<img name="myimage" src="<?php echo $row[$i]; ?>" width="60" height="60" alt="word" />';
echo '</td>';
}
?>
The result is, I get alt text only, and image is not displayed. also, I get error
Notice: Undefined offset: 1 in D:\wamp\www\demo\login\flashcard.php on
line 31
In my file
What I am trying is, to get 5 img url from database and display them in columns of a table..and what I guess is I am getting same img URL again and again...for 5 times..
Please give me guideline and tell me what I could be missing...

i have never seen someone loop through a query that way, i do it like this:
print "<table>";
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch LIMIT 5';
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
print '<tr>
<td>
<img name="myimage" src="'.$row[column_name_here].'" width="60" height="60" alt="word" />
</td>
</tr>';
}
print "</table>";
change column_name_here to the name of the column which store the image file name
edit: changed mysql_fetch_row to mysql_fetch_array <- that is why u got the same image all 5 times.

With mysql_fetch_row() your fetching the results one row at a time, since you only specified url_imgsrch in the SELECT statement, it will be an array with one single element, the value for url_imgrch. This is the reason for your error message. The for() loop tries to in turn read the first, second, etc up to fifth value of the array, which never gets updated with new information and always has only one element.
mysql_fetch_row() will return false when there is no more data to be read, you need to call it to fetch each new row of data, so what you want is to rewrite your code to something along the lines of this:
$sql = 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
while (false !== ($row = mysql_fetch_row($result))
{
echo '<td>';
echo '<img name="myimage" src=' . $row[0] . ' width="60" height="60" alt="word" />';
echo '</td>';
}
The first part is just as you've written, setting up the SQL query and fetching a resource pointer ($result) to with mysql_query().
In the next part the while() loop will run for as long as $row is not false, updating $row with new data for each run of the loop. Since mysql_fetch_row() fetches an numerically indexed array, you want to retrieve $row[0], it's the first (and only) column you requested in the SQL query. There are many ways of writing the while() loop, but this way quite common, and easy to read for other developers.

try this:
<?php
echo 'me'.'<br/>';
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
echo $result;
$row = mysql_fetch_row($result);
for ($i=0; $i<6; $i++)
{
//calling rows
echo '<td>';
//calling rows value for debugging purpose so that i can learn the process and check the output
echo $row[$i].'<br/>';
echo '<img name="myimage" src=' . $row[$i] . ' width="60" height="60" alt="word" />';
echo '</td>';
}
?>

Related

How to restrict number of cells per row in a html table from database with PHP

I am in the process of attempting to set up an e-commerce store for my website. I plan on having it split into three categories (this part is already working), and then listing items from a MySQL database to a table.
I already am familiar with how to use the MySQL LIMIT function to limit results, but I want it to list all items from the database that match the category to the table and restrict it to a maximum of three items per row.
i.e.
Table
Item1 Item2 Item3
Item4 Item5 Item6
Item7 etc. etc.
Due to how few items I am listing per category, pagination is not necessary.
How would I even begin to attempt to set this up properly with a while loop? I saw something about a slice function with PHP, but not sure if that would fit my needs.
I have the base while loop working as intended, I just am not sure where to begin to break the loop apart into different rows in the table. I did a google search, and most I found was something related to slicing, but it wasn't related to MySQL fetch array functions.
$sql = $db->query('SELECT * FROM store_items WHERE store_cat = "Apparel"');
if(is_object($sql) && $sql->num_rows > 0)
{
while($row = $result->fetch_array())
{
echo '<tr>';
echo '<td height="250">';
echo '<img src="" alt="" height="180" /><br />'.$row['store_name'];
echo '<br /><br />\$'.$row['store_price'].'<br />'.$row['store_desc'];
echo '<br /><href="">Add to Cart</a>';
echo '</td>';
echo '</tr>';
}
}
I wish to have the while loop output the data from the database in rows of 3 items each. Right now, it only outputs the data in 1 row, unless I run a different query for each row (and just as many while loops).
As, you want to display item with images. Try CSS Grid to display it. That way you will have more control over its layout regarding different screen sizes.
Here I am using, bootstrap grids, you can use different if you want.
$sql = $db->query('SELECT * FROM store_items WHERE store_cat = "Apparel"');
if(is_object($sql) && $sql->num_rows > 0)
{
echo '<div class="row">'; //Bootstrap Row
while($row = $result->fetch_array())
{
echo "<div class= 'col-md-4'>"; //Bootstrap Column
echo '<img src="" alt="" height="180" /><br />'.$row['store_name'];
echo '<br /><br />\$'.$row['store_price'].'<br />'.$row['store_desc'];
echo '<br /><href="">Add to Cart</a>';
echo '</div>';
}
echo '</div>';
}
In the code above, we are dividing the available width in three equal parts.
It's just styling issue your code is fine. If you just want to achieve this, avoid unnecessary codes or logics that will only slow down performance. This way you will have more option, you can style images and tags below it. There is other bootstrap classes for image thumbnails.
$row = fetch();
while($row) {
echo '<tr>';
for($i = 0; $i < 3; ++$i) {
echo '<td>';
if ($row) {
//print the card here
//then fetch next row
$row = fetch();
} else {
//nothing needs be done here, since you are just generating empty td tags
//to keep the table aligned - same number of columns in all rows.
//but you can place here something too.
}
echo '</td>';
}
echo '</tr>';
}
I highly recommend css grid for this. That way you would specify the number of items per row in your css & you wouldn't have to worry about appropriately placing the tr tag. I literally have to search for css grid every time i need to use it, and I'm on mobile so i don't have an example.
But with your current setup, you could do:
$count=0;
echo '<tr>';
while(...){
$count++;
//your other code
if ($count%3===0)echo '</tr><tr>';
}
echo '</tr>';
As i currently wrote it, you may end up with an empty row at the end, if there are items in multiples of 3. But I'm mobile right now, so I'll leave that to you.
You can try below. Defined a variable and checks modulus (%) then print tr open/close accordingly. See the comment in the below code for more details.
$sql = $db->query('SELECT * FROM store_items WHERE store_cat = "Apparel"');
if(is_object($sql) && $sql->num_rows > 0)
{
$index = 0; // Define variable for store the indexes
while($row = $result->fetch_array())
{
if($index % 3 == 0) echo '<tr>'; // Check modulus (%) of $index. Open tr if the modulus is 0
echo '<td height="250">';
echo '<img src="" alt="" height="180" /><br />'.$row['store_name'];
echo '<br /><br />\$'.$row['store_price'].'<br />'.$row['store_desc'];
echo '<br /><href="">Add to Cart</a>';
echo '</td>';
$index++; // Increment the value of $index
if($index % 3 == 0) echo '</tr>'; // Check modulus (%) of $index. Close tr if the modulus is 0
}
}
If you want to print 4 columns then just change the checking if($index % 3 == 0) to if($index % 4 == 0)

PHP MYSQL Table only display one row of results

I have a page where I am using a parameter in the URL as a filter for my SQL query.
I created a variable from the URL parameter:
$station = htmlspecialchars($_GET["station"]);
Then set up a conditional query depending on whether or not the URL parameter is set:
if(isset($_GET['station'])) {
$query = "SELECT * FROM song_of_the_day WHERE station = '$station'";
}
else {
$query = "SELECT * FROM song_of_the_day WHERE end_date >= CURDATE()";
}
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
Then I display the results in a table:
echo "<table width='758' border='0' cellpadding='10' cellspacing='0' class='myTable'>";
while($row = mysql_fetch_array( $result )) {
echo '<tr>';
echo '<td align="left" width="48">' . $row['station'] . '</td>';
echo '<td align="left">' . date('M j, Y',strtotime($row['end_date'])) . '</td>';
echo '<td width="24" align="left"><img src="http://yourligas.yourli.com/ad-inventory/edit.png" border="0"></td>';
echo '<td width="24" align="left"></td>';
echo "</tr>";
echo '</tbody>';
}
echo "</table>";
The query works find when the ELSE command uses the query, where I'm not relying on the parameter in my SQL, but the problem I am seeing when the URL parameter ISSET is only one row gets displayed from the query when there is more than one row that matches the criteria in the actual database. Does anybody know why this is happening?
Thank you
In this line, you appear to be consuming the first row of data while attempting to get the number of rows found:
$num_rows = mysql_fetch_row($result);
This removes the first row from your result cursor.
Instead, you probably meant to do the following:
$num_rows = mysql_num_rows($result);

What causes a query to exclude first record

PHP and MySQL:What causes a query to exclude the first record in a table:
for example i have a script like this:
$query = "SELECT * FROM cars WHERE car_name = 'BMW'";
$results = mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Vehicle Name:<th>";
echo "</tr>";
while($row = mysql_fetch_array($result)){
$name = $row['car_name'];
echo "<tr>";
echo "<td>$name<td>";
echo "</tr>";
}
echo "</table>";
All rows are returned except the first one.Please help a brother out folks.
Not an answer, but too long for a comment:
Let's take a peak at your table cars.
What does
$qs = array(
array('total #rows', 'SELECT Count(*) FROM cars'),
array('#BMW', "SELECT Count(*) FROM cars WHERE car_name='BMW'"),
array('#LIKE BMW', "SELECT Count(*) FROM cars WHERE car_name LIKE '%BMW%'"),
array('#car_names', "SELECT Count(*) FROM (SELECT distinct car_name as foo FROM cars) as bar")
);
foreach( $qs as $query ) {
echo $query[0], "<br />\r\n";
$result = mysql_query($query[1]) or die(mysql_error());
while ( false!==($row=mysql_fetch_row($result)) ) {
echo ' ', $row[0], "\r\n";
}
}
print if placed in your script instead of your posted code?
The output should be something like
total #rows<br />
6
#BMW<br />
2
#LIKE BMW<br />
3
#car_names<br />
4
BTW: the mysql_* extension is deprecated,
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
EDIT
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same name,
you must use the numeric index of the column or make an alias for the
column. For aliased columns, you cannot access the contents with the
original column name
You are using mysql_fetch_array and this is what it says in the documentation. I never use mysql* functions so I wouldn't have jumped to this type of conclusion quickly. Use mysql_fetch_assoc($results) and I'm 99% sure it will resolve your issue. The why this would be different is in the paragraph above from the documentation. I assume your first row is identical to at least 1 of the below rows. Which means it is very likely you're missing more than just the first one. May or may not be the case.
END EDIT
Add 4 things to your code.
echo "<tr>";
echo "<th>ID</th>"; // THIS
echo "<th>Vehicle Name:</th>"; // Add closing tags........
echo "</tr>";
echo mysql_num_rows($results); // THIS (compare this to your MYSQL output row count)
while($row = mysql_fetch_array($results)){ **THIS... you have $results set with query, but $result here*** make sure both are $results OR $result
$id = $row['YOUR_AI_ID']; // THIS
$name = $row['car_name'];
echo "<tr>";
echo "<td>$id</td>"; // THIS
echo "<td>$name</td>"; // Add closing tags.......
echo "</tr>";
}
Go go do now. Come back with results.

cannot display multiple image

Image cannot be displayed in html page.
for example code :
<?php
$id = $_GET['id'];
$data =mysql_query("select * from img_homestay WHERE id='$id'");
while ($row =mysql_fetch_array($data))
{
$location = $row['location'];
echo '<img src="'.$location.'" width=30% height=10%>';
echo '<td><div align="center">Delete</div></td>';
echo "<br>";
}
?>
One obvious mistake in your code is that the closing tag '>' is missing for img. So it needs to be
echo "<img src='$location' width='30%' height='10%'>";
Apart from this be sure $location var has the correct absolute or relative path picked from DB to show the image. Then, you are using $id in the query. Be sure this is not the unique ID in the img_homestay table, as that will only return you one row. I believe you want to fetch all the images for a particular post id, so ensure that you are using that ID only for the correct field in the query.
Another suggestion that done switch between double quote and single quote string notation in PHP. This will make your code hard to read and comprehend. In one echo statement you are using
echo " ";
and in next statement you are using:
echo ' ';
Try with this
<?php
$id = $_GET['id'];
$data =mysql_query("select * from img_homestay WHERE id='".$id."'");
while ($row =mysql_fetch_array($data))
{
$location = $row['location'];
?>
<img src="<?php echo $location;?>" width="30%" height="10%">
<td><div align="center">Delete</div></td>
<br>
<?php }
?>
<?php
$id = $_GET['id'];
$data =mysql_query("select * from img_homestay WHERE id='".$id."'");
while ($row =mysql_fetch_array($data))
{
$location = $row['location'];
echo '<img src="'.$location.'" width=30% height=10%>';
echo '<td><div align="center">Delete</div></td>';
echo "<br>";
}
?>
Your processing is wrong. Your query is select * from img_homestay WHERE id='$id' which means it's going to fetch a single row (I assume, because you're making a query based on an ID which, I again assume, is a unique key) so you actually don't need to use the while loop (if you intend to use single image).
Still, if that's not the case, you may need to use <tr> for each row, so maybe, try this:
$id = $_GET['id'];
$data =mysql_query("select * from img_homestay WHERE id=$id");
while($row=mysql_fetch_array($data)){
$location = $row['location'];
echo "<tr><td><img src='$location' width=30% height=10%>";
echo "<td><div align='center'><a href='#' imgid='$row[imgid]' class='delbutton' title='Click To Delete'>Delete</a></div></td>";
echo "</tr>";
}
?>
Also, I see, you're using td here which means, you're using table but I see no table tags. My guess is, there is some issue in table structure. A better check to see if you're image is being parsed or not would be to check the source code of the rendered HTML page. I'm sure you're getting the img tag in resulting HTML but it is not being rendered due to error in HTML structure so you better check and correct your HTML with respect to the table you're using.

Getting one result before the loop

I have a query which returns some results, and then I'm using a while loop to output the results.
The problem I'm having is that I want to return the 'question' before the while loop so that it doesn't display a number of times inside the loop.
I have the following code:
$query = "SELECT * FROM polls LEFT JOIN pollanswers ON polls.pollID = pollanswers.pollID WHERE polls.pollID = 1 ORDER By pollAnswerListing ASC";
$result = mysql_query($query);
echo '<p>Question</p>';
echo '<form action="#" class="poll-form">';
echo ' <p class="error"></p>';
echo ' <fieldset>';
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<div class="row">';
echo '<input type="radio" name="poll" id="'.$row["pollAnswerID"].'" class="radio" value="'.$row["pollAnswerID"].'" /><label for="'.$row["pollAnswerID"].'">'.$row["pollAnswerValue"].'</label>';
echo '</div>';
}
echo ' </fieldset>';
echo '</form>';
As you can see the loop is working perfectly, but how do I output the question just once from the same SQL statement BEFORE outputting the loop?
You can fetch one row to display your question (assuming you have the same question value for multiple rows), then use mysql_data_seek() to rewind the result resource back to the first record to start your loop:
// Retrieve the first row...
$first_row = mysql_fecth_array($result, MYSQL_ASSOC);
// Output your question however you need to...
echo "whatever...";
// Then rewind the result back to zero
mysql_data_seek($result, 0);
// Proceed with the rest of your while loop
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<div class="row">';
echo '<input type="radio" name="poll" id="'.$row["pollAnswerID"].'" class="radio" value="'.$row["pollAnswerID"].'" /><label for="'.$row["pollAnswerID"].'">'.$row["pollAnswerValue"].'</label>';
echo '</div>';
}
I believe you should not do it like that. The question itself should be retrieved separately, not with answers, because including it in every row of the database result is a waste of resources. Remember, that the data (result of the query) has to be passed from the database and what you do is effectively multiplying this data unnecessarily.
You may not hit the problem now, because it seems there is a small number of possible answers, but you should do it the right way.
In case you still want to do it as you mentioned, then below you can find two solutions regarding getting results before for loop.
Not including first row in for loop
If you do not want it to be included in the loop, just do the following before the loop:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
and use $row as you use $row within the loop.
Including first row in for loop
In this case you can use solution mentioned by #Michael (similarly as my first solution above, but using mysql_data_seek($result, 0) before for loop, so it starts from the beginning of the result again, including first row).
How about:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
if($row) {
echo '<p>Question</p>';
echo '<form action="#" class="poll-form">';
echo ' <p class="error"></p>';
// echo your poll name here somewhere...
echo ' <fieldset>';
do {
echo '<div class="row">';
echo '<input type="radio" name="poll" id="'.$row["pollAnswerID"].'" class="radio" value="'.$row["pollAnswerID"].'" /><label for="'.$row["pollAnswerID"].'">'.$row["pollAnswerValue"].'</label>';
echo '</div>';
}
while($row = mysql_fetch_array($result, MYSQL_ASSOC));
echo ' </fieldset>';
echo '</form>';
}
This also fixes another bug in your old when the MYSQL query returns an empty result set: your old code would generate a bogus form. (The fix is in that this code doesn't generate a poll form if there is no poll.)

Categories