如何将数据发送到服务器?

时间:2018-10-15 10:19:18

标签: php android mysql

我需要您的帮助,我的代码有问题,我想将数据发布到服务器,但是数据无法发布,这使我感到困惑,请帮助我。

这是我的代码。

private String JSON_STRING;
    LocalSession session;
    PostToServer postToServer;
    ProgressDialog loading;
    public static final String TAG_USERNAME = "username";
    String username,area,rayon;
    EditText user;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_tampil_semua_pgw);
        listView = (ListView) findViewById(R.id.listView);
        listView.setOnItemClickListener(this);
       // getJSON();
        username =getIntent().getStringExtra(TAG_USERNAME);
        user = (EditText)findViewById(R.id.user);
        user.setText(username);


        postToServer = new PostToServer();
        postToServer.delegate = this;
        postToServer.execute(konfigurasi.URL_GET_ALL,user.getText().toString().trim());

        loading = ProgressDialog.show(TampilSemuaPgw.this,"Fetching Data","Wait...",false,false);

        //getJSON();
        Log.e("loc change","long: "+user.getText().toString().trim()+" ");

    }

这是我的PHP代码。

<?php 



	//Import File Koneksi Database
	require_once('koneksi.php');
	$username = $_POST["username"];
	
	//Membuat SQL Query
	$sql = "SELECT * FROM t_p2tl_lpb where petugas='$username'";
	
	//Mendapatkan Hasil
	$r = mysqli_query($con,$sql);
	
	//Membuat Array Kosong 
	$result = array();
	
	while($row = mysqli_fetch_array($r)){
		
		//Memasukkan Nama dan ID kedalam Array Kosong yang telah dibuat 
		array_push($result,array(
			"idpel"=>$row['idpel'],
			"id"=>$row['id'],
			"nama"=>$row['nama']
		));
	}
	
	//Menampilkan Array dalam Format JSON
	echo json_encode(array('result'=>$result));
	
	mysqli_close($con);
?>

此代码运行良好,但是它调出了所有数据,而我想要的是仅显示具有我发布条件的数据的数据。请帮助所有人解决我的问题,因为我很困惑要解决这个问题。

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试使用PDO代替mysqli。就像下面的例子:

//Import File Koneksi Database
require_once('koneksi.php');
$username = isset($_POST["username"]) ? $_POST["username"] : null;

// ===============================================
// This params will be in file koneksi database
// ===============================================
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
// ===============================================
// ===============================================
// ===============================================
$result = [];
try {
    $pdo = new PDO($dsn, $user, $password);
    $stmt = $pdo->prepare('SELECT * FROM t_p2tl_lpb WHERE petugas = :username;');
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $result[] = [
            'idpel' => $row['idpel'],
            'id'    => $row['id'],
            'nama'  => $row['nama']
        ];
    }
    echo json_encode([
        'result' => $result
    ]);
    unset($pdo);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}