For you, the solution would be this one demonstrated, but because I do not know exactly what the structure of your table is, I will base myself on the details provided in the comments. Although you are using a different table, the example is very simple. The only problem you would have is perhaps the slug
which is basically the title of the article, but with some arrangements, for this has this, and this here.
config.php
<?php
// configuracao (nao importante)
$config = array(
'mysql' => array(
'host'=> 'localhost',
'usr' => 'root',
'pwd' => '',
'db' => 'nuwie'
),
'site' => array(
'nome' => 'Site sem Nome',
'inicio' => 'http://127.0.0.1:8080' . dirname($_SERVER['SCRIPT_NAME'])
)
);
// agilizar a busca dos valores da configuração (nao importante)
function conf($nome){
$p = preg_split('/[\s-@]/', $nome);
global $config;
foreach($config as $nome => $valor){
if($nome === $p[0] && array_key_exists($p[1], $valor)){
return $config[$nome][$p[1]];
}
}
return false;
}
// conexao
$mysqli = new mysqli(conf('mysql-host'), conf('mysql-usr'), conf('mysql-pwd'), conf('mysql-db'));
if($mysqli->errno){
die('Erro ao conectar banco de dados');
}
// buscar todos os artigos
function buscarArtigos($tabela){
global $mysqli;
$resultados = array();
if($stmt = $mysqli->query("SELECT id,titulo,seo_url FROM {$tabela}")){
if($stmt->num_rows > 0){
while($rs = $stmt->fetch_assoc()){
array_push($resultados, $rs);
}
return $resultados;
}
}
return false;
}
// buscar um artigo pela sua ID
function buscarArtigo($id, $tabela){
global $mysqli;
if($stmt = $mysqli->query("SELECT * FROM {$tabela} WHERE id = {$id}")){
if($stmt->num_rows > 0){
return $stmt->fetch_assoc();
}
}
return false;
}
// reajustar os titulos para que se adequem a url
// retirada de: http://www.visualscope.com/seo-friendly-urls.html
function friendly_seo_string($vp_string){
$vp_string = trim($vp_string);
$vp_string = html_entity_decode($vp_string);
$vp_string = strip_tags($vp_string);
$vp_string = strtolower($vp_string);
$vp_string = preg_replace('~[^ a-z0-9_.]~', ' ', $vp_string);
$vp_string = preg_replace('~ ~', '-', $vp_string);
$vp_string = preg_replace('~-+~', '-', $vp_string);
return $vp_string;
}
This file here contains basically the only two functions you’d need to make the idea work searchArticles and searchArticle, what’s there to spare (nothing important) created in the heat of the moment since they were simple except the last that may be useful and is not of my own making. The function friendly_seo_string is only required when you want to create a new article, for example:
- When you create a new article, in the database table for the fields
titulo
and conteudo
you can use the desired title and content respectively, the same applies to the field adicionado
, but to the countryside seo_url
would have to be the return of this function passing the title used as argument friendly_seo_string(titulo_usado_no_artigo). Or if you prefer you can always write your own function, so that it does the same thing.
.htaccess
RewriteEngine On
RewriteRule ^artigos/[0-9]\/(.*)$ ver_artigo.php?artigo=$0
For this example, you wouldn’t need much in the file .htaccess, only these two lines would be sufficient, or you can still check if the module rewrite
is enabled before activating it.
sql table
CREATE TABLE `artigos` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`titulo` varchar(60) NOT NULL,
`conteudo` text NOT NULL,
`seo_url` varchar(60) NOT NULL,
`adicionado` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
index php.
<?php
require_once 'config.php';
print "<a href=\"" . conf('site-inicio') ."\"><h1>" . conf('site-nome') . "</h1></a>";
// - inicio do conteudo
if(($artigos = buscarArtigos('artigos')) != false){
foreach($artigos as $artigo){
print "<div id=\"artigo\">";
print "<a href=\"artigos/{$artigo['id']}/{$artigo['seo_url']}\" target=\"_blank\"><h4>{$artigo['titulo']}</h4></a>";
print "</div>";
}
} else {
print "Nenhum artigo encontrado";
}
// - fim do conteudo
?>
The file index php., simply make available the respective titles and links of existing articles.
Attention to article link:
print "<a href=\"artigos/{$artigo['id']}/{$artigo['seo_url']}\" target=\"_blank\"><h4>{$artigo['titulo']}</h4></a>";
IN url
which stores, for articles, must precede artigos
at the beginning of href.
ver_article.php
<?php
require_once 'config.php';
if(isset($_GET['artigo'])){
$artigo_id = explode('/', $_GET['artigo']);
if(($artigo = buscarArtigo($artigo_id[0], 'artigos')) != false){
print "<div id=\"artigo\">";
print "<h2>{$artigo['titulo']}</h2>";
print $artigo['conteudo'];
print "</div>";
} else {
print "Artigo não encontrado";
}
print "<p><a href=\"" . conf('site-inicio') ."\">voltar</a></p>";
} else {
print "<h1>Erro</h1>";
}
?>
This part would be the equivalent of your page visualize.pph. Search the details of this article using your id
and returns them, if you do not find the article, provides a message saying that you did not find the article.
In that case, yours url
would look in this format similar to ptSO:
www.nomedomeusite.com/articles/id/article title
For the format:
www.nomedomeusite.com/companies/any-company
You’d have to match your own slug
instead of id
on the tab showing the details of the selected item.
ps.: I worked on the idea, but I didn’t give a damn about the safety factor, so I recommend before, that you research mainly on the .htaccess, and of course, you can always adapt or even , improve the code so that it works more closely to what you want. If there are still doubts, leave them in the comments, and good luck.
Recommended Reading
Apache
It is a site made only by html and php even without any framework
– Nicolas S.
That page
visualizar.php
is one of the common pages of my site, in it I make a call of various elements of my database and display them on the screen– Nicolas S.
Already read this post here ?
– Edilson
Yes, I came to see this post, but I couldn’t understand that code very well, so I couldn’t do it. If you could really explain to me how I can do this id, which takes the name of the database and puts it in the url, it would be of great help.
– Nicolas S.
This question actually already exists, and it has also been answered, but the fact that it has a reward does not allow it to be marked as duplicate. But in any case, it would be something like, by clicking on
link
article (the link itself would be the title of the article), would open a specific page that would show the content of that article, that’s it ?– Edilson
For that you’ll have to wait, because at the moment I am somewhat physically conditioned, unless someone would please give me that answer before I do. If no one answers, probably by tomorrow at the end of the day I will pass the answer.
– Edilson
Okay, I’m trying some stuff here, using that post there that you mentioned, anything, if I find an answer I’ll let you know
– Nicolas S.