PHP retrieval from database on single string

70 views Asked by At

I'm retrieving data from a SQL database with these lines of code

$username = $_POST['username'];
$selector = "SELECT * FROM client_table WHERE SalesmanID ='" . $username . "';";
$result = mysqli_query($con,$selector);

while($row = mysqli_fetch_array($result)) {
    echo  $row['ID'] . "/" . $row['Name'] .  "/" . $row['Address'] .  "/" . $row['Zip Code'] .  "/" . $row['SalesmanID'];
    echo "\\r\\n";
}
?>

On the Java side I do

while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
    stringBuilder.append(bufferedStrChunk);
}

String queryResult = stringBuilder.toString();

and the problem is that when I do

String[] results=queryResult.split("\n");

the string is not split. Could someone please help?

2

There are 2 answers

2
Adarsh Rajput On

In PHP code you used escape to \ by \\ that makes string appended with \-char followed by n-character AND in Java code you are splitting by new line char \n. This can be cause of problem.

Try it with escaped \:

String[] results=queryResult.split("\\\\n");
//EDITED: String[] results=queryResult.split("\\n"); //In comment informed that; to escape '\' we need to use four '\\\\'

That should work.

2
Pshemo On

You are not adding any line separator to stringBuilder when you are retrieving data from bufferedReader like

stringBuilder.append(bufferedStrChunk).append(System.lineSeparator())

Anyway if you want to get all lines in some sort of collection then you can simply use

List<String> lines = Files.readAllLines(Paths.get("pathToFile"));

In case of BufferedReader you can also use (since Java 8)

List<String> lines = br.lines().collect(Collectors.toList());