Create a SEO friendly URL - php

index.php
-------------
<?php
$connect = mysqli_connect("localhost","root","1234","mspl_test");
$data = mysqli_query($connect,"SELECT * FROM products");
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST">
<div class="container">
<table border="1">
<th>ID</th>
<th>Name</th>
<?php
while($row =mysqli_fetch_array($data))
{
echo "<tr><td><a href='exp.php?id=$row[0]&name=$row[1]'>$row[0]</a>
<td><a href='exp.php?id=$row[0]&name=$row[1]'>$row[1]</a>";
}
?>
</table>
</div>
</form>
</body>
</html>
exp.php
-------
<?php
$id = $_GET['id'];
$name = $_GET['name'];
echo "<h1 align='center'>Hello! You've selected $name having id of $id</h1>";
?>
.htaccess
---------
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^product?$ exp.php?id=$1&name=&1
</IfModule>
When user clicks on a link some id or name..it shows the url http://localhost/slug/exp.php?id=1&name=Google Nexus 4. i want to remove this id=1&name=Google Nexus 4 and make it seo friendly. i know i can sanitize my url with .htaccess.but it doesn't work. when i click it still shows the query string urls rather than just product.

Related

Get id from URL but database results aren't shown

I use the following:
<a href="showlog.php?id=<?php echo $car['car_id']; ?>">
and I get a url that looks like this:
https://example.com/showlog.php?id=AAA1111
So now in the showlog.php file I want select from a table all the lines that have this id value saved as car_id and echo the id (primary key which is different than the car_id), the trn_date, and the kilometers, so I use the following code:
<?php
include 'main.php';
checkLoggedIn($pdo);
$id=$_GET['id'];
$stmt = $pdo->prepare('SELECT id, trn_date, kilometers FROM serv WHERE car_id = '.$id.' ');
$stmt->execute([$_SESSION['id']]);
$cars = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body class="loggedin">
<div class="content">
<h2>Ser</h2>
<div>
<table>
<?php foreach($cars as $car): ?>
<tr>
<td>
<a href="showser.php?id=<?php echo "". $car["id"]. ""; ?>" style="color:DarkCyan; text-decoration: none">
<img src="images/car_service.png" width="40" height="40"> Date: <?="". $car["trn_date"]. ""?>
</a>
</td>
<td>kilometers: <?="". $car["kilometers"]. ""?></td>
</tr>
<tr><th colspan="8"><br/><hr width="100%"></th><tr>
<?php endforeach; ?>
</table>
</div>
</div>
</body>
</html>
The page loads but I get nothing as result. What am I doing wrong? :/

Inserting and Displaying image from MySQL

I'm trying to display an image which have been stored in MySQL, but haven't been able to get a success just yet. Apparently echoing the table header (img) gives me back something like this
In addition I would like to be able to add the image in the website itself rather than using the phpmyadmin and inserting the image there.
As of now this is the code I have for the standing.php page
<?php
require_once('database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main id="standingListMain">
<h1 id="addCategoryh1">Team Standings</h1>
<table id="standingListTable">
<tr>
<th>Team</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryID']; ?></td>
<td>
<?php echo $team['categoryName']; ?>
<?php echo $team['img']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
</main>
<!-- <footer id="standingListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer> -->
</body>
</html>
Basically, the user can add or remove a team from the team_list.php page and view it on the standings page
<?php
require_once('../Model/database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main>
<h1 id="addCategoryh1">Teams</h1>
<table id="categoryListTable">
<tr>
<th>Name</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryName']; ?></td>
<td>
<form action="delete_team.php" method="post"
id="delete_product_form">
<input type="hidden" name="team_id"
value="<?php echo $team['categoryID']; ?>">
<input id="deleteCategoryList" type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<h2 id="add_category_h2">Add Team</h2>
<form action="add_team.php" method="post"
id="add_category_form">
<label>Name:</label>
<input type="input" name="name">
<input id="add_category_button" type="submit" value="Add">
</form>
<br>
<p>View Team List</p>
</main>
<footer id="categoryListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer>
</body>
</html>
Code above is the team_list.php page and below is the code to connect to the database called the add_team.php
<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
}
?>
The image above shows the page where u can add or remove a team.
For testing purposes
First you need to know if the Image really exist. Let's assume that in your database you have an image with category Id of 1. Thus create another file, eg "image.php".
(Please ensure that this code runs correctly. I have not tested it but it should work for you).
image.php
<?php
require_once('database.php');
// Get all categories
$query = "SELECT img FROM categories where categoryID=1";
$statement = $db->prepare($query);
$statement->execute();
$num = $statement->rowCount();
if( $num ){
$teams = $statement->fetchAll();
// Ensure to specify header with content type,
// you can do header("Content-type: image/jpg"); for jpg,
// header("Content-type: image/gif"); for gif, etc.
header("Content-type: image/png");
//display the image file
print $teams['img'];
exit;
}else{
//echo no image found with that Category Id.
}
?>
Then in your "standing.php", remove this code:
<?php echo $team['img']; ?>
and replace it with:
<!– "1" is the categoryID id of the image to be displayed –>
<img src="image.php?id=1" />

how to load different page in a index page of website

I'm trying to build a website that having different pages.
I'm a newbie to PHP, I have an index page with certain tables for holding header, navigation menu, main body, a sidebar and for a footer. The index page is attached to all the above-mentioned elements in it using include("filename.extension");. The problem is I tried to load the main body i.e content of the site, dynamically when the menu is changed.
Below is my code, any suggestion on this is very appreciatable. Thanks in advance.
<body>
<div> <?php Include('header.php'); </div>
<div id="menu" align="center">
<table width="790" height="35">
<tr>
<td>Home</td>
<td>Register</td> // this page need to display on the same window with other elements, after click.
</tr>
</tabel>
</div>
<div id="sidebar" align="right"> <?php include ("sidebar.php");?> </div>
<div id="Content ">
<?php include("FILE"); // here i need to display the hyper linked page.?>
</div>
<div id="footer"> <?php include("footer.php");?> </div>
</body> `
guess Diogo's answer will get you to what you want. create your index.php file like this.
//menu area
<div id="menuWrap">
link to page1
link to page2
</div>
//side bar
<div id="sidebarWrap">...</div>
//content area
<div id="contentWrap">
<?php
switch($_GET['page'])
{
case 'page1':
include '/pages/page1.php';
break;
case 'page2':
include '/pages/page2.php';
break;
default:
include '/pages/notfound.php';
}
?>
</div>
//footer
<div id="footerWrap">...</div>
This way you can display other pages in your site in the same window, only the content area will change
update:
I have got corrected your typos, here is the answer according to your code segment.
<body>
<div>
<?php Include('header.php'); ?>
</div>
<div id="menu" align="center">
<table width="790" height="35">
<tr>
<td>Home</td>
<td>Register</td>
</tr>
</table>
</div>
<div id="sidebar" align="right">
<?php include ("sidebar.php"); ?>
</div>
<div id="Content ">
<?php
switch($_GET['page'])
{
case 'page1':
include '/pages/home.php';//file path of your home page
break;
case 'page2':
include '/pages/students/reg.php';
break;
default:
include '/pages/notfound.php';
}
?>
</div>
<div id="footer">
<?php include("footer.php");?>
</div>
</body>
First, create a file with exactly the name below: (including the dot)
.htaccess
and put it in the same folder of your index.
Inside the .htaccess, write the following code:
# .htaccess mod_rewrite
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
The .htaccess on this case will rewrite the URLs to change the http://127.0.0.1/index.php?page=register to accept the "blogging pretty url" http://127.0.0.1/register
inside of your index.php folder, create a new folder "pages".
Inside of the folder pages, create 4 simple PHP files (home.php, register.php, anyother.php and notfound.php), with any content like
<?php
echo "I'm the Register Page.";
?>
This will be an example of index based on your code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8"><title>¨title</title></head>
<body>
<div>
<?php include 'header.php'; ?>
</div>
<div id="menu" align="center">
<table width="790" height="35">
<tr>
<td>Home</td>
<td>Register</td>
<td>AnyOther</td>
<td>Broken Sample</td>
</tr>
</table>
</div>
<div id="sidebar" align="right">
<?php include 'sidebar.php'; ?>
</div>
<div id="Content ">
<?php
if(!isset($_GET['page']) || $_GET['page'] == ''){
$page = 'home'; //If no page specified
} else {
$page = $_GET['page'];
}
switch($page)
{
case 'home':
include '/pages/home.php';//file path of your home page
break;
case 'register':
include '/pages/register.php';
break;
case 'anyother':
include '/pages/anyother.php';
break;
default:
include '/pages/notfound.php'; //If any page that doesn't exists, then get back to home.
}
?>
</div>
<div id="footer">
<?php include("footer.php");?>
</div>
</body>
</html>

Linking to search results directly

I got myself into a project at work that is going beyond my (very modest) coding skills.
So i have a database with 6 fields. I'm able to make searchs on it using php (i followed a youtube tutorial), add records, delete records and update records. All of that is working just fine.
What i need now is this:
I need to link search results (only a few, the most popular) on a image.
Per example, i have a company logo on my main page (let's say company name is..i dunno.. "Google". When i click on it, i wanted it to redirect to the search results of "google", like if i had inserted that in the search field. Is that possible?
(notice that i don't have companies in my database, i'm just trying to give an example so that people can understand what i intend. In my database i would need to link to reflect search results of the field "unidade")
Here is my code so far. The add / update .php i don't think are needed.
<?php
// include the connection file
include "connection.php";
$sql = "SELECT * FROM usuariotb";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .=" WHERE nome LIKE '%".$search_term."%'";
$sql .=" OR posto = '{$search_term}' ";
$sql .=" OR nim = '{$search_term}' ";
$sql .=" OR unidade LIKE '%".$search_term."%'";
$sql .=" OR codigoueo LIKE '%".$search_term."%'";
}
$query = mysql_query($sql) or die (mysql_error());
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM usuariotb WHERE id = {$id}";
mysql_query($sql_delete) or die(mysql_error());
header("location:display_data.php");
exit();
}
?>
<html>
<head>
<meta charset="iso-8859-1">
<title></title>
<link rel="stylesheet" type="text/css" href="format.css" />
</head>
<body>
<div class="container">
<form name="search_form" method="POST" action="display_data.php">
Search: <input type="text" name="search_box" value=""/>
<input type="submit" name="search" value="Procurar">
</form>
<div class="container">
<div class="content">
<div class="toolbar">Adicionar Novo Militar</div>
</div>
<div class="toolbar">Voltar à página de pesquisa</div>
</div>
</div>
<div class="container">
<div class="content">
<table width="90%" cellpadding="5" cellspacing="5">
<tr>
<td><strong>Nome</strong></td>
<td><strong>Nim</strong></td>
<td><strong>Posto</strong></td>
<td><strong>Unidade</strong></td>
<td><strong>Sigla Unidade</strong></td>
<td><strong>Observações</strong></td>
<td><strong>Acções</strong></td>
</tr>
<?php if (mysql_num_rows($query)) { ?>
<?php while ($row=mysql_fetch_array($query)) {?>
<tr>
<td><?php echo $row['nome'];?></td>
<td><?php echo $row['nim'];?></td>
<td><?php echo $row['posto'];?></td>
<td><?php echo $row['unidade'];?></td>
<td><?php echo $row['codigoueo'];?></td>
<td><?php echo $row['observacoes'];?></td>
<td>Delete</td>
<td>Edit</td>
</tr>
<?php } /* end loop */ ?>
<?php } else { ?>
<h2> Nothing to display!</h2>
<?php } /* end rows checking */ ?>
</table>
</div>
</div>
</body>
</html>
First of all, I empathize with you regarding being tasked with a more complex task than your current ability. Been there, done that. Many companies do this.
Regarding your task, for search every website usually uses GET to do the search e.g. https://www.google.co.in/search?q=stackoverflow. Notice the q=stackoverflow part. For this you do not need to submit any form, just use the URL directly.
So, I suggest you visit the websites where you want to link directly for search. Search for some sample text, say TEST and observe the URL of the page that opens.
Then using JavaScript/jQuery/etc, on click of the logo, read whatever text you want to search, create a URL in JavaScript and redirect there.
This is the general idea, feel free to comment and ask if you face any issues in implementation.

PHP Combining search function with pagination

So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)
Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.
i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.

Categories