php解析json数据二种实例方法

 更新时间:2016年11月25日 16:28  点击:1508

 大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。


$json_string='{"id":1,"name":"111cn.net","email":"admin@111cn.net","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php


ecshop解析json类

if (!defined('EC_CHARSET'))
{
define('EC_CHARSET', 'utf-8');
}

class JSON
{
var $at   = 0;
var $ch   = '';
var $text = '';

function encode($arg, $force = true)
{
static $_force;
if (is_null($_force))
{
$_force = $force;
}

if ($_force && EC_CHARSET == 'utf-8' && function_exists('json_encode'))
{
return json_encode($arg);
}

$returnValue = '';
$c           = '';
$i           = '';
$l           = '';
$s           = '';
$v           = '';
$numeric     = true;

switch (gettype($arg))
{
case 'array':
foreach ($arg AS $i => $v)
{
if (!is_numeric($i))
{
$numeric = false;
break;
}
}

if ($numeric)
{
foreach ($arg AS $i => $v)
{
if (strlen($s) > 0)
{
$s .= ',';
}
$s .= $this->encode($arg[$i]);
}

$returnValue = '[' . $s . ']';
}
else
{
foreach ($arg AS $i => $v)
{
if (strlen($s) > 0)
{
$s .= ',';
}
$s .= $this->encode($i) . ':' . $this->encode($arg[$i]);
}

$returnValue = '{' . $s . '}';
}
break;

case 'object':
foreach (get_object_vars($arg) AS $i => $v)
{
$v = $this->encode($v);

if (strlen($s) > 0)
{
$s .= ',';
}
$s .= $this->encode($i) . ':' . $v;
}

$returnValue = '{' . $s . '}';
break;

case 'integer':
case 'double':
$returnValue = is_numeric($arg) ? (string) $arg : 'null';
break;

case 'string':
$returnValue = '"' . strtr($arg, array(
" "   => '\r',    " "   => '\n',    " "   => '\t',     ""   => '\b',
" "   => '\f',    '\'   => '\\',   '"'    => '"',
"" => 'u0000', "" => 'u0001', "" => 'u0002', "" => 'u0003',
"" => 'u0004', "" => 'u0005', "" => 'u0006', "" => 'u0007',
"" => '',     " " => 'u000b', " " => ' ',     "" => 'u000e',
"" => 'u000f', "" => 'u0010', "" => 'u0011', "" => 'u0012',
"" => 'u0013', "" => 'u0014', "" => 'u0015', "" => 'u0016',
"" => 'u0017', "" => 'u0018', "" => 'u0019', "" => 'u001a',
"" => 'u001b', "" => 'u001c', "" => 'u001d', "" => 'u001e',
"" => 'u001f'
)) . '"';
break;

case 'boolean':
$returnValue = $arg?'true':'false';
break;

default:
$returnValue = 'null';
}

return $returnValue;
}

function decode($text,$type=0) // 默认type=0返回obj,type=1返回array
{
if (empty($text))
{
return '';
}
elseif (!is_string($text))
{
return false;
}

if (EC_CHARSET === 'utf-8' && function_exists('json_decode'))
{
return $this->addslashes_deep_obj(json_decode(strips教程lashes($text),$type));
}

$this->at   = 0;
$this->ch   = '';
$this->text = strtr(stripslashes($text), array(
" "   => '', " "   => '', " "   => '', ""   => '',
"" => '', "" => '', "" => '', "" => '',
"" => '', "" => '', "" => '', "" => '',
"" => '', " " => '', " " => '', "" => '',
"" => '', "" => '', "" => '', "" => '',
"" => '', "" => '', "" => '', "" => '',
"" => '', "" => '', "" => '', "" => '',
"" => '', "" => '', "" => '', "" => '',
"" => ''
));

$this->next();
$return = $this->val();

$result = empty($type) ? $return : $this->object_to_array($return);

return addslashes_deep_obj($result);
}

/**
* triggers a PHP_ERROR
*
* @access   private
* @param    string    $m    error message
*
* @return   void
*/
function error($m)
{
trigger_error($m . ' at offset ' . $this->at . ': ' . $this->text, E_USER_ERROR);
}

/**
* returns the next character of a JSON string
*
* @access  private
*
* @return  string
*/
function next()
{
$this->ch = !isset($this->text{$this->at}) ? '' : $this->text{$this->at};
$this->at++;

return $this->ch;
}

/**
* handles strings
*
* @access  private
*
* @return  void
*/
function str()
{
$i = '';
$s = '';
$t = '';
$u = '';

if ($this->ch == '"')
{
while ($this->next() !== null)
{
if ($this->ch == '"')
{
$this->next();

return $s;
}
elseif ($this->ch == '\')
{
switch ($this->next())
{
case 'b':
$s .= '';
break;

case 'f':
$s .= ' ';
break;

case 'n':
$s .= ' ';
break;

case 'r':
$s .= ' ';
break;

case 't':
$s .= ' ';
break;

case 'u':
$u = 0;

for ($i = 0; $i < 4; $i++)
{
$t = (integer) sprintf('%01c', hexdec($this->next()));

if (!is_numeric($t))
{
break 2;
}
$u = $u * 16 + $t;
}

$s .= chr($u);
break;
case ''':
$s .= ''';
break;
default:
$s .= $this->ch;
}
}
else
{
$s .= $this->ch;
}
}
}

$this->error('Bad string');
}

/**
* handless arrays
*
* @access  private
*
* @return  void
*/
function arr()
{
$a = array();

if ($this->ch == '[')
{
$this->next();

if ($this->ch == ']')
{
$this->next();

return $a;
}

while (isset($this->ch))
{
array_push($a, $this->val());

if ($this->ch == ']')
{
$this->next();

return $a;

}
elseif ($this->ch != ',')
{
break;
}

$this->next();

}

$this->error('Bad array');
}
}

/**
* handles objects
*
* @access  public
*
* @return  void
*/
function obj()
{
$k = '';
$o = new StdClass();

if ($this->ch == '{')
{
$this->next();

if ($this->ch == '}')
{
$this->next();

return $o;
}

while ($this->ch)
{
$k = $this->str();

if ($this->ch != ':')
{
break;
}

$this->next();
$o->$k = $this->val();

if ($this->ch == '}')
{
$this->next();

return $o;
}
elseif ($this->ch != ',')
{
break;
}

$this->next();
}
}

$this->error('Bad object');
}

/**
* handles objects
*
* @access  public
*
* @return  void
*/
function assoc()
{
$k = '';
$a = array();

if ($this->ch == '<')
{
$this->next();

if ($this->ch == '>')
{
$this->next();

return $a;
}

while ($this->ch)
{
$k = $this->str();

if ($this->ch != ':')
{
break;
}

$this->next();
$a[$k] = $this->val();

if ($this->ch == '>')
{
$this->next();

return $a;
}
elseif ($this->ch != ',')
{
break;
}

$this->next();
}
}

$this->error('Bad associative array');
}

/**
* handles numbers
*
* @access  private
*
* @return  void
*/
function num()
{
$n = '';
$v = '';

if ($this->ch == '-')
{
$n = '-';
$this->next();
}

while ($this->ch >= '0' && $this->ch <= '9')
{
$n .= $this->ch;
$this->next();
}

if ($this->ch == '.')
{
$n .= '.';

while ($this->next() && $this->ch >= '0' && $this->ch <= '9')
{
$n .= $this->ch;
}
}

if ($this->ch == 'e' || $this->ch == 'E')
{
$n .= 'e';
$this->next();

if ($this->ch == '-' || $this->ch == '+')
{
$n .= $this->ch;
$this->next();
}

while ($this->ch >= '0' && $this->ch <= '9')
{
$n .= $this->ch;
$this->next();
}
}

$v += $n;

if (!is_numeric($v))
{
$this->error('Bad number');
}
else
{
return $v;
}
}

/**
* handles words
*
* @access  private
*
* @return  mixed
*/
function word()
{
switch ($this->ch)
{
case 't':

if ($this->next() == 'r' && $this->next() == 'u' && $this->next() == 'e')
{
$this->next();

return true;
}
break;

case 'f':
if ($this->next() == 'a' && $this->next() == 'l' && $this->next() == 's' && $this->next() == 'e')
{
$this->next();

return false;
}
break;

case 'n':
if ($this->next() == 'u' && $this->next() == 'l' && $this->next() == 'l')
{
$this->next();

return null;
}
break;
}

$this->error('Syntax error');
}

/**
* generic value handler
*
* @access  private
*
* @return  mixed
*/
function val()
{
switch ($this->ch)
{
case '{':
return $this->obj();

case '[':
return $this->arr();

case '<':
return $this->assoc();

case '"':
return $this->str();

case '-':
return $this->num();

default:
return ($this->ch >= '0' && $this->ch <= '9') ? $this->num() : $this->word();
}
}

/**
* Gets the properties of the given object recursion
*
* @access private
*
* @return array
*/
function object_to_array($obj)
{
$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($_arr as $key => $val)
{
$val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}

 

/**
* 递归方式的对变量中的特殊字符进行转义
*
* @access  public
* @param   mix     $value
*
* @return  mix
*/
function addslashes_deep($value)
{
if (empty($value))
{
return $value;
}
else
{
return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
}
}

/**
* 将对象成员变量或者数组的特殊字符进行转义
*
* @access   public
* @param    mix        $obj      对象或者数组
* @author   Xuan Yan
*
* @return   mix                  对象或者数组
*/
function addslashes_deep_obj($obj)
{
if (is_object($obj) == true)
{
foreach ($obj AS $key => $val)
{
$obj->$key =$this-> addslashes_deep($val);
}
}
else
{
$obj = addslashes_deep($obj);
}

return $obj;
}

/**
* 递归方式的对变量中的特殊字符去除转义
*
* @access  public
* @param   mix     $value
*
* @return  mix
*/
function stripslashes_deep($value)
{
if (empty($value))
{
return $value;
}
else
{
return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
}
}


/**
* 将JSON传递的参数转码
*
* @param string $str
* @return string
*/
function json_str_iconv($str)
{
if (EC_CHARSET != 'utf-8')
{
if (is_string($str))
{
return ecs_iconv('utf-8', EC_CHARSET, $str);
}
elseif (is_array($str))
{
foreach ($str as $key => $value)
{
$str[$key] = json_str_iconv($value);
}
return $str;
}
elseif (is_object($str))
{
foreach ($str as $key => $value)
{
$str->$key = json_str_iconv($value);
}
return $str;
}
else
{
return $str;
}
}
return $str;
}

}

$string='{"email":"cc@126.com","content":"this is a  just a     test","type":"0","id":"13","enabled_captcha":"0","captcha":"","rank":"5"}';
$json=new JSON();

$cmt = $json->json_str_iconv($string);  //字符转码


$cmt  = $json->decode($cmt);    //解码

print_r($cmt);

PHP捆绑PDFLIB库也许是最好的web出版平台了。一对典型的用法:

需求小册子
电子商务发货单

通过这个指南,你可以学会怎样使用php教程4中的PDF扩展来创建PDF文档。
我们也把焦点放在用mysql教程数据来创建PDF文档。

内容摘要


安装PDFLib 3.0.1 和有PDF支持的PHP4.01pl2(译注:你可以安装最新的php4.03pl1)

提取PDF文档
(我假设你有一点配置php的经验)



安装PDFLib和有PDF支持的PHP。

需求:

PHP 4.02+ 从 http://php.net 下载
PDFLib 3.0.1 从 http://www.pdflib.com 下载

这是一个怎样让PDFLib3.0.1和php4一起工作的小秘方:(老外很幽默的^_^)

直接从http://www.php.net下载 ext/pdf/pdf.c的补丁来支持PDFLib v 3.0.1

下载PDFLib3.0.1从此处 http://www.pdflib.com
适用的补丁你可以在此找到 http://www.pdflib.com/pdflib/patches.html

配置,Make和安装PDFLib

#./configure --enabled-shared-pdflib
#make
#make install
你会使得 PDFLib 安装在 /usr/local/lib .


配置 PHP
#./configure --with-apxs=/usr/bin/apxs
--with-gd --with-pdflib=/usr/local --with-mysql=/usr/local
--with-config-file-path=/etc/httpd --with-zlib-dir=/usr
--with-ttf=/usr/local/include
--with-jpeg-dir=/usr --with-tiff-dir=/usr
--with-system-regex=yes --enable-debug=no

#make
#make install



更新系统库
插入 /usr/local/lib 进 /etc/ld.so.conf (文件)

#/sbin/ldconfig



测试和验证
现在你需要重启apache
#apachectl restart


拷贝pdfclock.php 到的httpd目录中(就是web目录)...测试....一切正常。

重要信息

要使得PHPLIb和字体一起工作你必须注意PDFLib手册中的UPR部分。
最简单的用PDFLib使用字体的办法是拷贝PDFlib tar包中的标准UPR描述文件(fonts/pdflib.upr)到你的工作目录。

提取PDF文档
现在我们已经作好了如飞地生成PDF文档的条件!


在这个小例子中我们要生成FLYStore公司的需求小册子,当然是从目录数据库教程中提取数据。




准备数据库
我假设你有一点数据库的经验,最小限度,我真的只希望你懂得怎样创建一个数据库并向其中插入表。
创建表 catalogue:

create table catalogue(
id smallint(8) unsigned DEFAULT '0' NOT NULL,
item varchar(100) DEFAULT '' NOT NULL,
description tinytext,
img_data longblob,
imgname varchar(60),
imgsize varchar(60),
imgtype varchar(60),
price smallint(8) unsigned DEFAULT '0' NOT NULL,
PRIMARY KEY (id),
KEY item (item(20))
);



送出MIME头信息
为了让我们的正确地显示出来,我们需要送出正确的头信息到用户的浏览器。
在PHP中我们可以用header函数实现。下面的代码送出正确的MIME类型到浏览器。

header( "Content-type: application/pdf" );
header( "Content-Disposition: attachment; filename=modulo.pdf" );
header( "Content-Description: PHP3 Generated Data" );



重要信息
你必须知道的是在送出头信息前不能输出任何东西。一个常见的错误是在文件的开头存在空格。


从mysql中取数

这儿我们用一个从目录数据中提数据的简单代码片断。
<?php

$link = mysql_connect ("127.0.0.1", "flyadm", "flystore")
or die ("Could not connect");

mysql_select_db ("flystore", $link);

$result = mysql_query ("SELECT * FROM catalogue", $link)
or die ("Invalid query");

$data = mysql_fetch_row ($result);
....
....
mysql_close ($link);


?>


生成PDF文件

为了生成PDF文档,我们需要作经过以下步骤:


打开一个PDF流,并使它和一个句柄关联:
$pdf = PDF_open();

(Optional) Set document information like Author, Title, Subject, etc
(可选的)设置文档信息,如作者,标题,主题,等

开始一个新页(PDF文件可以用不同的版面生成不同的页,比如肖像,前景...):
PDF_begin_page($pdf, 595, 842);
(可选的)设置一个超链接:
PDF_add_outline($pdf, "Item ".$data[1]);

选择字体类型, 尺寸 (pdf_set_font($pdf, "Helvetica-Bold" , 20, winansi);) 表现模式

插入文本在X.y位置:
PDF_show_xy($pdf, "Item : " .$data[1], 100, 700);

或插入图片在X.Y位置:
pdf_place_image($pdf, $im, 100, 300, 3);

刷新文本缓冲区并关闭PDF流。
PDF Coordinate Systems
What we need to do to locate a string or picture in some part of the PDF page,
在PDF页的很多地方我们需要定位字符串和图片,转换英制单位到DTP点值.

在PDFLIB手册的45页写到:



".. .缺省的坐标系统的原点在页面的左下角,用DTP点作为单位:
1 pt = 1 inch /72 = 25.4mm /72 = 0.3528 mm
"


这儿是生成PDF文件的代码片断:
<?php

$pdf = PDF_open();
pdf_set_info_author($pdf, "Luca Perugini");
PDF_set_info_title($pdf, "Brochure for FlyStore");
pdf_set_info_creator($pdf, "See Author");
pdf_set_info_subject($pdf, "FlyStore");
PDF_begin_page($pdf, 595, 842);
PDF_add_outline($pdf, "Item ".$data[1]);
pdf_set_font($pdf, "Helvetica-Bold" , 20, winansi);
pdf_set_text_rendering($pdf, 0);
pdf_show_xy($pdf, "FlyStore Catalogue 2000",50,780);

PDF_show_xy($pdf, "Item : " .$data[1], 100, 700);

PDF_show_xy($pdf, "Description : " .$data[2], 100, 620);

$im = PDF_open_jpeg($pdf, "pass4_sml.jpg");
pdf_place_image($pdf, $im, 100, 300, 3);
pdf_close_image ($im);

pdf_stroke($pdf);
PDF_end_page($pdf);
PDF_close($pdf);


?>

php 文件在线压缩代码


class PHPZip
{
 function Zip($dir, $zipfilename)
 {
     if (@function_exists('gzcompress'))
  { 
   $curdir = getcwd();
   if (is_array($dir))
   {
     $filelist = $dir;
   }
   else
   {
    $filelist = $this -> GetFileList($dir);
   }
   
   if ((!empty($dir))&&(!is_array($dir))&&(file_exists

($dir))) chdir($dir);
   else chdir($curdir);

   if (count($filelist)>0)
   {
    foreach($filelist as $filename)
    {
     if (is_file($filename))
     {
      $fd = fopen ($filename,

"r");
      $content = @fread ($fd,

filesize ($filename));
      fclose ($fd);

      if (is_array($dir))

$filename = basename($filename);
      $this -> addFile($content,

$filename);
     }
    }
    $out = $this -> file();

    chdir($curdir);
    $fp = fopen($zipfilename, "w");
    fwrite($fp, $out, strlen($out));
    fclose($fp);
   }
   return 1;
  }
  else return 0;
 }

 function GetFileList($dir)
 {
  if (file_exists($dir))
  {
   $args = func_get_args();
   $pref = $args[1];
    
   $dh = opendir($dir);
   while($files = readdir($dh))
   {
    if (($files!=".")&&($files!=".."))
    {
     if (is_dir($dir.$files))
     {
      $curdir = getcwd();
      chdir($dir.$files);
      $file = array_merge($file,

$this -> GetFileList("", "$pref$files/"));
      chdir($curdir);
     }
     else $file[]=$pref.$files;
    }
   }
   closedir($dh);
  }
  return $file;
 }

    var $datasec      = array();
    var $ctrl_dir     = array();
    var $eof_ctrl_dir = "x50x4bx05x06x00x00x00x00";
    var $old_offset   = 0;

    /**
     * Converts an Unix timestamp to a four byte DOS date and time format

(date
     * in high two bytes, time in low two bytes allowing magnitude

comparison).
     *
     * @param  integer  the current Unix timestamp
     *
     * @return integer  the current date in a four byte DOS format
     *
     * @access private
     */
    function unix2DosTime($unixtime = 0) {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

        if ($timearray['year'] < 1980) {
         $timearray['year']    = 1980;
         $timearray['mon']     = 1;
         $timearray['mday']    = 1;
         $timearray['hours']   = 0;
         $timearray['minutes'] = 0;
         $timearray['seconds'] = 0;
        } // end if

        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] <<

21) | ($timearray['mday'] << 16) |
                ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) |

($timearray['seconds'] >> 1);
    } // end of the 'unix2DosTime()' method


    /**
     * Adds "file" to archive
     *
     * @param  string   file contents
     * @param  string   name of the file in the archive (may contains the

path)
     * @param  integer  the current timestamp
     *
     * @access public
     */
    function addFile($data, $name, $time = 0)
    {
        $name     = str_replace('\', '/', $name);

        $dtime    = dechex($this->unix2DosTime($time));
        $hexdtime = 'x' . $dtime[6] . $dtime[7]
                  . 'x' . $dtime[4] . $dtime[5]
                  . 'x' . $dtime[2] . $dtime[3]
                  . 'x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');

        $fr   = "x50x4bx03x04";
        $fr   .= "x14x00";            // ver needed to extract
        $fr   .= "x00x00";            // gen purpose bit flag
        $fr   .= "x08x00";            // compression method
        $fr   .= $hexdtime;             // last mod time and date

        // "local file header" segment
        $unc_len = strlen($data);
        $crc     = crc32($data);
        $zdata   = gzcompress($data);
        $c_len   = strlen($zdata);
        $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix

crc bug
        $fr      .= pack('V', $crc);             // crc32
        $fr      .= pack('V', $c_len);           // compressed filesize
        $fr      .= pack('V', $unc_len);         // uncompressed filesize
        $fr      .= pack('v', strlen($name));    // length of filename
        $fr      .= pack('v', 0);                // extra field length
        $fr      .= $name;

        // "file data" segment
        $fr .= $zdata;

        // "data descriptor" segment (optional but necessary if archive is

not
        // served as file)
        $fr .= pack('V', $crc);                 // crc32
        $fr .= pack('V', $c_len);               // compressed filesize
        $fr .= pack('V', $unc_len);             // uncompressed filesize

        // add this entry to array
        $this -> datasec[] = $fr;
        $new_offset        = strlen(implode('', $this->datasec));

        // now add to central directory record
        $cdrec = "x50x4bx01x02";
        $cdrec .= "x00x00";                // version made by
        $cdrec .= "x14x00";                // version needed to extract
        $cdrec .= "x00x00";                // gen purpose bit flag
        $cdrec .= "x08x00";                // compression method
        $cdrec .= $hexdtime;                 // last mod time & date
        $cdrec .= pack('V', $crc);           // crc32
        $cdrec .= pack('V', $c_len);         // compressed filesize
        $cdrec .= pack('V', $unc_len);       // uncompressed filesize
        $cdrec .= pack('v', strlen($name) ); // length of filename
        $cdrec .= pack('v', 0 );             // extra field length
        $cdrec .= pack('v', 0 );             // file comment length
        $cdrec .= pack('v', 0 );             // disk number start
        $cdrec .= pack('v', 0 );             // internal file attributes
        $cdrec .= pack('V', 32 );            // external file attributes -

'archive' bit set

        $cdrec .= pack('V', $this -> old_offset ); // relative offset of

local header
        $this -> old_offset = $new_offset;

        $cdrec .= $name;

        // optional extra field, file comment goes here
        // save to central directory
        $this -> ctrl_dir[] = $cdrec;
    } // end of the 'addFile()' method


    /**
     * Dumps out file
     *
     * @return  string  the zipped file
     *
     * @access public
     */
    function file()
    {
        $data    = implode('', $this -> datasec);
        $ctrldir = implode('', $this -> ctrl_dir);

        return
            $data .
            $ctrldir .
            $this -> eof_ctrl_dir .
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries

"on this disk"
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries

overall
            pack('V', strlen($ctrldir)) .           // size of central dir
            pack('V', strlen($data)) .              // offset to start of

central dir
            "x00x00";                             // .zip file comment

length
    } // end of the 'file()' method


}

 代码如下 复制代码
function countSeason($start,$end){
    $temp = date("Y-m",strtotime("$start +3month"));
    while ($temp <= $end){
        $time[] = $temp;
        $temp = date("Y-m",strtotime("$temp +3month"));
    }
    return $time;
}
$time = countSeason("2008-10",date("Y-m"));
?>
<select name="select_season" id="select">
    <option> 按季度查看 </option>
    <?php foreach ($time as $val){?>
    <option value="http://www./<?php echo $val;?>"><?php echo substr($val,0,4);?>年 第<?php
    $temp = intval(substr($val,5,2));
    if (0<$temp&&$temp<4)
        {echo "1";}
    elseif (3<$temp&&$temp<7)
        {echo "2";}
    elseif (6<$temp&&$temp<10)
        {echo "3";}
    else
        {echo "4";}
    ?>季度</option>
    <?php }?>
</select>


/*
直接循环
如果是月,则循环变量每次增加1(月)
如果是年,则每次增加12(月),
同时输出date('Y-m')或者 date('Y')

*/

//保存图片到数据库

 代码如下 复制代码
If($Picture != "none") { 
$PSize = filesize($Picture); 
$mysqlPicture = addslashes(fread(fopen($Picture, "r"), $PSize)); 
mysql_connect($host,$username,$password) or die("Unable to connect to SQL server");
@mysql_select_db($db) or die("Unable to select database"); 
mysql_query("INSERT INTO Images (Image) VALUES ($mysqlPicture)") or die("Cant Perform Query"); 
}else { 
echo"You did not upload any picture"; 


 
//以img标签读取数据库中的图片

 代码如下 复制代码

mysql_connect($host,$username,$password) or die("Unable to connect to SQL server");
@mysql_select_db($db) or die("Unable to select database");
$result=mysql_query("SELECT * FROM Images") or die("Cant Perform Query"); 
While($row=mysql_fetch_object($result)) {
echo "<IMG SRC="Second.php3? PicNum=$row->PicNum">";

//如secoed.php文件代码如下
$result=mysql_query("SELECT * FROM Images WHERE PicNum=$PicNum") or die("Cant perform Query"); 
$row=mysql_fetch_object($result); 
Header( "Content-type: image/gif");
echo $row->Image;

 

[!--infotagslink--]

相关文章

  • php 中file_get_contents超时问题的解决方法

    file_get_contents超时我知道最多的原因就是你机器访问远程机器过慢,导致php脚本超时了,但也有其它很多原因,下面我来总结file_get_contents超时问题的解决方法总结。...2016-11-25
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • HTTP 408错误是什么 HTTP 408错误解决方法

    相信很多站长都遇到过这样一个问题,访问页面时出现408错误,下面一聚教程网将为大家介绍408错误出现的原因以及408错误的解决办法。 HTTP 408错误出现原因: HTT...2017-01-22
  • Android子控件超出父控件的范围显示出来方法

    下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
  • ps把文字背景变透明的操作方法

    ps软件是现在非常受大家喜欢的一款软件,有着非常不错的使用功能。这次文章就给大家介绍下ps把文字背景变透明的操作方法,喜欢的一起来看看。 1、使用Photoshop软件...2017-07-06
  • Mysql select语句设置默认值的方法

    1.在没有设置默认值的情况下: 复制代码 代码如下:SELECT userinfo.id, user_name, role, adm_regionid, region_name , create_timeFROM userinfoLEFT JOIN region ON userinfo.adm_regionid = region.id 结果:...2014-05-31
  • intellij idea快速查看当前类中的所有方法(推荐)

    这篇文章主要介绍了intellij idea快速查看当前类中的所有方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-02
  • js导出table数据到excel即导出为EXCEL文档的方法

    复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ht...2013-10-13
  • php把读取xml 文档并转换成json数据代码

    在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。...2016-11-25
  • mysql 批量更新与批量更新多条记录的不同值实现方法

    批量更新mysql更新语句很简单,更新一条数据的某个字段,一般这样写:复制代码 代码如下:UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value';如果更新同一字段为同一个值,mysql也很简单,修改下where即...2013-10-04
  • ps怎么制作倒影 ps设计倒影的方法

    ps软件是一款非常不错的图片处理软件,有着非常不错的使用效果。这次文章要给大家介绍的是ps怎么制作倒影,一起来看看设计倒影的方法。 用ps怎么做倒影最终效果&#819...2017-07-06
  • js基础知识(公有方法、私有方法、特权方法)

    本文涉及的主题虽然很基础,在许多人看来属于小伎俩,但在JavaScript基础知识中属于一个综合性的话题。这里会涉及到对象属性的封装、原型、构造函数、闭包以及立即执行表达式等知识。公有方法 公有方法就是能被外部访问...2015-11-08
  • 安卓手机wifi打不开修复教程,安卓手机wifi打不开解决方法

    手机wifi打不开?让小编来告诉你如何解决。还不知道的朋友快来看看。 手机wifi是现在生活中最常用的手机功能,但是遇到手机wifi打不开的情况该怎么办呢?如果手机wifi...2016-12-21
  • PHP 验证码不显示只有一个小红叉的解决方法

    最近想自学PHP ,做了个验证码,但不知道怎么搞的,总出现一个如下图的小红叉,但验证码就是显示不出来,原因如下 未修改之前,出现如下错误; (1)修改步骤如下,原因如下,原因是apache权限没开, (2)点击打开php.int., 搜索extension=ph...2013-10-04
  • c#中分割字符串的几种方法

    单个字符分割 string s="abcdeabcdeabcde"; string[] sArray=s.Split('c'); foreach(string i in sArray) Console.WriteLine(i.ToString()); 输出下面的结果: ab de...2020-06-25
  • js控制页面控件隐藏显示的两种方法介绍

    javascript控制页面控件隐藏显示的两种方法,方法的不同之处在于控件隐藏后是否还在页面上占位 方法一: 复制代码 代码如下: document.all["panelsms"].style.visibility="hidden"; document.all["panelsms"].style.visi...2013-10-13
  • 连接MySql速度慢的解决方法(skip-name-resolve)

    最近在Linux服务器上安装MySql5后,本地使用客户端连MySql速度超慢,本地程序连接也超慢。 解决方法:在配置文件my.cnf的[mysqld]下加入skip-name-resolve。原因是默认安装的MySql开启了DNS的反向解析。如果禁用的话就不能...2015-10-21
  • C#方法的总结详解

    本篇文章是对C#方法进行了详细的总结与介绍,需要的朋友参考下...2020-06-25
  • Zend studio文件注释模板设置方法

    步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
  • EXCEL数据上传到SQL SERVER中的简单实现方法

    EXCEL数据上传到SQL SERVER中的方法需要注意到三点!注意点一:要把EXCEL数据上传到SQL SERVER中必须提前把EXCEL传到服务器上.做法: 在ASP.NET环境中,添加一个FileUpload上传控件后台代码的E.X: 复制代码 代码如下: if...2013-09-23