Error in generating php link?

1

The error is generated by the records in the database. The tags are saved without any space and the link is generated in this way: example.com/tags/html,php

 id    addtags
----  ------------
 1     html,php

Now if I manually edit the records in the database in this way:

 id    addtags
----  ------------
 1     html, php

The links are generated correctly, like this: example.com/tags/html and example.com/tags/php .

Now my question is how do I save the records in the database in this way to correctly generate the links.

 id    addtags
----  ------------
 1     html, php

Code to save to the database:

<?php

if (isset($_POST['tags']) && !empty($_POST['tags'])) {
    $tags = $_POST['tags'];

    $host = "localhost";
    $usuario = "root";
    $clave = "";
    $basedatos = "tags";
    $tabla = "tags";

    $mysqli = mysqli_connect($host, $usuario, $clave, $basedatos);
    if (mysqli_connect_errno($mysqli)) {
        die( "Error al conectar a MySQL: " . mysqli_connect_error() );
    }

    $sentencia = $mysqli->prepare("INSERT INTO $tabla (id, addtags) VALUES (?, ?)");
    $sentencia->bind_param('is', $id, $tags);
    $sentencia->execute();


    $sentencia = null;
    $mysqli = null;

    echo "Se grabó la etiqueta tags";
}

?>

Php code to generate link:

<?php

  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "tags";

  $conn = new mysqli($servername, $username, $password, $dbname);

  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }

  $sql = "SELECT id, addtags FROM tags";
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
      $datotags = $row["addtags"];
      $tags = explode(', ', $datotags);
      $resultado = '';
      foreach ($tags as &$tag) {
        $resultado .= "\n" . '<a href="example.com/tags/'.$tag.'">'.$tag.'</a>' ;
      }

      echo $resultado;
    }
  }else {
    echo "0 results";
  }

  $conn->close();

?>  
    
asked by Otto 24.09.2016 в 06:53
source

1 answer

2

The problem you have is that you are using the explode () function, with characters that do not exist in your tags, specifically you use comma followed by a space ', '

To solve it and separate your tags use explode only with a comma, like this:

$tags = explode(',', $datotags);

That way each element of your tags is separated in the resulting array.

    
answered by 24.09.2016 / 07:51
source