简体   繁体   中英

Sql query with punctuation marks

I have a webServer Between my SQL database and my Android app. On the database I want to put a sentence with question marks but when the webserver catches the query, the echo is null. This only happen when I use question marks, dots or commas in the phrase. The code of the webserver is:

<?php
$hostname_localhost ="*****";
$database_localhost ="*****";
$username_localhost ="*****";
$password_localhost ="*****";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

$resultado = mysql_query('SELECT pregunta,respuesta,intentos,frase FROM Frases');
if (!$resultado) {
    die('Consulta no válida: ' . mysql_error());
}

while ($fila = mysql_fetch_assoc($resultado)) {
    $pregunta = $fila['pregunta'];
    $respuesta = $fila['respuesta'];
    $intentos = $fila['intentos'];
    $frase = $fila['frase'];

}

mysql_close($localhost);

$data = array('pregunta' => $pregunta, 'respuesta' => $respuesta, 'intentos' => $intentos, 'frase' => $frase); 
print (json_encode($data));

?>

You are declaring the variables ($pregunta, $respuesta, $intentos, $frase) locally to the while loop, once the while loop is completed those variables no longer exist.

Change:

while ($fila = mysql_fetch_assoc($resultado)) {
    $pregunta = $fila['pregunta'];
    $respuesta = $fila['respuesta'];
    $intentos = $fila['intentos'];
    $frase = $fila['frase'];

}

mysql_close($localhost);

$data = array('pregunta' => $pregunta, 'respuesta' => $respuesta, 'intentos' =>     $intentos, 'frase' => $frase); 
print (json_encode($data));

To:

$data = array();

while ($fila = mysql_fetch_assoc($resultado)) {
    $pregunta = $fila['pregunta'];
    $respuesta = $fila['respuesta'];
    $intentos = $fila['intentos'];
    $frase = $fila['frase'];

    $data = array('pregunta' => $pregunta, 'respuesta' => $respuesta, 'intentos' =>     $intentos, 'frase' => $frase); 
}

mysql_close($localhost);


print (json_encode($data));

The data is then assigned to a variable outside the while loop and is thus retained, allowing you to output the json encoded array.

In your java code, you can send your GET variables that way. encoded to utf-8

String query = URLEncoder.encode("Do I need to write a question mark?", "utf-8");
 String url = "http://questionmark.com/search?q=" + query;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM