0

Hi all been working on this for a couple of days. I want to upload 4 image names to the mysql database and upload the images to a folder on the local server. I also want to display my images that goes with the text data.

So far I can add text to mysql and images as a BLOB and display the text and image name for example name of image.jpg, but can't seem to see the images.

So to my question is how would I add 4 images to the mysql database and to also store them in a the local server folder like for example image folder and then display them with the information added from the form?

Much appreciated and many thanks for the help in advance.

Mysql database;
Database: `cms1`

Table structure for table `cms_content`

CREATE TABLE IF NOT EXISTS `cms_content` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(350) NOT NULL,
`body` text NOT NULL,
`image1` blob NOT NULL,
`image2` blob NOT NULL,
`image3` blob NOT NULL,
`image4` blob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ;


syntax below;

The add-content.php / The Form to upload text and images.

<?php
 session_start();
 if(isset($_SESSION['user'])) {
 
include '../_class/cms_class.php';
 
$obj = new modernCMS();
 
//Setup Our Connection Vars
 $obj->host = 'localhost';
 $obj->username = 'username';
 $obj->password = 'password';
 $obj->db = 'dbname';
 
// Connect To Our Database
 $obj->connect();
 

?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <title>CMS Alpha</title>
 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 <link rel="stylesheet" type="text/css" href="../css/main.css" />
 <!-- TinyMCE -->
 <script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
 <script type="text/javascript">
         tinyMCE.init({
                 // General options
                 mode : "textareas",
                 theme : "advanced",
                 plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",
 
                // Theme options
                 theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
                 theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                 theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
                 theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",
                 theme_advanced_toolbar_location : "top",
                 theme_advanced_toolbar_align : "left",
                 theme_advanced_statusbar_location : "bottom",
                 theme_advanced_resizing : true,
 
                // Example content CSS (should be your site CSS)
                 content_css : "css/content.css",
 
                // Drop lists for link/image/media/template dialogs
                 template_external_list_url : "lists/template_list.js",
                 external_link_list_url : "lists/link_list.js",
                 external_image_list_url : "lists/image_list.js",
                 media_external_list_url : "lists/media_list.js",
 
                // Style formats
                 style_formats : [
                         {title : 'Bold text', inline : 'b'},
                         {title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
                         {title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
                         {title : 'Example 1', inline : 'span', classes : 'example1'},
                         {title : 'Example 2', inline : 'span', classes : 'example2'},
                         {title : 'Table styles'},
                         {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
                 ],
 
                // Replace values for the template plugin
                 template_replace_values : {
                         username : "Some User",
                         staffid : "991234"
                 }
         });
 </script>
 <!-- /TinyMCE -->
 
</head>
 <body>
 <div id="page-wrap">
   <h1>CMS Alpha</h1>
   <h3>Add Content</h3>
   <br />
    <?php include '../nav.php'; ?>
 
<form method="post" action="index.php">
         <div>
                 <input type="hidden" name="add" value="true" />
     <div>
         <label for="title">Title:</label>
         <input type="text" name="title" id="title" />
     </div>
 
                <!-- Gets replaced with TinyMCE, remember HTML in a textarea should be encoded -->
                 <div>
         <label for="title">Message:</label>
                         <textarea id="body" name="body" rows="15" cols="80" style="width: 80%">
                                 
                        </textarea>
                 </div>
     <div>
         <label for="title">Image 1:</label>
         <input type="file" name="image1" id="title" /><br /><br />
         <label for="title">Image 2:</label>
         <input type="file" name="image2" id="title" /><br /><br />
         <label for="title">Image 3:</label>
         <input type="file" name="image3" id="title" /><br /><br />
         <label for="title">Image 4:</label>
         <input type="file" name="image4" id="title" />
     </div>
                 
                <br />
                 <input type="submit" name="save" value="Submit" />
         </div>
 </form>
 </div>
 <script type="text/javascript">
 if (document.location.protocol == 'file:') {
         alert("The examples might not work properly on the local file system due to security settings in your browser. Please use a real webserver.");
 }
 </script>
 </body>
 </html>
 <?php } ?>

The main function page class.php

Main bit to look at in the code I think is the;
* Add Function 'add_content' to database and image folder
* Get Function 'get_content' from database text and image

<?php
 
class modernCMS {
         
        var $host;
         var $username;
         var $password;
         var $db;
         
        function connect() {
                 $con = mysql_connect($this->host, $this->username, $this->password) or die(mysql_error());
                 mysql_select_db($this->db, $con) or die(mysql_error());
         }
 /////////////////Get Function from database text and folder for image////////////////////////////
         function get_content($id = '') {
                 
                if($id != ""):
                         $id = mysql_real_escape_string($id);
                         $sql = "SELECT * FROM cms_content WHERE id = '$id'";
                         
                        $return = '<p><a href="index.php">Go Back to Content</a></p>';
                 else:
                         $sql = "SELECT id, title FROM cms_content ORDER BY id DESC";
                 endif;
                 
                $res = mysql_query($sql) or die(mysql_error());
                 
                if(mysql_num_rows($res) != 0):
                         while($row = mysql_fetch_assoc($res)) {
                                 echo '<h1><a href="index.php?id=' . $row['id'] . '">' . $row['title'] . '</a></h1>';
                                 echo '<p>' . $row['body'] . '</p>';
                                 echo '<table><tr><td>' . $row['image1'] . '</td><td>' . $row['image2'] . '</td><td>' . $row['image3'] . '</td><td>' . $row['image4'] . '</td></tr></table>';
                                 
                }
                 else:
                         echo '<p>Uh Oh!, this doesn\'t exist!';
                 endif;
                 
                echo $return;
         
        }
 ////////////////////////////////////////////////////////////////////////////    
/////////////////Add Function to database and image folder//////////////////////
                 function add_content($p) {
                 $title = mysql_real_escape_string($p['title']);
                 $body = mysql_real_escape_string($p['body']);
                 $image1 = mysql_real_escape_string($p['image1']);
                 $image2 = mysql_real_escape_string($p['image2']);
                 $image3 = mysql_real_escape_string($p['image3']);
                 $image4 = mysql_real_escape_string($p['image4']);
 
        //This is the directory where images will be saved
         $target = "./images";
         $target = $target . basename( $_FILES['image1']['image2']['image3']['image4']);
 
        //Writes the photo to the server
         if(move_uploaded_file($_FILES['image1']['image2']['image3']['image4'], $target))
 
        //file properties
         $file = $_FILES['image1']['temp_name1']['image2']['temp_name2']['image3']['temp_name3']['image4']['temp_name4'];
         
        
        
                if(!$title || !$body):
                         
                        if(!$title):
                                 echo "<p>The title is required</p>";
                         endif;
                         if(!$body):
                                 echo "<p>The body is required</p>";
                         endif;
                         
                                echo '<p><a href="add-content.php">Please Try Again!</a></p>';
                         else:
                                 $sql = "INSERT INTO cms_content VALUES (null, '$title', '$body', '$image1', '$image2', '$image3', '$image4')";
                                 $res = mysql_query($sql) or die(mysql_error());
                                 echo "Added Successfully!";
                         endif;
         }
 ////////////////////////////////////////////////////////////////////////////
         
        function manage_content() {
                 echo '<div id="manage">';
                 $sql = "SELECT * FROM cms_content";
                 $res = mysql_query($sql) or die(mysql_error());
                 while($row = mysql_fetch_assoc($res)) :
         ?>
 
<div>
   <table width="800px" cellspacing="10" cellpadding="10">
     <tr>
       <td colspan="15" width="700"><h3 class="title"><?php echo $row['title'];?></h3></td>
       <td colspan="15" width="90"><span class="actions"><a href="update-content.php?id=<?php echo $row['id'];?>">Edit</a> | <a href="?delete=<?php echo $row['id'];?>">Delete</a></span></td>
     </tr>
   </table>
 </div>
 <?php
                 endwhile;
                 echo '</div>'; //Closes Manage Div
         }
         
        function delete_content($id) {
                 if(!$id) {
                         return false;
                 } else {
                         $id = mysql_real_escape_string($id);
                         $sql = "DELETE FROM cms_content WHERE id = '$id'";
                         $res = mysql_query($sql) or die(mysql_error());
                         echo "Content Deleted Successfully!";
                 }
         }
         
        function update_content_form($id) {
                 $id = mysql_real_escape_string($id);
                 $sql = "SELECT * FROM cms_content WHERE id = '$id'";
                 $res = mysql_query($sql) or die(mysql_error());
                 $row = mysql_fetch_assoc($res);
         ?>
 <form method="post" action="index.php">
   <input type="hidden" name="update" value="true" />
   <input type="hidden" name="id" value="<?php echo $row['id'];?>" />
   <div>
     <label for="title">Title:</label>
     <input type="text" name="title" id="title" value="<?php echo $row['title'];?>" />
   </div>
   <div>
     <label for="body">Body:</label>
     <textarea id="body" name="body" rows="15" cols="80" style="width: 80%"><?php echo $row['body'];?></textarea>
   </div>
   <input type="submit" name="submit" value="Update Content" />
 </form>
 <?php
         }
         
        function update_content($p) {
                 $title = mysql_real_escape_string($p['title']);
                 $body = mysql_real_escape_string($p['body']);
                 $id = mysql_real_escape_string($p['id']);
                 
                if(!$title || !$body):
                         
                        if(!$title):
                                 echo "<p>The title is required</p>";
                         endif;
                         if(!$body):
                                 echo "<p>The body is required</p>";
                         endif;
                         
                                echo '<p><a href="update-content.php?id=' . $id . '">Please Try Again!</a></p>';
                         else:
                                 $sql = "UPDATE cms_content SET title = '$title', body = '$body' WHERE id = '$id'";
                                 $res = mysql_query($sql) or die(mysql_error());
                                 echo "Updated Successfully!";
                         endif;
         }
 } //End of the class
 
?>

Edited by bow103: n/a

2
Contributors
8
Replies
12
Views
6 Years
Discussion Span
Last Post by bow103
0

To display an image saved in the database you need to create a separate script. A basic example of display.php:

<?php
header('Content-type: image/jpeg');
$case = $_GET['case'];
$id = $_GET['id'];

#check if $id is a number
if(ctype_digit($id))
{
	require('db_conn.php');
	switch($case)
	{
		case 'image1':
		$query = "select image1 from cms_content where id = '$id' limit 1";
		break;

		case 'image2':
		$query = "select image2 from cms_content where id = '$id' limit 1";
		break;

		case 'image3':
		$query = "select image3 from cms_content where id = '$id' limit 1";
		break;

		case 'image4':
		$query = "select image4 from cms_content where id = '$id' limit 1";
		break;

		default:
		$query = "select image1 from cms_content where id = '$id' limit 1";
	}

	$rows = mysql_fetch_row($query);
	echo $row['0'];
}

else
{
	echo 'wrong data';

?>

After that, you only have to write img tags like in this example:

<img src="/display.php?case=image1&id=23" />
<img src="/display.php?case=image2&id=23" />
<img src="/display.php?case=image3&id=23" />
<img src="/display.php?case=image4&id=23" />

The default value in the switch case will ensure that if you enter something different you will always get image1.
However I would not save images to the database, this can decrease the performance and force you to add scripts like the previous.

0

Thanks cereal, I have noticed that it has been running slow when processing. How would I go about on saving the images in a folder and and retrieve them on?

much appreciated on the help your giving me cereal.

0

At the moment you don't even insert the images into the database, before the INSERT query you shoud use fopen() and fread() on each image, an example would be:

<?php

$fName1 = $_FILES['image1']['name'];
$fSize1 = $_FILES['image1']['size'];
$fType1 = $_FILES['image1']['type'];
$tName1  = $_FILES['image1']['tmp_name'];

$fp = fopen($tName1,'r');
$content1 = fread($fp,filesize($tName1));
$content1 = mysql_real_escape_string($content1);
fclose($fp);

# and repeat the previous for each image

$query = mysql_query("insert into cms_content (image1Name, image1Content, image2Name, image2Content, ...) values($fName1,$content1,$fName2,$content2,...)");
?>

In your case, just point the img tag to the path you have defined as $target:

<img src="./images/<?php echo $row['image1']; ?>" />

Remember that it could be useful to rename the uploaded images, so you can avoid to overwrite the already existing images in the destination folder.

Last but not least, you include the cms_class.php in the index.php but you don't call for any functions right after and there are no conditional statements, so the add_content() will not run.

There's a lot to do, you should try to run little scripts for each step so you get everything to work.

0

Hi cereal I tryed that, but I get a odd error message which I've never seen before.
I get a "MySQL server has gone away".

Kind Regards and appreciate your help.

0

Hi cereal I looked at the mysql website. I logged into mysql via shell and then put the command in --max_allowed_packet=16M, but got an error on line 1. I don't think I understand it.


appreciate your help.

0

You can use that option only if you have access to a terminal session, like ssh, if you log directly to MySQL shell that would not work. You can check the current value running a command from the mysql shell:

mysql> show variables like 'max%';

you should get something like this:

+----------------------------+------------+
| Variable_name              | Value      |
+----------------------------+------------+
| max_allowed_packet         | 1048576    |
| max_binlog_cache_size      | 4294967295 |
| max_binlog_size            | 1073741824 |
| max_connect_errors         | 10         |
| max_connections            | 100        |
| max_delayed_threads        | 20         |
| max_error_count            | 64         |
| max_heap_table_size        | 16777216   |
| max_insert_delayed_threads | 20         |
| max_join_size              | 4294967295 |
| max_length_for_sort_data   | 1024       |
| max_prepared_stmt_count    | 16382      |
| max_relay_log_size         | 0          |
| max_seeks_for_key          | 4294967295 |
| max_sort_length            | 1024       |
| max_sp_recursion_depth     | 0          |
| max_tmp_tables             | 32         |
| max_user_connections       | 0          |
| max_write_lock_count       | 4294967295 |
+----------------------------+------------+
19 rows in set (0.30 sec)

Where 1048576 are bytes (equal to 1,049MB). If you don't have root access or you can't change the MySQL config, and you need to store images into the database, than you can only write to the administrators of your server and ask them how you can solve the problem.

Anyway, you could also try to upload few images under 1MB and see if that works. At least you know if your script is running well.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.