我試圖使用查詢來搜索數據庫,並返回表中的幾列,無論用戶的名字是LIKE搜索查詢。也就是說,如果我輸入「M」,則會檢索像Max,Matthew等名稱。但是,執行時查詢不會返回任何內容。我用try/catch函數把它全部包圍起來,它們正常工作,回顯一個我可以使用的整數,但我更喜歡代碼實際上做了它的意義。我花了很長時間擺弄這個,首先嚐試使用MySqli然後轉向PDO,因爲每個人都認爲它更好。Android/php:使用PDO檢索一組結果,使用'LIKE',並解析爲JSON
如果有人可以看到這有什麼問題,請不要猶豫,糾正它!
服務器端腳本如下:
if(!empty($_POST['name'])){
$host =
$db =
$user =
$password =
$charset =
$dsn = 'mysql:host=localhost;dbname=dbname';
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn,$user,$password,$opt);
$response = array();
$name = $_POST['name'];
$query = "SELECT user_id, name, email FROM users WHERE name LIKE ?";
try {
$stmt = $pdo->prepare("SELECT user_id, name, email FROM users WHERE name LIKE ?");
$stmt->execute([$name]);
$result = $stmt->fetch();
} catch (Exception $e) {
echo "99"; //Statement failed
}
if ($result !== false) {
foreach($result as $row) {
echo json_encode($row['user_id']);
echo json_encode($row['name']);
echo json_encode($row['email']);
}
} else {
echo '2'; //Empty result
}
$dsn = null;
} else {
echo "3"; //No search entry
}
從AndroidStudio相關的代碼如下:
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
final String name = searchInput.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
System.out.println(response);
System.out.println(name);
if(response != null) {
System.out.println("Statement executed");
} else if (Integer.parseInt(response) == 2) {
System.out.println("Statement executed, but result invalid");
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT).show();
} else if (Integer.parseInt(response) == 3) {
System.out.println("Search field empty");
Toast.makeText(getApplicationContext(), "No search entry", Toast.LENGTH_SHORT).show();
} else if (Integer.parseInt(response) == 99) {
System.out.println("Failed to execute");
Toast.makeText(getApplicationContext(), "Statement failure", Toast.LENGTH_SHORT).show();
} else {
JSONArray jsonResponse = new JSONArray(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
PopupContactRequest AddContactRequest = new PopupContactRequest(name, responseListener);
RequestQueue queue = Volley.newRequestQueue(PopupAddContact.this);
queue.add(AddContactRequest);
}
一旦我能真正得到傳遞到應用中的一些有用的數據,我d喜歡用它填充搜索建議類型列表視圖,以便用戶可以選擇要添加的適當人員。如果任何人也知道如何做到這一點,隨時添加它作爲評論或消息我,因爲我需要我可以得到的所有幫助!
乾杯, Ĵ
這工作,你是一個傳奇,謝謝! – JSteward