Alright, no problem.
Let's start with the database itself. First, you need to know your DB hostname, username, password, and the name of the database itself. You should have all of these from when you set up the database. You'll need them in your script to open a connection to the database (but don't post them here -or anywhere- ******* them out instead).
Next, you'll need to decide what information you need to store in the database and then create a database table. That's the code I posted above. Let's add another field to differentiate between the large images and the thumbnails; then, we'll need to load all of your records.
To retrieve that information, you'll use a select
statement ("query"). Your query will probably look something like this:
Code:
select `path`,`caption` from `image_gallery`
Before PHP can query the database, it will need to establish a connection to it. There are several choices. I will give you an example using [http://php.net/pdo]PDO[/url], but you could use MySQLi instead. Do not use the mysql_*
functions. They are deprecated and are not recommended for new code.
PHP Code:
<?php
// get a PDO object that is connected to your database
// * if you are running PHP version prior to 5.3.6, we'll have to change this slightly. let me know.
try{
$PDO = new PDO( "mysql:host=your.db.hostname;dbname=your_db_name;charset=utf8","your db username","your db password" );
}
catch( PDOException $PDOe ){
/* the connection failed. during development, you can do: */
// print $PDOe->getMessage();
/* to see what the problem was. but _never_ do this on your live site. */
exit( "database connection failed." );
}
Once you are connected, you can prepare your query and then send it to the database:
PHP Code:
<?php
try{
$query = $PDO->prepare( "select `path`,`caption` from `image_gallery`" );
$query->execute();
// loop over results
while( $row = $query->fetch() ){
// build your <img> tags for the gallery
// add a width attribute to the thumbnail image to keep it smaller, or use css.
// if the images are very large, you might want to add another field to the DB for the thumbnail image.
$img[] = '<a href="http://example.com/'. $path .'" class="galpop" data-galpop-group="gallery">'
.'<img src="http://example.com/'. $path .'" alt="">'
.'</a>';
}
// if there are any images, we'll print them:
if( ! empty( $img ) ){
// combine all imgs into markup for gallery
$gallery = implode( $img,"\n" );
// and print
print $gallery;
// all done :)
}
}
catch( Exception $e ){
/* as above, something went wrong. try: */
// print $e->getMessage();
}
Bookmarks