0

this is my create and read.php files problem is that in read.php file image is not being displayed only its file name is displaying

// crate.php


    <div class="control-group <?php echo !empty($imgError)?'error':'';?>">
                        <label class="control-label">Image Upload</label>
                        <div class="controls">
                            <input name="image"   type="file"  placeholder="image" value="<?php echo !empty($image)?$image:'';?>">
                            <?php if (!empty($imgError)): ?>
                                <span class="help-inline"><?php echo $imgError;?></span>
                            <?php endif;?>
                            <?php

// check if a file was submitted
if(!isset($_FILES['image']))
{
    echo '<p>Please select a file</p>';
}
else
{
    try {
    $msg= upload();  //this will upload our image
    echo $msg;  //Message showing success or failure.
    }
    catch(Exception $e) {
    echo $e->getMessage();
    echo 'Sorry, could not upload file';
    }
}

// the upload function

function upload() {
    include "database.php";
    $maxsize = 10000000; //set to approx 10 MB

    //check associated error code
    if($_FILES['image']['error']==UPLOAD_ERR_OK) {

        //check whether file is uploaded with HTTP POST
        if(is_uploaded_file($_FILES['image']['tmp_name'])) {    

            //checks size of uploaded image on server side
            if( $_FILES['image']['size'] < $maxsize) {  

               //checks whether uploaded file is of image type
              //if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if(strpos(finfo_file($finfo, $_FILES['image']['tmp_name']),"image")===0) {    

                    // prepare the image for insertion
                    $imgData =addslashes (file_get_contents($_FILES['image']['tmp_name']));

                    // put the image in the db...
                    // database connection
                    $link=mysqli_connect($dbHost, $dbUsername, $dbUserPassword) OR DIE (mysql_error());

                    // select the db
                    mysqli_select_db ($dbName) OR DIE ("Unable to select db".mysql_error());

                    // our sql query
                    $sql = "INSERT INTO customers
                    (image)
                    VALUES
                    ('{$imgData}', '{$_FILES['image']['name']}');";

                    // insert the image
                    mysqli_query($sql) or die("Error in Query: " . mysqli_error());
                    $msg='<p>Image successfully saved in database with id ='. mysqli_insert_id().' </p>';
                }
                else
                    $msg="<p>Uploaded file is not an image.</p>";
            }
             else {
                // if the file is not less than the maximum allowed, print an error
                $msg='<div>File exceeds the Maximum File limit</div>
                <div>Maximum File limit is '.$maxsize.' bytes</div>
                <div>File '.$_FILES['image']['name'].' is '.$_FILES['image']['size'].
                ' bytes</div><hr />';
                }
        }
        else
            $msg="File not uploaded successfully.";

    }
    else {
        $msg= file_upload_error_message($_FILES['image']['error']);
    }
    return $msg;
}

// Function to return error message based on error code

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
?>


// read.php



              <div class="control-group">
                        <label class="control-label">Image</label>
                        <div class="controls">
                            <label class="checkbox">
                            <?php

$dbName = 'crud_tutorial' ;
$dbHost = 'localhost' ;
$dbUsername = 'root';
$dbUserPassword = '';
//include "database.php";
 // just so we know it is broken
 error_reporting(E_ALL);
 // some basic sanity checks
 if(isset($_GET['id']) && is_numeric($_GET['id'])) {
     //connect to the db
     $link = mysql_connect("$dbHost", "$dbUsername", "$dbUserPassword")
     or die("Could not connect: " . mysql_error());

     // select our database
     mysql_select_db("crud_tutorial") or die(mysql_error());

     // get the image from the db
     $sql = "SELECT image FROM customers WHERE id=" .$_GET['id'] . ";";

     // the result of the query
     $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());

     // set the header for the image
     //header("Content-type: image/jpeg");
     //exit();
     echo mysql_result($result, 0);

     // close the db link
     mysql_close($link);
 }
 else {
     echo 'Please use a real id number';
 }
 echo $data['image'];

?>
2
Contributors
5
Replies
27
Views
2 Years
Discussion Span
Last Post by anmol.raghuvanshi1
0

YOur read.php starts from <Div which is html i think.Please paste code of every file which is included seperate.You can paste code in a single window but star commenting out the name of the file, before it starts.I got confused reading this code.

0
//read.php

<?php
     ob_start();
    require 'database.php';
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }

    if ( null==$id ) {
        header("Location: index.php");
    } else {
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM customers where id = ?";
        $q = $pdo->prepare($sql);
        $q->execute(array($id));
        $data = $q->fetch(PDO::FETCH_ASSOC);
        Database::disconnect();
    }
    ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">

                <div class="span10 offset1">
                    <div class="row">
                        <h3>Read Record</h3>
                    </div>

                    <div class="form-horizontal" >
                      <div class="control-group">
                        <label class="control-label">Name</label>
                        <div class="controls">
                            <label class="checkbox">
                                <?php echo $data['name'];?>
                            </label>
                        </div>
                      </div>
                      <div class="control-group">
                        <label class="control-label">Email Address</label>
                        <div class="controls">
                            <label class="checkbox">
                                <?php echo $data['email'];?>
                            </label>
                        </div>
                      </div>
                      <div class="control-group">
                        <label class="control-label">Mobile Number</label>
                        <div class="controls">
                            <label class="checkbox">
                                <?php echo $data['mobile'];?>
                            </label>
                        </div>
                      </div>

                      <div class="control-group">
                        <label class="control-label">Image</label>
                        <div class="controls">
                            <label class="checkbox">
                            <?php
ob_start();
$dbName = 'crud_tutorial' ;
$dbHost = 'localhost' ;
$dbUsername = 'root';
$dbUserPassword = '';
//include "database.php";
 // just so we know it is broken
 error_reporting(E_ALL);
 // some basic sanity checks
 if(isset($_GET['id']) && is_numeric($_GET['id'])) {
     //connect to the db
     $link = mysql_connect("$dbHost", "$dbUsername", "$dbUserPassword")
     or die("Could not connect: " . mysql_error());

     // select our database
     mysql_select_db("crud_tutorial") or die(mysql_error());

     // get the image from the db
     $sql = "SELECT image FROM customers WHERE id=" .$_GET['id'] . ";";

     // the result of the query
     $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());

     // set the header for the image
     //header("Content-type: image/jpeg");
     //exit();
     echo mysql_result($result, 0);

     // close the db link
     mysql_close($link);
 }
 else {
     echo 'Please use a real id number';
 }
 echo $data['image'];
 ob_end_flush();
?>

                            </label>
                        </div>
                      </div>

                        <div class="form-actions">
                          <a class="btn" href="index.php">Back</a>
                       </div>


                    </div>
                </div>

    </div> <!-- /container -->
  </body>
</html>
0
//database.php

<?php
class Database
{
private static $dbName = 'crud_tutorial' ;
    private static $dbHost = 'localhost' ;
    private static $dbUsername = 'root';
    private static $dbUserPassword = '';
    private static $cont  = null;
     public function __construct() {
       die('Init function is not allowed');
    }
     public static function connect()
    {
       // One connection through whole application
       if ( null == self::$cont )
       {     
        try
        {
          self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword); 
        }
        catch(PDOException $e)
        {
          die($e->getMessage()); 
        }
       }
       return self::$cont;
    }
     public static function disconnect()
    {
        self::$cont = null;
    }
}
?>
0
// create.php


<?php

    require 'database.php';




    if ( !empty($_POST)) {
        // keep track validation errors
        $nameError = null;
        $emailError = null;
        $mobileError = null;
        $imgError=null;

        // keep track post values
        $name = $_POST['name'];
        $email = $_POST['email'];
        $mobile = $_POST['mobile'];
        $img = $_POST['image'];

        // validate input
        $valid = true;
        if (empty($name)) {
            $nameError = 'Please enter Name';
            $valid = false;
        }

        if (empty($email)) {
            $emailError = 'Please enter Email Address';
            $valid = false;
        } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
            $emailError = 'Please enter a valid Email Address';
            $valid = false;
        }

        if (empty($mobile)) {
            $mobileError = 'Please enter Mobile Number';
            $valid = false;
        }
        if (empty($img)) {
            $imgError = 'Please upload image ';
            $valid = false;
        }

        // insert data
        if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO customers (name,email,mobile,image) values(?, ?, ?,?)";
            $q = $pdo->prepare($sql);
            $q->execute(array($name,$email,$mobile,$img));
            Database::disconnect();
            header("location: index.php");  
        }
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">

                <div class="span10 offset1">
                    <div class="row">
                        <h3>Create Record</h3>
                    </div>


                    <form  class="form-horizontal" action="create.php" method="post">

                      <div class="control-group <?php echo !empty($nameError)?'error':'';?>">
                        <label class="control-label">Name</label>
                        <div class="controls">
                            <input name="name" type="text"  placeholder="Name" value="<?php echo !empty($name)?$name:'';?>">
                            <?php if (!empty($nameError)): ?>
                                <span class="help-inline"><?php echo $nameError;?></span>
                            <?php endif; ?>
                        </div>
                      </div>

                      <!--<div class="control-group <?php echo !empty($Error)?'error':'';?>">
                          <label class="Gender">Gender:</label>
                          <div class="controls">
                          <input type="radio" name="gender"<?php if (isset($gender) && $gender=="female") echo "checked";?>
                            value="female">Female
                              <input type="radio" name="gender"<?php if (isset($gender) && $gender=="male") echo "checked";?>
                                 value="male">Male
                    </div>
                     </div>
-->                   
                      <div class="control-group <?php echo !empty($emailError)?'error':'';?>">
                        <label class="control-label">Email Address</label>
                        <div class="controls">
                            <input name="email" type="text" placeholder="Email Address" value="<?php echo !empty($email)?$email:'';?>">
                            <?php if (!empty($emailError)): ?>
                                <span class="help-inline"><?php echo $emailError;?></span>
                            <?php endif;?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($mobileError)?'error':'';?>">
                        <label class="control-label">Mobile Number</label>
                        <div class="controls">
                            <input name="mobile" type="text"  placeholder="Mobile Number" value="<?php echo !empty($mobile)?$mobile:'';?>">
                            <?php if (!empty($mobileError)): ?>
                                <span class="help-inline"><?php echo $mobileError;?></span>
                            <?php endif;?>
                        </div>
                      </div>

                    <div class="control-group <?php echo !empty($imgError)?'error':'';?>">
                        <label class="control-label">Image Upload</label>
                        <div class="controls">
                            <input name="image"   type="file"  placeholder="image" value="<?php echo !empty($image)?$image:'';?>">
                            <?php if (!empty($imgError)): ?>
                                <span class="help-inline"><?php echo $imgError;?></span>
                            <?php endif;?>
                            <?php

// check if a file was submitted
if(!isset($_FILES['image']))
{
    echo '<p>Please select a file</p>';
}
else
{
    try {
    $msg= upload();  //this will upload our image
    echo $msg;  //Message showing success or failure.
    }
    catch(Exception $e) {
    echo $e->getMessage();
    echo 'Sorry, could not upload file';
    }
}

// the upload function

function upload() {
    include "database.php";
    $maxsize = 10000000; //set to approx 10 MB

    //check associated error code
    if($_FILES['image']['error']==UPLOAD_ERR_OK) {

        //check whether file is uploaded with HTTP POST
        if(is_uploaded_file($_FILES['image']['tmp_name'])) {    

            //checks size of uploaded image on server side
            if( $_FILES['image']['size'] < $maxsize) {  

               //checks whether uploaded file is of image type
              //if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if(strpos(finfo_file($finfo, $_FILES['image']['tmp_name']),"image")===0) {    

                    // prepare the image for insertion
                    $imgData =addslashes (file_get_contents($_FILES['image']['tmp_name']));

                    // put the image in the db...
                    // database connection
                    $link=mysqli_connect($dbHost, $dbUsername, $dbUserPassword) OR DIE (mysql_error());

                    // select the db
                    mysqli_select_db ($dbName) OR DIE ("Unable to select db".mysql_error());

                    // our sql query
                    $sql = "INSERT INTO customers
                    (image)
                    VALUES
                    ('{$imgData}', '{$_FILES['image']['name']}');";

                    // insert the image
                    mysqli_query($sql) or die("Error in Query: " . mysqli_error());
                    $msg='<p>Image successfully saved in database with id ='. mysqli_insert_id().' </p>';
                }
                else
                    $msg="<p>Uploaded file is not an image.</p>";
            }
             else {
                // if the file is not less than the maximum allowed, print an error
                $msg='<div>File exceeds the Maximum File limit</div>
                <div>Maximum File limit is '.$maxsize.' bytes</div>
                <div>File '.$_FILES['image']['name'].' is '.$_FILES['image']['size'].
                ' bytes</div><hr />';
                }
        }
        else
            $msg="File not uploaded successfully.";

    }
    else {
        $msg= file_upload_error_message($_FILES['image']['error']);
    }
    return $msg;
}

// Function to return error message based on error code

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
?>



                        </div>
                      </div>

                      <div class="form-actions">
                          <button type="submit" class="btn btn-success">Create</button>
                          <a class="btn" href="index.php">Back</a>
                        </div>
                    </form>
                </div>

    </div> <!-- /container -->
  </body>
</html>
0

i am new to php and i have looked at the web for coding .....plz help me out

This question has already been answered. 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.