this is the full code of uploading image using php..

<?php

// Connect to database

$errmsg = "";
if (! @mysql_connect("localhost","root")) {
        $errmsg = "Cannot connect to database";
        }
@mysql_select_db("records");

// First run ONLY - need to create table by uncommenting this
// Or with silent @ we can let it fail every sunsequent time ;-)

$q = < < <CREATE
create table pix (
    pid int primary key not null auto_increment,
    title text,
    imgdata longblob)
CREATE;
@mysql_query($q);

// Insert any new image into database

if ($_REQUEST[completed] == 1) {
        // Need to add - check for large upload. Otherwise the code
        // will just duplicate old file ;-)
        // ALSO - note that latest.img must be public write and in a
        // live appliaction should be in another (safe!) directory.
        move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
        $instr = fopen("latest.img","rb");
        $image = addslashes(fread($instr,filesize("latest.img")));
        if (strlen($instr) < 149000) {
                mysql_query ("insert into pix (title, imgdata) values (\"".
                $_REQUEST[whatsit].
                "\", \"".
                $image.
                "\")");
        } else {
                $errmsg = "Too large!";
        }
}

// Find out about latest image

$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
        $title = htmlspecialchars($row[title]);
        $bytes = $row[imgdata];
} else {
        $errmsg = "There is no image in the database yet";
        $title = "no database image available";
        // Put up a picture of our training centre
        $instr = fopen("../wellimg/ctco.jpg","rb");
        $bytes = fread($instr,filesize("../wellimg/ctco.jpg"));
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
        header("Content-type: image/jpeg");
        print $bytes;
        exit ();
        }
?>
<html><head>
<title>Upload an image to a database</title>
<body bgcolor=white><h2>Here's the latest picture</h2>
<font color=red><?= $errmsg ?></font>
<center><img src=?gim=1 width=144><br>
<b><?= $title ?></center>
<hr>
<h2>Please upload a new picture and title</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
then: <input type=submit></form><br>
<hr>
</body>
</html>

cannot display in my program.

here'a the revision of code..

form.php

<html><head>
<title>Upload an image to a database</title>
<body bgcolor=white><h2>Here's the latest picture</h2>
<font color=red><?= $errmsg ?></font>
<center><img src=?gim=1 width=144><br>
<b><?= $title ?></center>
<hr>
<h2>Please upload a new picture and title</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
then: <input type=submit></form><br>
<hr>
</body>
</html>

displayimage.php

<?php

// Connect to database

$errmsg = "";
if (! @mysql_connect("localhost","root")) {
        $errmsg = "Cannot connect to database";
        }
@mysql_select_db("records");

// First run ONLY - need to create table by uncommenting this
// Or with silent @ we can let it fail every sunsequent time ;-)

$q = < < <CREATE
create table pix (
    pid int primary key not null auto_increment,
    title text,
    imgdata longblob)
CREATE;
@mysql_query($q);

// Insert any new image into database

if ($_REQUEST[completed] == 1) {
        // Need to add - check for large upload. Otherwise the code
        // will just duplicate old file ;-)
        // ALSO - note that latest.img must be public write and in a
        // live appliaction should be in another (safe!) directory.
        move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
        $instr = fopen("latest.img","rb");
        $image = addslashes(fread($instr,filesize("latest.img")));
        if (strlen($instr) < 149000) {
                mysql_query ("insert into pix (title, imgdata) values (\"".
                $_REQUEST[whatsit].
                "\", \"".
                $image.
                "\")");
        } else {
                $errmsg = "Too large!";
        }
}

// Find out about latest image

$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
        $title = htmlspecialchars($row[title]);
        $bytes = $row[imgdata];
} else {
        $errmsg = "There is no image in the database yet";
        $title = "no database image available";
        // Put up a picture of our training centre
        $instr = fopen("../wellimg/ctco.jpg","rb");
        $bytes = fread($instr,filesize("../wellimg/ctco.jpg"));
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
        header("Content-type: image/jpeg");
        print $bytes;
        exit ();
        }
?>

cannot display the image together with other records..

Recommended Answers

All 7 Replies

Uhm..

So you spammed this post with code.. What is it supposed to do? What does it fail to do? What does not "display in your program" (i supposed you mean browser, or sumthin')?

Does anything get inserted to your MySQL Database? What do you mean by "together with other records"? - Does that mean it cannot be shown when anything else is shown, or that some other records you are too lazy to define, won't show neither?

Uhm..

So you spammed this post with code.. What is it supposed to do? What does it fail to do? What does not "display in your program" (i supposed you mean browser, or sumthin')?

Does anything get inserted to your MySQL Database? What do you mean by "together with other records"? - Does that mean it cannot be shown when anything else is shown, or that some other records you are too lazy to define, won't show neither?

no what i mean is actually,that code the whole code was fully functionable..can upload image..but since i've added that code in my adding record only the html code above and i put the php code in my display_records.php together with my other records..when i add new record and upload image,well its almost done,displayed the succesfully message but when i view the records,only the informations were displayed in my table and not the image of the user..

Are we talking about a html <table> or a MySQL table?

It seems you're posting the actual image data into your MySQL table - why don't you just post the link to the uploaded image, and then do a <img src=\"".$row."\">.

Are we talking about a html <table> or a MySQL table?

It seems you're posting the actual image data into your MySQL table - why don't you just post the link to the uploaded image, and then do a <img src=\"".$row."\">.

ah yeah.. in my mysql table when i veiw records..hmm you have a point there that i should put a link in the table to view the image of the user instead of displaying their images in one table..it's too large right to display the image in a single table so i should post a link over the table..hmm ok i'll try what you've advise..i'll pm if it is not work or error occur in my code..tnx..! :)

ah yeah.. in my mysql table when i veiw records..hmm you have a point there that i should put a link in the table to view the image of the user instead of displaying their images in one table..it's too large right to display the image in a single table so i should post a link over the table..hmm ok i'll try what you've advise..i'll pm if it is not work or error occur in my code..tnx..! :)

how do i save a link in mysql table (what datatype etc.)

Are we talking about a html <table> or a MySQL table?

It seems you're posting the actual image data into your MySQL table - why don't you just post the link to the uploaded image, and then do a <img src=\"".$row."\">.

Guys, there's a problem lies on my code...cant display the image in viewing candidates..i already put the code <img src=\"".$row['image']."\"> as what you had said in my code in viewing but it seems it didn't work out..
here's my adding record..

add_new.php

<?php
/* 
    NEW.PHP
    Allows user to create a new entry in the database
*/
    
    // creates the new record form
    // since this form is used multiple times in this file, I have made it a function that is easily reusable
    function renderForm($name, $position, $partyname, $error)
    {
        ?>
                                       
                              
            <?php 
                // if there are any errors, display them
                if ($error != '')
                {
                    echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
                }
            ?>                

            <form action="" enctype=multipart/form-data method="post">
           
                  <center><table width="50%" cellspacing="0" cellpadding="4" border="0">
               <tr> <td width="40%">First Name:</td><td width="80%"><input type="text" name="f_name"/></td></tr><br>
               <tr> <td width="40%">Last Name:</td><td width="80%"><input type="text" name="l_name"/></td></tr><br>
               <tr> <td width="40%">Middle Name:</td><td width="80%"><input type="text" name="m_name"/></td></tr><br>
		<tr><td width="40%">Position:</td><br>

<?php
    include('connect-db.php');

   
    $result = mysql_query("SELECT * FROM positions") 
        or die(mysql_error());  

	echo"<td width=80%><select name=position>";
    while($row = mysql_fetch_array( $result )) {

        echo '<option value="'.$row['position'].'">' . $row['position'] . '</option>';  
	
       }
        
    echo "</select></td></tr>";


?>
                <tr><td width="40%">Party Name:</td>

<?php
    include('connect-db.php');

   
    $result = mysql_query("SELECT * FROM partynames") 
        or die(mysql_error());  
 
	echo"<td width=80%><select name=partyname>";
    while($row = mysql_fetch_array( $result )) { 

        echo '<option value="'.$row['partyname'].'">' . $row['partyname'] . '</option>';  
	
       }
        
    echo "</select></td></tr>";
    



?>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
</form>
                 <tr><td></td><td></td></tr>


                <tr><td></td><td align="left"><input type="submit" name="submit" value="Add"></td></tr>
                </table>
            </form>
        
        <?php    
    }

    // connect to the database
    include('connect-db.php');
    
    // check if the form has been submitted. If it has, start to process the form and save it to the database
    if (isset($_POST['submit']))
    {    
        // get form data, making sure it is valid
            $f_name = htmlspecialchars($_POST['f_name']);
            $l_name = htmlspecialchars($_POST['l_name']);
            $title = htmlspecialchars($_POST['title']);
            $imgdata = htmlspecialchars($_POST['imgdata']);
            $m_name = htmlspecialchars($_POST['m_name']);
	    $position = htmlspecialchars($_POST['position']);
            $partyname = htmlspecialchars($_POST['partyname']);


        // check to make sure both fields are entered
        if (f_name == '' || l_name == '' || title == '' || imgdata == '' || m_name == '' || position == '' || partyname == '')
            {
            // generate error message
            $error = 'ERROR: Please fill in all required fields!';
            
            // if either field is blank, display the form again
             renderForm($id,$f_name, $l_name, $title, $imgdata, $m_name, $position, $partyname, $error);
            }
        else
        {
            // save the data to the database
             mysql_query("INSERT candidates SET f_name='$f_name', l_name='$l_name', title='$title', imgdata='$imgdata', m_name='$m_name', position='$position', partyname='$partyname'")
                    or die(mysql_error()); 
            
            echo"<br><br><center>Succesfully added!";    
        }
    }
    else
    // if the form hasn't been submitted, display the form
    {
        renderForm('','','','','','','','');
    }
    if ($_REQUEST[completed] == 1) {
        // Need to add - check for large upload. Otherwise the code
        // will just duplicate old file ;-)
        // ALSO - note that latest.img must be public write and in a
        // live appliaction should be in another (safe!) directory.
        move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
        $instr = fopen("latest.img","rb");
        $image = addslashes(fread($instr,filesize("latest.img")));
        if (strlen($instr) < 149000) {
                mysql_query ("insert into candidates (title, imgdata) values (\"".
                $_REQUEST[whatsit].
                "\", \"".
                $image.
                "\")");
        } else {
                $errmsg = "Too large!";
        }
}


// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
        header("Content-type: image/jpeg");
        print $bytes;
        exit ();
        }
?>

view_records.php

<?php
    include('connect-db.php');

   
    $result = mysql_query("SELECT * FROM candidates") 
        or die(mysql_error());
        
    
   echo "<table width='600' cellspacing='0' cellpadding='0' border='1' align='center'>";
    echo "<tr> <th bgcolor='lightblue'>Picture</th><th bgcolor='lightblue'>FirstName</th><th bgcolor='lightblue'>LastName</th><th bgcolor='lightblue'>MiddleName</th><th bgcolor='lightblue'>Position</th> <th bgcolor='lightblue'>PartyName</th> <th bgcolor='lightblue'>Action</th></tr>";

    // loop through results of database query, displaying them in the table
    while($row = mysql_fetch_array( $result )) {
        
        // echo out the contents of each row into a table
        echo '<td><center><img src=\''.$row['imgdata'] .\''> '</td>';
        echo '<td><center>' . $row['f_name'] . '</td>';
        echo '<td><center>' . $row['l_name'] . '</td>';
        echo '<td><center>' . $row['m_name'] . '</td>';
        echo '<td><center>' . $row['position'] . '</td>';
	echo '<td><center>' . $row['partyname'] . '</td>';
        echo '<td><center><a href="edit_candidates.php?id=' . $row['id'] . '">Modify</a>&nbsp;&nbsp;&nbsp;<a href="delete_candidates.php?id=' . $row['id'] . '">Delete</td>';
        echo "</tr>";  
    } 

   
    echo "</table>";
?>

Pls find out whats the problem lies about. i need to implement it..tnx..

here's the error in my program..

Warning: Unexpected character in input: '\' (ASCII=92) state=1 in C:\wamp\www\41e1\candidate\view_records.php on line 121

can i use this code to upload pdf files and word or excel files?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.