使用PHP从Flickr中选择图像并将其存储在数据库中


Selecting images from Flickr and storing them in a Database using PHP

我正在编写一段从Flickr打印图像的代码。根据用户的输入,代码查找相应的图像。

一旦图像打印在页面上,我希望能够做出选择,并将选择保存到数据库或其他地方,我可以检索它们,以便编辑它们或最终在制作自己的拼贴页面中使用它们。

我用来检索Flickr图片的代码如下:
<?php
//choices of tags, number of pictures, tag search based on given tags
//send back in Json format and decode json
    $api_key = '4eb66ae95c7e8fb8dd729ebf61541d79';
    if(isset($_POST['submit']))
{
    $tag1 = htmlspecialchars($_POST['tag1']);
    $tag2 = htmlspecialchars($_POST['tag2']);
    $tag3 = htmlspecialchars($_POST['tag3']);
    $tag = $tag1.",".$tag2.",".$tag3;
    $perPage = 25;
    $url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search';
    $url.= '&api_key='.$api_key;
    $url.= '&tags='.$tag;
    $url.= '&per_page='.$perPage;
    $url.= '&format=json';
    $url.= '&nojsoncallback=1';
    $response = json_decode(file_get_contents($url));
    $photo_array = $response->photos->photo;
     //check each photo from server, and specifiy url to print   
    foreach($photo_array as $single_photo)
    {
        $farm_id = $single_photo->farm;
        $server_id = $single_photo->server;
        $photo_id = $single_photo->id;
        $secret_id = $single_photo->secret;
        $size = 'm';
        $title = $single_photo->title;
        $photo_url = 'http://farm'.$farm_id.'.staticflickr.com/'.$server_id.'/'.$photo_id.'_'.$secret_id.'_'.$size.'.'.'jpg';
        print "<img title='".$title."' src='".$photo_url."' />";
    }
    }
?>

所以我的问题是,有没有一种方法可以使打印的图像可点击/可选择和/或一种方法来存储图像,使用数据库或其他东西?

我认为你的问题太宽泛了,但这里有一些提示。

首先,在你的img标签上添加一些类

print_r "<img class="clickable" title='".$title."' src='".$photo_url."' />"

使用AJAX将照片url发送到另一个PHP页面。下面是一个使用jQuery的例子。

$('.body').on('click', '.clickable', function (){
    //use on because your <img> is dynamic
    var photo_url = $(this).prop('src);
    $.ajax({
            url: 'myApp/saveImg.php',
            data: {'url': photo_url},
            type: 'POST',
            success: function(){
                alert('ok');
            }
            error: function(){
                alert('error');
            }                
});

你的saveimage .php是

$img_url = $_POST['url'];
$con = new PDO("mysql:host=ip_number;port=port_number;dbname=dbname", 'user', 'pass', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'));
        $sql = 'INSERT INTO table_name VALUES("'.$img_url.'")';
        $result = $con->query($sql);
 return 'URL inserted';

就像这样。试着适应你的需求。

希望能有所帮助。