2013年4月26日 星期五

php 換頁


把資料放入陣列中,利用GET的方式接收值來分頁


//-----------------------------------------換頁--------------------------------------------
$page_size = 2; //分布大小


$aa = array("a", "b", "c", "d" , "e", "f" , "g" , "h");

$record=count($aa);  //計算陣列大小
$page_count = ceil($record_count / $page_size); //頁數



if(!$_GET['page'])
{

 $page = 1; //當前頁面
 $aa = array_slice($aa, ($page-1)*$page_size, $page_size);  //取出資料
}
else
{

 $page=$_GET['page'];
 $aa = array_slice($aa, ($page-1)*$page_size, $page_size);  //取出資料


}

var_dump($aa);
$next=$page+1;
echo "目前頁數:$page<a href=test.php?page=$next>下一頁</a>.<br />";

//--------------------------------------------------------------------------------------------

Result:

array(2) { [0]=> string(1) "g" [1]=> string(1) "h" } 目前頁數:4下一頁.

2013年4月6日 星期六

php檔 未執行

php安裝常常失敗 以下是這次php檔未執行的主要原因 PHPIniDir "C:/Users/USER/Desktop/wei/WebService/PHP/php.ini" phpinidir 為空值,因此錯誤 必須給予系統中php.ini的位置 LoadModule php5_module "C:/Users/USER/Desktop/wei/WebService/PHP/php5apache2_2.dll" loadmodule 必須給予系統中php5apache2_2.dll的位置 AddType application/x-httpd-php .php

2012年12月17日 星期一

Note10

package com.example.upload;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import com.example.upload.Base64;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main extends Activity {
    private static final int SELECT_PICTURE = 1;
        private String selectedImagePath;
        private ImageView img;
        
        //EditText ed=(EditText)findViewById(R.id.ed);
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            img = (ImageView)findViewById(R.id.ImageView01);
            ((Button) findViewById(R.id.Button01)).setOnClickListener(new OnClickListener()
            {
                public void onClick(View arg0) 
                {
                    //選擇圖片
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
                    //最後一個參數傳入選擇圖片的URI
                }
            });
        }
        public void onActivityResult(int requestCode, int resultCode, Intent data) 
        {
            InputStream is;
            //data去接剛剛選取的圖片
            if (resultCode == RESULT_OK) 
            {
                if (requestCode == SELECT_PICTURE) 
                {
                    //取得路徑
                    Uri selectedImageUri = data.getData();
                    selectedImagePath = getPath(selectedImageUri);
                    System.out.println("Image Path : " + selectedImagePath);
                    
                    //設定顯示圖片
                    img.setImageURI(selectedImageUri);
                    //使用Bitmap取圖片
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2;
                    //圖片寬高都為原來的二分之一,即圖片為原來的四分之一
                    Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath,options);    
                    ByteArrayOutputStream bao = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
                    byte [] ba = bao.toByteArray();
                    //要POST至PHP檔使用Base64編碼
                    String ba1=Base64.encodeBytes(ba);
                    final ArrayList<NameValuePair> nameValuePairs = new
                    ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("source",ba1));
                    try{
                        /*
                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new
                            HttpPost("http://127.0.0.1/SOT/upload.php");
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            is = entity.getContent();
                        */
                        //好像都不能直接跑在主執行緒上因此直接做了Thread讓他去用
                        Thread thread = new Thread(){ 
                            @Override
                            public void run(){ 
                                try{
                                    HttpClient httpclient = new DefaultHttpClient();
                                    HttpPost httppost = new
                                    HttpPost("YOUR_URL");
                                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
                                    //設定輸出為UTF-8
                                    HttpResponse response = httpclient.execute(httppost);
                                    HttpEntity entity = response.getEntity();
                                    InputStream is = entity.getContent();

                                }catch (Exception e){
                                    e.printStackTrace();
                                }finally{
                                }
                            }
                        };
                        //開始執行執行緒
                        thread.start();
                    }catch(Exception e){
                        Log.e("log_tag", "Error in http connection "+e.toString());
                    }
    
                }
            }
        }
        public String getPath(Uri uri) 
        {    String[] projection = 
            {
                MediaStore.Images.Media.DATA 
            };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        
        
        
        
        
         public String convertStreamToString(InputStream is)
                    throws IOException {
                //
                // To convert the InputStream to String we use the
                // Reader.read(char[] buffer) method. We iterate until the
                // Reader return -1 which means there's no more data to
                // read. We use the StringWriter class to produce the string.
                //
                if (is != null) {
                    Writer writer = new StringWriter();
         
                    char[] buffer = new char[1024];
                    try {
                        Reader reader = new BufferedReader(
                                new InputStreamReader(is, "UTF-8"));
                        int n;
                        while ((n = reader.read(buffer)) != -1) {
                            writer.write(buffer, 0, n);
                        }
                    } finally {
                        is.close();
                    }
                    return writer.toString();
                } else {        
                    return "";
                }
            }
}


PHP檔如下:




$base=$_REQUEST['source'];

echo $base;

// base64 encoded utf-8 string

$binary=base64_decode($base);

// binary, utf-8 bytes

header('Content-Type: bitmap; charset=utf-8');


$name=uniqid();
//uniqid()是用來亂數產生一串英文數字

$file = fopen("$name.jpg", 'wb');
//開啟以那串英文數字為檔名的檔案
fwrite($file, $binary);
//寫入檔案
fclose($file);
//寫入完畢關閉檔案

//unlink($file)
//unlink刪除檔案
echo "";




大部分的解釋都直接註解在裡面了

這是一個從Android選取圖片直接上傳到PHP的程式

花了不少時間拼拼湊湊才把這個弄出來

網路上資料雖然很多,但是很多都是不能用的,不然就是舊的...

以上的流程大概就是
Android -> choose image -> encode(use Base64) -> PHP($_REQUEST) -> decode(Base64) ->Write to File and save


下面這兩行是因為手機似乎不像電腦有那麼大的記憶體

如果不縮小一點常常都會出現java.lang.outmemory然後就直接Shutdown了...

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;


然後

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

如果要傳中文進去php檔必須要記得php檔要用utf儲存

android端送出資料的時候也要記得加上HTTP.UTF_8

如果出現這一行

org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused

上網google似乎是因為android把自己當作local端了..

所以只要用 cmd ipconfig 查詢本機的ip換上去就可以了通常是 192.168.xxx.xxx

2012年10月7日 星期日

Note9



function test(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
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","Check_ID.php?id="+str,true);
xmlhttp.send();
}


這次用了ajax利用GET把值傳到php檔來進行資料庫的判斷,

上面的是判斷瀏覽器所使用的,這是網路上的範例,只做了小部分的修改,

之後在想想能否再用上ajax的技術,不用整個畫面重新整理還蠻方便的,

接下來要做的是上學期驗收老師所提的功能,讓使用者能夠用圖片來進行發文的動作,

之前有看過文件Facebook是可以的,plurk跟twitter的文件還沒有去看。

2012年6月10日 星期日

Note8

上禮拜終於結束了專題的報告,

運氣很好的我果然還是被抽上台了,

報告的時候有點小緊張,

不過在發現老師好像大多在研究手中的那張A4之後,

就開始不那麼緊張了,

最後發問的時候雖然一直聽不懂老師在說什麼,

不過在休息時間在去問了幾次才聽懂,

老師的建議也很好,我應該再試試看能不能把圖片的資料也顯示出來,

這樣應該會更有吸引力。

接下來測試社群網站的未讀功能,

plurk和facebook看官方的文件是有未讀的可以使用,

但是Twitter似乎沒有提供這個功能,

可能還要在嘗試看看,

也開始規劃暑假應該做哪些進度,

忙碌的暑假。

2012年5月30日 星期三

Note7

這兩個禮拜幾乎都在撰寫文件,一直在新增修改,並對報告做演練,只是常常會遇到不知道該

怎麼寫的,比如系統架構圖,有些就是畫得很順,但是講起來就是不通。


2012年5月13日 星期日

Note6

這次先使用 plurk 做測試

$plurk->callAPI('/APP/Timeline/getUnreadPlurks');

回傳的是 object 的資料型態,我將他轉成Array方便使用,$b=objectToArray($json);



function objectToArray($d) {

if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);

}

他會分別將帳戶分為兩個陣列然後一直包下去,第一個陣列放的是在這次撈出來的資料中,

有出現的使用者,包含暱稱、姓名、生日等等一些公開的基本資料,第二個陣列放的就是發

文的資料,但是第二個陣列裡面放的卻只有使用者的ID,因此如果要知道是哪一個使用者發

文的就必須要和第一個陣列做比對,才能取出發文者的資料,經過排列整理之後就能夠依照

自己的方式把他排好。我的方式是先將所有的id和該id的暱稱存放到一個陣列,當開始處理第

二個陣列(發文的資料)的時候,就到這一個陣列來比對該id是對應到哪一個暱稱。


例如:

xxx Says : [科普]  (小雨為什麼後悔了?) "

現在遇到的問題是因為都必須在到第一個陣列去做比對,但是有些人有暱稱,有些人沒有,從

朋友的塗鴉牆撈我作測試的帳號,卻無法正確的撈出暱稱,除了我的帳號之外其他人的顯示都是正常的目前還是不知道原因出在哪裡