Download a zip file with the MySqlSlideshow class files and examples: Download Zip File
<?php
// This is a server side example
// Start a PHP Session
session_start();
require_once("dbclass.connectinfo.i.php"); // has $Host, $User, $Password
// This file has the MySqlSlideshow class
require_once("mysqlslideshow.class.php");
// Construct the slideshow class:
// There is a 4th argument for the database name if not "mysqlslideshow" and a 5th argument for the table name if not
// "mysqlslideshow"
$ss = new MySqlSlideshow($Host, $User, $Password); // use values from dbclass.connectinfo.i.php
// for use in <form action="$self" tags.
$self = $_SERVER['PHP_SELF'];
// Check for Microsoft Internet Explorer -- because everything Microsoft makes is broken!
$isIe = preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']);
$ieMsg = $isIe ? '<p style="color: red">Microsoft Internet Explorer Version, because Microsoft can not do it like anyone else!</p>' : "";
// This file should not be in the Apache path for security reasons
//********************
// Start of Slide Show Logic
// NOTE THE ORDER. STOP must be before START and session checking. One could of course design this section differently so the
// order was not important but this is only an example of using the CLASS.
if($_POST['stop']) {
unset($_SESSION['next']);
echo <<<EOF
<html>
<head>
<title>Slideshow Example: Server Side Version</title>
</head>
<body>
<h1>Slide Show Example: Server Side Version</h1>
$ieMsg
<form action="$self" method="post">
<input type="submit" name="start" value="Start"/>
</form>
</body>
</html>
EOF;
exit();
}
if($_POST['start']) {
$_SESSION['next'] = "next";
}
if($_SESSION['next'] == "next") {
$inx = $_SESSION['index'];
$ids = $_SESSION['ids'];
// Microsoft test
if(!isIE) {
$images = $_SESSION['images'];
// getImage() returns an assoc array [data], [mime], [subject], and [desc]
// [data] is base64 by default. If a second argument is provided as 'raw' then the data is the raw image data.
$data = $images[$inx++];
$_SESSION['index'] = ($inx > count($ids)-1) ? 0 : $inx;
$image = $data['data']; // image in base64
$mime = $data['mime']; // mime type like "image/gif" etc.
$subject = $data['subject'];
$desc = $data['desc'];
} else {
// Handle BROKEN Browser!
$image = "mysqlslideshow.php?image=$ids[$inx]&type=raw";
$info = $ss->getInfo($ids[$inx++]);
$_SESSION['index'] = ($inx > count($ids)-1) ? 0 : $inx;
$subject = $info['subject'];
$desc = $info['description'];
}
echo <<<EOF
<html>
<head>
<title>Slideshow Example: Server Side Version</title>
<!-- Set Refresh for every 5 seconds -->
<meta http-equiv="Refresh" content="5"; url="http://localhost/test.php" />
</head>
<body>
<h1>Slide Show Example: Server Side Version</h1>
$ieMsg
<form action="$self" method="post">
<input type="submit" name="stop" value="Stop"/>
</form>
<p>Image: $inx</p>
<img src="$image" alt="" /><br>
<p>Subject: $subject, Description: $desc</p>
</body>
</html>
EOF;
exit();
}
//++++++++++++++++++++
// First Page
// Get a list of id's.
// This function takes one optional arguments:
// $where: defaults to "", the where conditions of the query.
// You can add where conditions like this for example: "type = 'link' && data like('%bill%.jpg')" then you
// would only get link type rather than data type entries and only links with the name bill and jpegs.
$ids = $ss->getImageIds();
// Set the session up.
$_SESSION['ids'] = $ids;
$_SESSION['index'] = 0; // Start at the beginning
// Get all the images
// For NON IE browsers we can cache the images.
if(!$isIe) {
$images = Array();
for($i=0; $i < count($ids); ++$i) {
$images[$i] = $ss->getImage($ids[$i]);
}
$_SESSION['images'] = $images;
}
// Here is the example of a slide show.
// We have two buttons "Start" and "Stop"
// and the table with the slideshow mysqlslideshow table displayed (not everything just some).
//
// The style is to add borders and padding to the table.
//
echo <<<EOF
<html>
<head>
<style type="text/css">
#displayAllImageInfo * {
border: 1px solid black;
padding: 0 10px;
}
</style>
</head>
<body>
<h1 id="maintitle">Slide Show Example: Server Side Version</h1>
$ieMsg
<div id="startstop">
<form action="$self" method="post">
<input type="submit" name="start" value="Start"/>
</form>
</div>
EOF;
$ss->displayAllImageInfo();
echo <<<EOF
</body>
</html>
EOF;
?>
<!--
// MySql Slideshow Example: Browser Side Javascript Ajax Version
// Here is the example of a slide show.
// The HTML for this example only has the <noscript> tags all the rest is handled by the Javascript
//
// The style is to add borders and padding to the table.
// In this example I use the jQuery Javascript library. You could code it all without jQuery but it would be harder. When the
// start button is clicked the PHP class library is called via Ajax (the $.get() jQuery function) with the ids[inx++] argument.
// inx was initialized to zero and each Ajax call increments it by one. The loadpic() function is called the first time. The image
// is fetched and a timer is started with a 5 second delay and a callback to the loadpic() function. After 5 seconds the loadpic()
// function is called again and the next image is loaded. The $("#image").html("<img src='" + data + "'/>"); is more jQuery which
// basically gets the "div" element by id and adds the html code for the image. This could all be done with standard DOM calls but
// it would be harder. After loading the image the loadpic() function checks to see if the index value inx is at the end of the
// ids array and if so resets inx to zero. The timer is reset for 5 seconds (wash, rinse, repeat). The "Stop" button just does a
// clearTimeout() to stop the whole process.
-->
<html>
<head>
<title>MySql Slideshow Example: Ajax Version</title>
<style type="text/css">
#displayAllImageInfo * {
border: 1px solid black;
padding: 0 10px;
}
</style>
<!-- We are using the jQuery Javascript library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<![if !IE]>
<script type="text/javascript">
<!-- Hide javescript
// The PHP class supports two ways of getting the image.
// 1) The first method is supported by most good browsers. The image is returned as "data:$mime;base64,$image" and this is added
// to the '<img src=data:"$mime;base64,$image"...' (where $mime is the mime type like "image/gif" and $image is the base64
// encoded image). This works with Firefox, Galion, Opera, Google Chrome, and almost every other browser EXCEPT (you guessed it)
// Microsoft Internet Explorer (lets hear it for Microsoft!)
// 2) The second method works everywhere even in IE. This method uses the mysqlslideshow.php file to return an image just as if
// you had <img src="image.gif"> for example. The code looks like: <img src="mysqlslidshow.php?image=1&type=raw"...> in this case
// you would have to also get the "subject" and "description" via the "mysqlslideshow.php?info=1" in an Ajax call.
// I show both methods as well as a caching approach using new Image().
var ids = new Array;
var inx = 0; // index starts at zero
var timerid; // for use by clearTimeout()
var reg=/^(.*)<::subject::>(.*)<::description::>(.*)/;
var images = new Array;
var infos = new Array;
// setTimeout callback function.
// NOTE: in both Ajax calls via $.get() if you really want the timing to include the network time you
// should do the next setTimeout in the $.get() callback function. As this code is if th network takes a long
// time we could timeout before the image was received.
function loadpic() {
// We cash the images on the first load so we don't have to do the Ajax code every time.
// We could also have loaded all the images when the page is first loaded and then only used the cached copies in the timer
// logic. See the IE version for this approach.
if(typeof images[inx] != "undefined") {
$("#image").html("<p>Image from cache: " + (inx+1) + "</p><img src='" + images[inx] + "'/>");
$("#image").append("<p>Subject: "+ infos[inx][0] +", Description: "+ infos[inx][1] +"</p>");
++inx;
if(inx > ids.length-1) { inx = 0 };
timerid = setTimeout("loadpic()", 5000);
} else {
$.get("mysqlslideshow.php", {image: ids[inx], addinfo: 1}, function(data) {
var m = reg.exec(data);
images[inx] = m[1];
infos[inx] = new Array(m[2], m[3]);
++inx;
$("#image").html("<p>Image: " + inx + "</p><img src='" + m[1] + "'/>");
$("#image").append("<p>Subject: "+m[2]+", Description: "+m[3]+"</p>");
if(inx > ids.length-1) { inx = 0 };
// here we set the timer in the callback which means that even if the image takes a long time to load the timer only starts
// after the image is finished loading.
timerid = setTimeout("loadpic()", 5000);
});
}
}
jQuery(document).ready(function($) {
$("noscript").after('<h1>Slideshow Example: Ajax Version</h1>\
<button id="start">Start</button><button id="stop">Stop</button><br>\
<div id="image"></div>');
$("#stop").hide();
$.get("mysqlslideshow.php", {ids : 1}, function(data) {
// data is a list of ids "'1','2'..."
ids = data.split(',');
});
// Put the table after the image div
$.get("mysqlslideshow.php", {table: 1}, function(data) {
$("#image").after(data);
});
// Start and Stop button click event
$("#start").click(function() {
$("#start").hide();
$("#stop").show();
$("#displayAllImageInfo").hide(); // once we start hide the table
loadpic();
});
$("#stop").click(function() {
clearTimeout(timerid);
$("#stop").hide();
$("#start").show();
});
});
//-->
</script>
<![endif]>
<!--[if IE]>
<script type="text/javascript">
// This is the javascript that works with IE
var ids = new Array;
var inx = 0; // index starts at zero
var timerid; // for use by clearTimeout()
var reg=/<::subject::>(.*)<::description::>(.*)/;
var images = new Array;
var infos = new Array;
// setTimeout callback function.
// NOTE: in both Ajax calls via $.get() if you really want the timing to include the network time you
// should do the next setTimeout in the $.get() callback function. As this code is if th network takes a long
// time we could timeout before the image was received.
// In this IE version we have initially cached all of the images in inmages and the info in infos
function loadpic() {
$("#image").html("<p>Image: " + (inx+1) + "</p><img src='" + images[inx].src + "'/>");
$("#image").append("<p>Subject: " + infos[inx][0] + ", Description: " + infos[inx][1] +"</p>");
if(++inx > ids.length-1) { inx = 0 };
timerid = setTimeout("loadpic()", 5000);
}
jQuery(document).ready(function($) {
$("noscript").after('<h1>Slideshow Example: Ajax Version</h1>\
<p style="color: red">Microsoft Internet Explorer Version, because Microsoft can not do it like anyone else!</p>\
<button id="start">Start</button><button id="stop">Stop</button><br>\
<div id="image"></div>');
$("#stop").hide();
// We get all the IDS and then precache all of the images
$.get("mysqlslideshow.php", {ids : 1}, function(data) {
// data is a list of ids "'1','2'..."
ids = data.split(',');
$.ajaxSetup({async: false}); // do the following synchronously so the infos array is filled properly
// Now load all of the images and get the info
for(var i=0; i < ids.length; ++i) {
images[i] = new Image;
images[i].src = "mysqlslideshow.php?image=" + ids[i] + "&type=raw";
// do this synchronously
$.get("mysqlslideshow.php", {info: ids[i]}, function(data) {
var m = reg.exec(data);
infos[i] = new Array(m[1], m[2]);
});
}
$.ajaxSetup({async: true}); // back to default
});
// Put the table after the image div
$.get("mysqlslideshow.php", {table: 1}, function(data) {
$("#image").after(data);
});
// Start and Stop button click event
$("#start").click(function() {
$("#start").hide();
$("#stop").show();
$("#displayAllImageInfo").hide(); // once we start hide the table
loadpic();
});
$("#stop").click(function() {
clearTimeout(timerid);
$("#stop").hide();
$("#start").show();
});
});
//-->
</script>
<![endif]-->
</head>
<body>
<noscript>
<h1>Javascript Not Available</h1>
<p>Your browser does not support Javascript or you have it disables. You can view a server side version by clicking
<a href="serverside.php">Server Side Example</a></p>
</noscript>
</body>
</html>
<?php
// Add selected images from a directory
// This file should not be in the Apache path for security reasons
require_once("dbclass.connectinfo.i.php"); // has $Host, $User, $Password
// This file has the MySqlSlideshow class
require_once("mysqlslideshow.class.php");
// Construct the slideshow class:
// There is a 4th argument for the database name if not "mysqlslideshow" and a 5th argument for the table name if not
// "mysqlslideshow"
$ss = new MySqlSlideshow($Host, $User, $Password); // use values from dbclass.connectinfo.i.php
$self = $_SERVER['PHP_SELF'];
if($_POST) {
extract($_POST);
echo <<<EOF
<html>
<body>
<h1>Adding Images</h1>
EOF;
for($i=0; $i < $count; ++$i) {
$image = eval("return \$box$i;");
if($image) {
$subject = eval("return \$subject$i;");
$desc = eval("return \$desc$i;");
if(($ret = $ss->addImage($image, $subject, $desc, $type)) === true) {
echo "<p>Image added: $image, subject=$subject, description=$desc</p>\n";
} else {
echo "<p style='color: red'>$ret</p>\n";
}
}
}
echo <<<EOF
</body>
</html>
EOF;
exit();
}
if($path = $_GET['path']) {
$type = $_GET['type'] ? $_GET['type'] : 'link';
$ar = glob($path);
$images = Array();
$pattern = $_GET['pattern'];
if(!empty($pattern)) {
foreach($ar as $file) {
if(preg_match("/$pattern/", $file)) {
$images[] = $file;
}
}
} else {
$images = $ar;
}
if(count($images)) {
echo <<<EOF
<html>
<body>
<h1>Select Images</h1>
<form action="$self" method="post">
EOF;
$i=0;
for(; $i < count($images); ++$i) {
$image = $images[$i];
echo <<<EOF
<input type="checkbox" name="box$i" value="$image"/>$image<br>
<input type="text" name="subject$i" /><br>
<input type="text" name="desc$i" /><br>
<br>
EOF;
}
echo <<<EOF
<input type="hidden" name="count" value="$i" />
<input type="hidden" name="type" value="$type" />
<input type="submit" value="Submit"/>
</form>
</body>
</html>
EOF;
} else {
echo <<<EOF
<html>
<body>
<h1>No Files Matched</h1>
</body>
</html>
EOF;
}
}
?>
<?php
// Add or Update an Image in the Database table
// This file should not be in the Apache path for security reasons
require_once("dbclass.connectinfo.i.php"); // has $Host, $User, $Password
// This file has the MySqlSlideshow class
require_once("mysqlslideshow.class.php");
// Construct the slideshow class:
// There is a 4th argument for the database name if not "mysqlslideshow" and a 5th argument for the table name if not
// "mysqlslideshow"
$ss = new MySqlSlideshow($Host, $User, $Password); // use values from dbclass.connectinfo.i.php
//********************
// The following section is used to add images and text to the database
// Options to URL:
// ?image=imagefilename&subject=subject&desciption=description
// only image is required.
// ?update=id&subject=subject&desciption=description
// only update id is required but one would think that ether or both additonal arguments would make more sense
// With NO arguments slide show plus display table of image info.
if($image = $_GET['image']) {
// Add a new image to the table.
$subject = $_GET['subject'];
$desc = $_GET['description'];
$type = $_GET['type'] ? $_GET['type'] : 'link';
if(($ret = $ss->addImage($image, $subject, $desc, $type)) !== true) {
echo "$ret<br>";
} else {
echo "<br>Image=$image<br>Added<br>";
}
exit();
}
// Update an existing images subject and description
if($id = $_GET['update']) {
// Update an existing image to change the subject and/or the description
$subject = $_GET['subject'];
$desc = $_GET['description'];
$ret = $ss->updateImageInfo($id, $subject, $desc);
if($ret === true) {
echo "<br>Image with id=$id has been updated with<br>subject=$subject,<br>and description=$desc<br>\n";
} else {
echo "$ret<br>";
}
exit();
}
// End of the add and update logic
//********************
?>
<html>
<body>
<h1>Usage</h1>
<p>This page accepts several GET arguments.</p>
<code>addupdateimage.php?image=imagefile&subject=text&description=text</code>
<p>The first argument "image" is the filename of the iage file to add to the database table</p>
<p>The second and third arguments are optional and update the <i>subject</i> and <i>description</i>
fields in the database table.</p>
<code>addupdateimage.php?update=5&subject=text&description=text</code>
<p>The first argument "update" is the <i>id</i> of the image in the database table</p>
<p>The second and third arguments are optional and update the <i>subject</i> and <i>description</i>
fields in the database table.</p>
</body>
</html>
This is used by the Ajax code to get various things by passing querys via GET.
<img src="mysqlslideshow.php?image=1&type=raw" /> . This works for all browsers even IE ids = data.split(',') .Usage of this file can be found in the browserside.html file.
<?php
// This is intended for use with Javascript Ajax and as the subject to the "<img src=" or as the subject to a Javascript sequence
// like "var i = new Image(); i.src=mysqlslideshow.php?image=2;"
require("dbclass.connectinfo.i.php"); // has $Host, $User, $Password
require("mysqlslideshow.class.php");
$ss = new MySqlSlideshow($Host, $User, $Password);
//********************
// This is an Ajax call.
// Get the image given an id.
// The arguments are:
// image=id
// type=raw optional argument, if pressent then the raw image data is returned with the proper mime type header. If not present
// then returns an echoed data package that can be the argument to "<img src=" tag.
// addinfo=1 optional argument, if present and if not specified as raw then the "<::subject::>text<::description::>text" is
// appended onto the base64 image packet. If type=raw then addinfo is ignored!
if($_GET['image']) {
extract($_GET);
if($type == 'raw') {
$ar = $ss->getImage($image, ""); // the second arg defaults to base64 so here we want to unset it.
Header("Content-type: $mime");
$data = $ar['data'];
echo $data;
} else {
$ar = $ss->getImage($image); // default is base64
Header("Content-type: text/plain");
$data = $ar['data'];
$data = "$data";
if($addinfo) {
$data .= "<::subject::>$ar['subject']<::description::>$ar['desc']";
}
echo "$data";
}
exit();
}
//********************
// This is an Ajax call.
// Gets the "subject" and "description"
// The arguments are:
// info=id
// returns an echoed string like this:
// "<::subject::>subject info<::description::>>description info"
// this string can be parsed to get the subject and description.
if($id = $_GET['info']) {
Header("Content-type: text/plain");
$data = $ss->getInfo($id);
echo "<::subject::>$data['subject']<::description::>$data['description']";
exit();
}
//********************
// This is an Ajax call.
// Get the list of ids
// ids=1
// where=where arguments. optional
// returns the list of ids
if($_GET['ids']) {
Header("Content-type: text/plain");
$ar = $ss->GetImageIds($_GET['where']);
$ids = "";
foreach($ar as $id) {
$ids .= "$id,";
}
echo rtrim($ids, ',');
exit();
}
//********************
// This is an Ajax call.
// Display a <table> containing all of the rows of the database table
// table=1
if($_GET['table']) {
Header("Content-type: text/plain");
return $ss->displayAllImageInfo();
}
?>
This is the PHP class "MySqlSlideshow" which extends the Database class below.
The class has the following methods:
public function __construct($host, $user, $password, $database="mysqlslideshow", $table="mysqlslideshow")public function getImageIds($where="")public function getImage($id, $returntype="base64")public function getInfo($id)public function imageQuery($where="")public function returnResult()public function getNextImageRowData()public function getNumImages()public function addImage($imagefile, $subject="", $desc="", $type="link")public function updateImageInfo($id, $subject, $desc)public function displayAllImageInfo()Methods 1 through 4 and 11 are the primary methods and examples can be found in the serverside.php example file above. Examples of methods 9 and 10 can be found in addimages.php and addupdateimage.php. Methods 5 through 8 are not shown in any examples and are lower level methods.
<?php
// This class facilitates a slide show where the links or image data is stored in a mysql table. In addition to the link/data the
// table comments, description, date, etc.
//
// The class provides methods for getting, displaying, editing, and adding image items
// This class extends a Database class that handles the MySql connection and provides at a minimum:
// Database::__construct; Conects and opens database.
// Database::query; Dose a mysql_query.
// Database::getDb; return the resource from mysql_connect().
// The database should have the following fields:
// CREATE TABLE `mysqlslideshow` (
// `id` int(11) NOT NULL auto_increment,
// `type` enum('link', 'data') default 'link', /* if link then data is a link address, if data then image.
// `imageinfo` varchar(255) NOT NULL, /* return from getimagesize(img, extrinfo) serialized
// `subject` varchar(255) default NULL,
// `description` text,
// `data` blob default NULL,
// `created` datetime NOT NULL default CURRENT_TIMESTAMP,
// PRIMARY KEY (`id`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//
// include a database class file.
// what I do is have a file that is not accessable by the web server but can be loaded via require_once().
// In this file I have the user, password so these are secure.
require_once("dbclass.i.php"); // name of your Database class file.
class MySqlSlideshow extends Database {
private $result = 0;
private $table;
private $numRows = -1; // uninited
// Constructor take three manditory and two optional arguments
public function __construct($host, $user, $password, $database="mysqlslideshow", $table="mysqlslideshow") {
// Constructor
$this->table = $table;
// Call the Database constructor
parent::__construct($host, $user, $password, $database); // open the database
}
//********************
// These are the primary methods used for a slide show
//********************
// Get list if ids given an optional where argument
// returns an array of ids
// false if error.
public function getImageIds($where="") {
if(isset($whre)) {
//echo "where=$where";
$where = " where $where";
}
$result = $this->query("select id from $this->table$where");
if(!$result) {
return false;
}
while($row = mysql_fetch_assoc($result)) {
$ids[] = $row['id'];
}
return $ids;
}
// Get the image given an id
// Arguments:
// $id: the id of the image in the database table
// $type: defaults to "base64". If $type is not "base64" then returns raw image data.
// returns an assoc array:
// [data] has string that can be used in a "<img src=" tag, or if $type is not "base64" raw image data
// [mime] has the mime type of the image
// [subject] has a string with the subject text
// [desc] has a string with the description text
public function getImage($id, $returntype="base64") {
$result = $this->query("select * from $this->table where id='$id'");
$row = mysql_fetch_assoc($result);
extract($row);
$ret = Array();
if($type == "data") {
$image = $data;
} else {
$image = file_get_contents($data);
}
$imageinfo = unserialize($row['imageinfo']);
$mime = image_type_to_mime_type($imageinfo[2]);
if($returntype == "base64") {
$image = base64_encode($image);
$ret['data'] = "data:$mime;base64,$image";
} else {
$ret['data'] = $image;
}
$ret['mime'] = $mime;
$ret['subject'] = $subject;
$ret['desc'] = $description;
return $ret;
}
// Get the information (subject, and description)
// $id is the entry to get (like getImage())
// returns an assoc array with the two fields
public function getInfo($id) {
$result = $this->query("select * from $this->table where id='$id'");
$row = mysql_fetch_assoc($result);
extract($row);
return Array('subject'=>$subject, 'description'=>$description);
}
//********************
// These are posibley usefull methods but are now shown in the EXAMPLE supplied
//********************
// Quiry database.
// $where defaults to blank. Put the where conditions in $where
// returns true or false
public function imageQuery($where="") {
if(isset($whre)) {
echo "where=$where";
$where = " where $where";
}
// Note Database::query() can either just output an error message and exit,
// or return false on error
$result = $this->query("select * from $this->table$where");
if(!$result) {
return false;
}
$this->result = $result;
$this->numRows = mysql_num_rows($result);
return true;
}
// Return the $result for a query in case user wants to do direct mysql stuff.
public function returnResult() {
return $this->result;
}
// Get the next image from the database.
// returns the row as an assoc array
// or false if all items have been read. This can be used in a while statement like:
// $x->imageQuery(some query);
// while($row = $x->getNextImageRowData()) { do something }
public function getNextImageRowData() {
$row = mysql_fetch_assoc($this->result);
return $row;
}
// Get number of images in database
// if this is called before a quiry then the method returns "false" so user should always check the return value with === or
// !== false;
public function getNumImages() {
if($this->numRows == -1) {
return false;
}
return $this->numRows; // This could be zero so don't be sure to test === or !== false to see if an error ocurred
}
//********************
// The next two methods are used to add and modify the database table. See examples in the EXAMPLE file
//********************
// Add an image to the databasse table. This does an insert.
// Arguments:
// $imagefile: either the path on the server of the image file, or if $type='data' the actual image data.
// $type: defaults to 'link'. Can be 'data' if the $imagefile is the actual image data.
// $subject: defaults to blank.
// $description: defaults to blan.
// returns true if OK else an error string.
public function addImage($imagefile, $subject="", $desc="", $type="link") {
if(!file_exists($imagefile)) {
return "File does not exist: $imagefile";
}
$imagefile = realpath($imagefile); // make it into the absolute path
$extrainfo;
$imageinfo = getimagesize($imagefile, $extrainfo);
array_push($imageinfo, $extrainfo);
$imageinfo = serialize($imageinfo);
switch($type) {
case "link":
$data = $imagefile;
break;
case "data":
$data = file_get_contents($imagefile);
break;
default:
// Error
return "Invalid type: $type";
}
//$imageinfo = mysql_real_escape_string($imageinfo);
$query = "insert into $this->table (type, imageinfo, data";
$qdata = ") value('$type', '$imageinfo', '$data'";
if($subject) {
$query .= ", subject";
$qdata .= ", '$subject'";
}
if($desc) {
$query .= ", description";
$qdata .= ", '$desc'";
}
$query .= ", created$qdata, now())";
//echo "$query<br>";
$this->query($query);
return true;
}
// update an image whose id=$id. Set the subject and desc
public function updateImageInfo($id, $subject, $desc) {
$ids = $this->getImageIds(); // get an array of all the ids
// Is this id in the field?
if(array_search($id, $ids) === false) {
return "Id=$id is not in the table";
}
$s = "";
if($subject) {
$s = " subject='$subject'";
}
$d = $s ? ", " : "";
if($desc) {
$d .= "description='$desc'";
}
$query = "update $this->table set $s$d where id='$id'";
//echo "$query<br>";
$this->query($query);
if(!mysql_affected_rows()) {
return "No changes made by query: $query";
} else {
return true;
}
}
//********************
// A helper method to display a <table> with all of the items in the database table
//********************
// Display all of the information in the table
public function displayAllImageInfo() {
$result = $this->query("select id, subject, description, data, created from $this->table");
echo <<<EOF
<table id="displayAllImageInfo">
<thead>
<tr>
EOF;
$header = true;
while($row = mysql_fetch_assoc($result)) {
if($header) {
$header = false;
$line = "<tr>\n";
foreach($row as $key=>$value) {
echo "<th>$key</th>\n";
$item = $value ? $value : " ";
$line .= "<td>$item</td>\n";
}
echo "</tr>\n</thead>\n<tbody>\n";
echo "$line</tr>\n";
}
echo "<tr>\n";
foreach($row as $value) {
$item = $value ? $value : " ";
echo "<td>$item</td>\n";
}
echo "</tr>\n";
}
echo <<<EOF
</tbody>
</table>
EOF;
}
}
// !!! There can be NOTHING after the ending PHP tag NOT EVEN a NL or CR!!!
?>
This is the Database class from which MySqlSlideshow is derived.
<?php
class Database {
public $db = 0;
private $host, $user, $password, $database;
public function __construct($host, $user, $password, $database) {
//echo "<br>host=$host, user=$user, password=$password, database=$database<br>\n";
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->opendb(); // Make sure we have a db even before we do a query!
}
//----------------------------------------------------------
// resourceId opendb(<host>, <user>, <password>, <database>)
// Opens the database, returns the resourceId
//----------------------------------------------------------
private function opendb() {
// Only do one open
if($this->db) {
return $this->db;
}
$db = mysql_connect($this->host, $this->user, $this->password, true);
if(!$db) {
echo __FILE__ ." Can't connect to database: host=$this->host, user=$this->user, password=$this->password\n";
exit;
}
if(!mysql_select_db($this->database, $db)) {
echo __FILE__ . " Can't select database: database=$this->database\n";
exit;
}
$this->db = $db;
return $db;
}
//-------------------------------
// resultId query(<query string>)
// On error calls SqlError() which outputs error message.
// On error function exits.
// !! This could also return false if error.
// returns resultId
//-------------------------------
public function query($query) {
//$db = $this->opendb();
$db = $this->db; // the constructor opens the database!
$result = mysql_query($query, $db);
if(!$result) {
SqlError(mysql_error($db), $query);
// or could return false
exit();
}
return $result;
}
//--------------------------------
// resourceId getDb()
// returns the database resourceId
// NOTE there is no setDb()!
//--------------------------------
public function getDb() {
return $this->db;
}
}
//-----------------
// Database errors
// Simple function not an exception
//-----------------
if(!function_exists('SqlError')) {
function SqlError($msg, $query) {
$PHP_SELF = $_SERVER['PHP_SELF'];
echo "<h1>SQL DEBUG INFO: ERROR in $PHP_SELF:</h1>\n";
echo "<p>$msg</p>\n";
echo "<p>Query: $query</p>\n";
// mail("info@granbyrotary.org", "PhpError in $PHP_SELF", "Message:
// $msg\nQuery=$query");
}
}
//------------------------------------------
// Helper function
// Function to strip slashes from $row array
//------------------------------------------
if(!function_exists('stripSlashesDeep')) {
function stripSlashesDeep($value) {
$value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value);
return $value;
}
}
// WARNING THERE MUST BE NOTHING AFTER THE CLOSING PHP TAG.
// Really nothing not even a space!!!!
?>