Hi, I've had problems separating a query, you'll see this is my code, I extract the alarms from the database, that's what the field is called, there are only 3 options "Alarm", "Warning" and "Both" you can only insert one in a record when I extract the query it shows it like this;
Alarm Warning
And I want it to show it like this;
alarm, notice
(with the comma) I already tried with implode
, but I couldn't get it right, it came out like this;
AlarmWarning,AlarmWarning.
$sql = "SELECT *
FROM notificaciones
WHERE idDepto = " .$_POST['id_depto']."";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{// Datos obtenidos de la consulta
while($row = $result->fetch_assoc())
{
$noti = $row["Notificacion"]; //Nombre de notificacion Alarma/ Aviso / Ambas
$verialarma = $noti;
echo $verialarma;
} else {
echo "0 resultados"; //Validacion
}
$conn->close();
I don't see your complete code, like where does the while end? and I don't know if $noti is returning the array you are looking for
But assuming that you already get as a result: AlarmaViso , this indicates that you are using implode without a character to join the elements in your case the comma (",")
Syntax: implode ( string $glue, array $array ); obtained from the PHP Manual
In the end you just join your chain in the following way:
What could be implemented is a concatenation of a "," to each element that the query brings you as follows:
Could you do the test and tell me if it works for you, it's that I couldn't do the test since I don't have PHP installed on my machine. Any doubt we could check it.
From what I understand what you need is that when you have recovered
AlarmaAviso
it put it in this wayAlarma,Aviso
.To do this, you can use the
preg_replace
PHP function. With it, and by means of a regex, you can detect the capital letters and insert a comma in front of them. Later, you can use the functionltrim
to remove the comma that has been inserted in front of the first word of the string.Example:
demos .
I think you could get it using
GROUP_CONCAT
.You don't explain the context well. But if the notifications occur in department 1
Alarma
and theyAviso
exist in different rows of a table,GROUP_CONCAT
it allows you to obtain a single row of results with all the notifications that occurred according to the criteria applied to the query.That is, if you place a in the query
WHERE dpto_id=1
and then apply aGROUP BY dpto_id
, what it will doGROUP_CONCAT
is return a single row separated by the separator that you indicate, grouped by each department. Of course, more criteria can be added, both inWHERE
and in theGROUP BY
.Código:
Ver Demo
Resultado:
Security note: The code used in your question is vulnerable to SQL injection. It is recommended to use prepared queries, example:
Passing the value of the field separately
dpto_id
, to avoid SQL Injection .