我试图在php中使用ajax从数据库中获取图像

时间:2015-01-03 12:02:26

标签: javascript php ajax

这里是我的代码我试图使用ajax从数据库中获取图像,但它无法正常工作,请将我解雇。当我尝试使用锚标记获取图像时图像上传正常工作,但它在另一页上显示我的图像。但我想在窗口加载时在同一页面上。

getImage.php

if(filter_has_var(INPUT_GET, "image_id") !== false && filter_input(INPUT_GET, 'image_id', FILTER_VALIDATE_INT) !== false)
{

$image_id = filter_input(INPUT_GET, "image_id", FILTER_SANITIZE_NUMBER_INT);
try     {

    $dbh = new PDO("mysql:host=localhost;dbname=flipbook", 'root', '');


    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    $sql = "SELECT image, image_type FROM testblob WHERE user_id=$image_id";

    /*** prepare the sql ***/
    $stmt = $dbh->prepare($sql);


    $stmt->execute(); 

    /*** set the fetch mode to associative array ***/
    $stmt->setFetchMode(PDO::FETCH_ASSOC);


    $array = $stmt->fetch();


    if(sizeof($array) == 2)
        {

            header("Content-type: ".$array['image_type']);


            echo $array['image'];
        }
    else
        {
        throw new Exception("Out of bounds Error");
        }
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
catch(Exception $e)
    {
    echo $e->getMessage();
    }
    }


 else
    {
    echo 'Please use a real id number';
    }
}

的index.php

<body onload="showUserProfilePic(<?php echo $_SESSION['current_user_id'];?>)">
<div id="txtHint">Child Picture will be listed here.</div>
<script>
        function showUserProfilePic(str) {
            //alert(str);
            if (str == "") {
                document.getElementById("txtHint").innerHTML = "";
                return;
            } else { 
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                    }
                }
                xmlhttp.open("GET","getImage.php?image_id="+str,true);
                xmlhttp.send();
            }
        }

1 个答案:

答案 0 :(得分:0)

尝试使用

$sql = "SELECT image, image_type FROM testblob WHERE user_id='" . $image_id . "';

你的标签在哪里?