Your code is missing the execution of the SQL query, the extraction of the result and sending it to the client.
In addition, your code suffers from the serious security issues associated with SQL injection to be solved with prepared queries or using mysqli::real_escape_string()
.
The query is executed with a call to mysqli::query
or mysqli::prepare
if you use prepared queries.
The result can be obtained by using mysqli_result::fetch_assoc()
.
Finally, to send the data in JSON you have to set the necessary header ( Content-Type: application/json; charset=utf-8
) and use the function json_encode()
to obtain the value correctly generated as a JSON value (although being numeric this will be the number as such).
Here is your finished code with the suggested modifications:
<?php
$host = "localhost";
$username = "---";
$password = "---";
$db = "---";
//connection
$conn = new mysqli($host, $username, $password, $db);
/* Escapamos correctamente el usuario recibido por POST
para evitar inyección SQL */
$username = $conn->real_escape_string($_POST["username"]);
/* Agregamos un alias al COUNT(*) para poder acceder a él fácilmente */
$sql = "SELECT COUNT(*) numero FROM 'login' WHERE username = '$username'";
/* Hacemos efectiva la consulta */
$resultado = $conn->query($sql);
/* Obtenemos el primer y único registro */
$registro = $resultado->fetch_assoc();
/* Enviamos al cliente el resultado (numérico) codificado en JSON
(que será únicamente el número sin más) */
header('Content-Type: application/json; charset=utf-8');
echo json_encode($registro['numero']);
NOTE: This code does not handle SQL errors or any other error that occurs during calls to mysqli
functions. You should check the result of calling each of them.