Android / php:使用PDO使用“LIKE”检索一组结果,并解析为JSON

时间:2017-09-22 12:58:13

标签: php android mysql json pdo

我正在尝试使用查询来搜索数据库,并从用户名称​​ LIKE 搜索查询的表中返回几列。即如果我输入“M”,将检索Max,Matthew等名称。但是,执行时查询不返回任何内容。我用try / catch函数包围了它们并且它们正常工作,回显我可以使用的整数,但我更喜欢代码实际上做了它的意图。我已经花了一段时间摆弄这个,首先尝试使用MySqli然后转移到PDO,因为在线的每个人都认为它更好。

如果有人能看出这有什么问题,请不要犹豫,纠正它!

服务器端脚本如下:

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);

}

一旦我可以将一些有用的数据传递给应用程序,我想用它填充搜索建议类型列表视图,以便用户可以选择要添加的相应人员。如果有人也知道如何做到这一点,请随意将其添加为评论或给我发消息,因为我需要所有帮助,我可以得到这个!

干杯, Ĵ

2 个答案:

答案 0 :(得分:2)

要获得一个功能性的LIKE语句,需要注意,需要在mysql中添加一个precent标志作为通配符。

这将使Names startig为“M”

SELECT user_id, name, email FROM users WHERE name LIKE 'M%'

这将使名称以“M”结尾

SELECT user_id, name, email FROM users WHERE name LIKE '%M'

这将获得在某个地方包含“M”的名称

SELECT user_id, name, email FROM users WHERE name LIKE '%M%'    

答案 1 :(得分:1)

您希望数据与字符串的开头匹配,就像您必须在结尾添加%一样

try {
$stmt = $pdo->prepare("SELECT user_id, name, email FROM users WHERE name LIKE ?");
$name = $name."%"; // add this line
$stmt->execute([$name]);
$result = $stmt->fetch();
} catch (Exception $e) {
    echo "99"; //Statement failed
}