Using PHP/MySQL to insert information into DIVs - php

Okay, so what I am trying to achieve is a "News Feed" type of thing with PHP and a MySQL database. I have the database and tables setup, and a CMS setup that inserts info into the database, and have successfully called individual rows of the table into my HTML layout using the SELECT statement.
Now, what I am trying to do is have a home page, which contains 12 divs, each one being an image that links to an individual post page, and dynamically generated from my table in DESC order. That way, the 12 most recent designs are displayed on the homepage.
Then, I want to achieve the same type of thing except on a page that is sorted by category, which I am assuming would be done by adding a WHERE category=categoryname to my SELECT statement. Just hoping someone with more knowledge could give me some guidance on how to proceed with this.
Here's my HTML (I inserted Needs to be dynamically generated in the links and img src):
/* Other relevant Code */
<div class="homeContent">
<div class="newsItems">
<div class="newsItem1">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem2">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem3">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem4">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem5">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem6">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem7">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem8">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem9">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem10">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem11">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
<div class="newsItem12">
<img src="**Needs to be dynamically generated**" alt="" class="newsItem" />
</div>
</div>
</div>
I haven't gotten very far with the PHP for this part, as I am not sure which direction to go, and I have slowly learned that if you choose the wrong direction with PHP it usually involves starting over. Thanks in advance for any help!
Long Story Short, how can I get the img src and links to be dynamically generated into these predefined DIVs from a MySQL table using PHP, and get them to be in DESC order?

The following code will take the data from your database and display a new <div>, link, and image.
Image.php:
<?php
$query = "SELECT id, link, image FROM images ORDER BY id DESC";
?>
<html>
<body>
<?php while($row = mysql_fetch_assoc($query)): ?>
<div class="NewsItem<?php echo $row['id']; ?>">
<img src="<?php echo $row['image']; ?>" alt="" class="newsItem" />
</div>
<?php endwhile; ?>
</body>
</html>
This assumes you have a table with the following columns:
ID (AUTO INCREMENT) INT
image TINYTEXT - URL to image file
link TINYTEXT - Link to where you want the link to go.

This answer assumes you have the following:
A MySQL connection in PHP (here, this is stored in the $sql variable).
image_src, url, and created_at columns in your MySQL table (we'll call the table my_table).
Querying for Everything
First off, let's go over the query.
We want to get all the data for all twelve rows at the same time so we don't have to query multiple times. We also want everything ordered in a descending fashion, which is where created_at comes into play.
It could look something like this:
SELECT m.image_src, m.url, m.created_at
FROM my_table AS m
ORDER BY m.created_at DESC
LIMIT 12
Let's store this query in a variable. We'll make it simple and call it $query
$query = /* The query we just wrote above */
Displaying the Results
Now we just have to figure out how to make the result look nice. I'll assume you know how to run the query, seeing how you've managed it already.
Looking at your example, we want each result to be in it's own div element, with a unique class attribute. I would recommend making those into ids instead, since they will be unique. We can add a newsItem class to each one instead.
To do what we want, we'll create a while loop to iterate over each row and print out the appropriate HTML. It could look like this:
<div class="newsItems">
<?php
$result = $sql->query($query);
$count = 0;
while(null !== ($r = $result->fetch_assoc()): ?>
<div id="newsItem<?php echo ++$count; ?>" class="newsItem">
<img src="<?php echo $r['image_src']; ?>" alt="" />
</div>
<?php
endwhile;
?>
</div>
A Couple of Things
Take careful notice of the while condition. With new versions of PHP, it is important that you compare the $r variable against a null value. It used to be possible to use false instead, but now that it isn't, a statement like this one will throw an error:
while(false !== ($r = $result->fetch_assoc())):
Be careful with your statements.
Note how we only put the newsItem class on the div elements. Because the a and img tags are inside of the div, you can select either of them using .newsItem a or .newsItem img in your stylings.
If you have a series of unique classes, it is better to make them ids than classes for clarity. There is no point in having a class that only gets used once.
Enjoy and good luck with your project!

Related

how to call columns from database and format it with HTML code

Actually I am beginner programmer in HTML, CSS and PHP. I have simple website for add and register in courses. The user should be add course into website and the courses should be posted on the site.so users can browse and register.
Actually my problem is how to call the course name from database and how to format it with HTML code as I want.
This is the page of courses which is content the list of available courses in website ( please note it is only HTML code, I do that to see how the page will be )
Screenshot of page:
So as you see, the first page include many this HTML code to add course list into website with the following code:
<div class="card card-1">
<a href="http://127.0.0.1/project2/course details/course1.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% "></a> <div class="container">
<h4 class="textstyle"><b>Operating System</b> </h4>
<p class="textstyle">Free Course</p>
</div>
</div>
what i want do with PHP?
I want to write a PHP code to replace the P and h4 with the course name, cost of courses from my database for each available course.
Please note: the pic for each course it will be from my pc, no need to call the pic from database.
I tried to write PHP code like below:
<div>
<div class="card card-1">
<a href="http://127.0.0.1/project2/course details/course1.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% "></a> <div class="container">
<?php
include_once("db.php");
$result = mysqli_query(OpenCon(), "SELECT Course_Name,cost FROM `course`");
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<p>".$res['Course_Name']."</p>";
echo "<p>".$res['cost']."</p>";
}
?>
</div>
</div>
</div>
This is my result:
It's okay but I want the style to be like the first screenshot. each course should have picture.
After that when the user click on course name. I want move to another page which is content the course details ( for the same course that user clicked ) also it's called for my database
like this:
I hope any one help my to solve this problem only, I should solve this problem within 2 days only. and sorry if my explanation is bad.
Thanks in advance for everyone.
Put the code in a PHP loop.....
So, this
<div class="card card-1">
<a href="http://127.0.0.1/project2/course details/course1.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% ">
</a>
<div class="container">
<h4 class="textstyle"><b>Operating System</b> </h4>
<p class="textstyle">Free Course</p>
</div>
</div>
Becomes (after cleaning up the code a bit - I think you didn't mean to use two <p> in there, but I left them so you can see it. Note that using different lines for the segments makes it a lot easier to see what you have.)
include_once("db.php");
$result = mysqli_query(OpenCon(), "SELECT Course_Name,cost FROM `course`");
$count = 0;
while($res = mysqli_fetch_array($result)) {
$count ++;
// NOTE: Here is the LOOP! - not outside the query, but INSIDE it
// First you 'jump out' of PHP, going back to HTML
?> <!-- now you are in HTML (when you need PHP again, you 'jump in' and 'jump out' as needed - see the code below....) -->
<div class="card card-<?php echo $count;?>">
<a href="http://127.0.0.1/project2/course details/course<?php echo $count;?>.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% ">
</a>
<div class="container">
<h4 class="textstyle">
<b><p><?php echo $res['Course_Name'];?></p></b>
</h4>
<p class="textstyle">
<p><?php echo $res['cost'];?></p>
</p>
</div>
</div>
<?php // we are in PHP again....
}
That should do what you asked for - though I would go a step (well, more than one...) further and make as much of this dynamic as you can.
For this I will presume that:
your database table has a column called 'id' (if it doesn't, you should have) and it relates to the course number (you could make a course number column if they don't match up, but I'm keeping it simple)
you have all your pictures labeled 'coursepicX' where the X is the course number.
We'll use 'coursepic' as a default in case there isn't a picture yet...
Now, the code is more dynamic!
include_once("db.php");
$result = mysqli_query(OpenCon(), "SELECT id,Course_Name,cost FROM `course`");
while($res = mysqli_fetch_array($result)) {
// NOTE: Here is the LOOP! - not outside the query, but INSIDE it
// First you 'jump out' of PHP, going back to HTML
?> <!-- now you are in HTML (when you need PHP again, you 'jump in' and 'jump out' as needed - see the code below....) -->
<div class="card card-<?php echo $res['id']?>">
<a href="http://127.0.0.1/project2/course details/course<?php echo $res['id']?>.php">
<?php
$pic = "http://127.0.0.1/project2/icons/coursepic.jpg";
if(file_exists("http://127.0.0.1/project2/icons/course" . $res['id'] . ".jpg") {
$pic = "http://127.0.0.1/project2/icons/course" . $res['id'] . ".jpg";
}
<img src="<?php echo $pic; ?>" alt="Avatar" style="width:101% ">
</a>
<div class="container">
<h4 class="textstyle">
<b><p><?php echo $res['Course_Name'];?></p></b>
</h4>
<p class="textstyle">
<p><?php echo $res['cost'];?></p>
</p>
</div>
</div>
<?php // we are in PHP again....
}
Note that this is the basic 'shopping cart' sort of program - you will likely use it many (many) times in your career.
Happy Coding!

Getting div value (content/text) using XPath

I have next html structure:
<li id="REQUIRED_ITEM_1" class="listing-post">
<a class="listing-thumb" href="blah" title="blah" data-palette-listing-image="">
<img src="REQUIRED_ITEM_2" width="75" height="75" alt="blah"> </a>
<div class="listing-detail ">
<div class="listing-title">
<div class="listing-icon hidden"></div>
blah
<div class="listing-maker">
<span class="name wrap">blah</span>
</div>
</div>
<div class="listing-date">
REQUIRED_ITEM_6
</div>
<div class="listing-price">
Sold
</div>
</div>
</li>
There are few dozens of these <li> on the same page, all with different id and content. The content that I need is marked REQUIRED_ITEM_1 - REQUIRED_ITEM_6.
I am collecting the data from these <li>s with the help of Xpath.
Here is the code I use:
foreach($xpath->query("//li[#class='listing-post']") as $link) {
$REQUIRED_ITEM_1 = $link->getAttribute('id');
$REQUIRED_ITEM_2 = $xpath->query(".//img", $link)->item(0)->getAttribute('src');
$REQUIRED_ITEM_3 = $xpath->query(".//a", $link)->item(1)->getAttribute('href');
$REQUIRED_ITEM_4 = $xpath->query(".//a", $link)->item(1)->getAttribute('title');
$REQUIRED_ITEM_5 = $xpath->query(".//a", $link)->item(2)->getAttribute('href');
$REQUIRED_ITEM_6 = $xpath->query("./div/text", $link)->item(4);
}
It works as intended for the first 5 REQUIRED_ITEMs, however it seems the code to get text contained within listing-date div (REQUIRED_ITEM_6) is wrong.
Also, is this the best way to parse my html and collect data, or is there a better approach?
Here is the xPath to get REQUIRED_ITEM_6
//li[#class='listing-post']//div[#class='listing-date']/text()
That would be little bit faster (but first version may be more safe, since it is less dependent on XML structure).
//li[#class='listing-post']/div/div[#class='listing-date']/text()
So your code must look like something like this (but you may need to adjust it little bit with your php, not sure why you used item(4)).
$REQUIRED_ITEM_6 = $xpath->query(".//div[#class='listing-date']/text()", $link)->item(0)->textContent;

How to avoid images being displayed in one column

I am developing a gallery website where users can visit images that other people have shared. I have created the gallery and images can be viewed using thumbnails and the images upload from the right of the previsous image. If an image is at the edge of the page the next image will go in the row beneath it. I use this code to do this:
<?php
mysql_connect("localhost","root","");
mysql_select_db("pardeepsandhu");
$res= mysql_query("select * from images");
$row=mysql_fetch_array($res)
?>
<div id="w">
<div id="content">
<div id="images"><?php while ($row=mysql_fetch_array($res)){?>
<img src="<?php echo $row["Image"]; ?>" height="134.1175" width="134.1175" border="5" alt="turntable" />
<?php } ?>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#images a').lightBox();
});
</script>
However, i am now trying to get a voting system set up. At the bottom of each image there would be a button which will give an image a like. The button works however the images, with the buttons, are being laid out differently. All the images appear one beneath the other, it looks like they are in on column. I don't want this to happen as space will be wasted. This is the code with a button:
<div id="w">
<div id="content">
<div id="images"><?php while ($row=mysql_fetch_array($res)){?>
<img src="<?php echo $row["Image"]; ?>" height="134.1175" width="134.1175" border="5" alt="turntable" />
<form id="form1" name="form1" method="post" action="">
<input type="submit" name="button" id="button" value="Like this image" />
</form>
<?php } ?>
How do I get the images to load like they did before, so that they appear in rows rather than in one column. Can anyone help me?
To achieve a horizontal layout, you will need to use the css "display:inline-block;" on all of your image / link containers. If I were you, I would have another div which contains all the image and voting info. Also, please make sure you are closing all of your divs as this can dramatically change your layout.
Something along the lines of this should get them horizontal.
<div id="pic" style="display: inline-block;">
<img src="">
<form></form>
</div>
http://jsfiddle.net/u9gSD/

Php to auto populate grids

I have the following html code:
<div class="media row-fluid">
<div class="span3">
<div class="widget">
<div class="well">
<div class="view">
<img src="img/demo/media/1.png" alt="" />
</div>
<div class="item-info">
Title 1
<p>Info.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
<div class="widget">
<div class="well">
<div class="view">
<img src="img/demo/media/2.png" alt="" />
</div>
<div class="item-info">
This is another title
<p>Some info and details go here.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
</div>
Which basically alternates between a span class with the widget class, and then the widget class without the span3 class.
What I wanted to know was if there was a way to have php "echo" or populate the details for and details under the "item-info" class. Would I need to use a foreach statement to get this done? I would be storing the information in a mysql database, and while I can get it to fill in the info one by one (repeatedly entering the and echoing out each image and item title) it's not practical when the content needed to be displayed is over 15 different items. I'm not well versed in foreach statements so I could definitely use some help on it.
If someone could help me perhaps structure a php script so that it can automatically output the html based on the number individual items in the database, that'd be greatly appreciated!
I'm wondering if the html + php (not including the foreach) would look like this:
<div class="span3">
<div class="widget">
<div class="well">
<div class="view">
<img src="img/<? $file ?>" alt="" />
</div>
<div class="item-info">
<?$title?>
<p>Info.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
EDIT:
I wanted to add some more information. The items populated would be based on a type of subscription - which will be managed by a group id.
I was initially going to use <? (if $_SESSION['group_id']==1)>
echo <div class="item-info">
$title
<p>$info</p>
</div>
so that only the subscribed items would populate. But, I would need it to iterate through all the items for group1 table and list it. Currently I know that I can do
<? (if $_SESSION['group_id']==1)
while ($row=mysql_fetch_assoc($sqlItem))
{
$itemInfo = $row['info'];
$image = $row['image'];
$title = $row['title'];
$url = $row['url'];
};
>
$sqlItem for now can only be assigned one thing (manually - as in: $sqlItem = '123'), unless I iterate through which is what I'm trying to figure out.
Just read that 'mysql_fetch_assoc' is being depreciated with 5.5, here is the new way and looks better, easier I think.. Hope this helps, was updated today.
I hope this helps http://php.net/manual/en/mysqli-stmt.fetch.php
replace the printf with echo '//then your html stuff
This will iterate through the rows in your database until their are no more matching records.
shouldn't a while be enough? It depends on the structure of your database and website (we didn't need so much HTML I think. Some more PHP maybe). Hope this helps.

PHP Fancybox same ID

This may seem like a weird request, but this is something I have to use based on something I have been provided that is live.
I have a voting system that uses an id for the voting button based on the entry id, so the code looks like:
<div class="like_wrap">
<div class="vot_plus" id="vt_img41"></div>
</div><!--like_wrap-->
This works how I need it to, however when you click the image within the vote it opens up a larger picture of the entry (again this works), but the client would like to add that vote to the fancybox popup. However when this is added it removes all references as it is calling the same ID twice. Any idea how I can get the voting button to appear on both, but actually look like it only appears once?
Here is the full code of an entry:
<div class="single ">
<a href='#inline41' rel='example_group' title='NAME GOES HERE'><img src='IMAGE GOES HERE' height='90' width='90' class='image' /></a>
<div class="right_col">
<h3>NAME GOES HERE</h3>
<div class="like_wrap"><div class="vot_plus" id="vt_img41"></div></div><!--like_wrap-->
</div><!--right_col-->
<div class="clear"></div><!--clear-->
<div id="inline41" style="display: none;">
<img src='IMAGE GOES HERE' height='400' class='image' /></a>
<div class="vote_bottom">
<p>Vote: </p>
<div class="like_wrap"><div class="vot_plus" id="vt_img41"></div></div><!--like_wrap-->
<div class="clear"></div><!--clear-->
</div><!--vote_bottom-->
</div>
</div><!--single-->
Any ideas how I can do this?
Thanks.

Categories