P H P - Personal Home Page - ( 


)
O PHP (um acrônimo recursivo para PHP: Hypertext Preprocessor) é uma linguagem de
script open source de uso geral, muito utilizada, e especialmente adequada para o
desenvolvimento web e que pode ser embutida dentro do HTML
*** Página melhor visualizada no " navegador Chrome "
Index
01 - Sobre PHP
02 - Testando scripts
03 - Configurando Servidor Xampp
04 - Servidor gratuito online - orgfree.com
05 - Criando banco de dados em MySQL no servidor online
06 - Listando registros 1
07 - Listando registros 2
08 - PHP System - Add - Edit - Del - Search
01 - Sobre PHP 
PHP é utilizado como uma linguagem de script do lado do servidor, e é especialmente
indicada para criar páginas web dinâmicas. Esta linguagem inclui suporte para lidar com
bases de dados, como MySQL, que a torna a candidata ideal para o desenvolvimento de
aplicações web, desde pequenos websites pessoais, até aplicações empresariais super
complexas.
Ao contrário do HTML, que é executado pelo browser quando uma página é aberta, PHP é
pré-processado pelo servidor.
Assim, todo o código PHP incluído num ficheiro é processado pelo servidor antes de
enviar algo para o cliente, através do browser.
Uma das grandes vantagens para os programadores PHP é o fato de ser uma linguagem de
script. Algumas linguagens necessitam que os ficheiros sejam compilados em código antes
de poderem ser executados, e este é um processo que consome imenso tempo, desnecessá-
riamente. Não tendo de compilar os ficheiros significa que você poderá editar e testar
o seu código muito mais rapidamente.
Como PHP é uma linguagem do lado do servidor, correr os script PHP no seu computador
requer que tenha um servidor instalado no seu computador.
PHP -> Servidor Web -> Interpretador -> HTML -> Utilizador
Esta é uma forma de entender como funciona a linguagem PHP. Outra ideia simples de se
definir o modo de funcionamento da linguagem PHP é pensar que todo o output gerado pelo
código PHP é HTML.
02 - Testando scripts em PHP 
Para testarmos os codigos / scripts feitos em php precisaremos configurar um servidor
virtual local ( no nosso computador ) para usarmos banco de dados etc,
No exemplo abaixo usaremos um testador de scripts PHP online e neste momento nao insta-
laremos um servidor local.
Existem varios sites testadores de codigos PHP mas selecionei os dois abaixoÇ
http://phptester.net/ ou
http://sandbox.onlinephpfunctions.com/
- No lado esquerdo da tela voce digita o codigo em PHP
- No lado direito da tela e o resultado do codigo ja em execucao.
http://phptester.net/
03 - Configurando um servidor Xampp 
O XAMPP é um pacote com os principais servidores de código aberto do mercado, incluindo
FTP, banco de dados MySQL e Apache com suporte as linguagens PHP e Perl.
Com ele é possível rodar sistemas como WordPress e Drupal localmente, o que facilita e
agiliza o desenvolvimento. Como o conteúdo estará armazenado numa rede local, o acesso
aos arquivos é realizado instantaneamente. O pacote de servidores é baixado cerca de
600 mil vezes por mês, de acordo com dados do SourceForge.
Atualmente, o XAMPP está disponível para quatro sistemas operacionais:
Windows, Linux, Mac OS X e Solaris.
Vamos baixar o Xampp.
https://www.apachefriends.org/download.html

Instale o xampp como qualquer outro programa e apos a instalacao sera mostrada uma
tela como esta abaixo:
1 - Na linha do
apache, ao clicar no botao
Start e possivel que seja possivel iniciar
o servidor pois a porta 80 pode estar sendo utilizada por outro servidor do
Windows IIS ( se estiver instsalado ). Veja na imagem acima em vermelho indica que
estou usando a porta 80, para resolver isto facilmente iremos alterar o porta de
80 para 8080.
2 - Clique no botao
Config, ao abrir este arquivo texto procure por e altere a porta:
de
Listen 80 para
Listen 8080
de
ServerName localhost:80 para
ServerName localhost:8080
3 - No item 3 mostra o arquivo de log ( historico ) dos processo, casa houver algum
problema ali ficara documentado.
Veja na imagem abaixo o Xampp e o servidor virtual Apache esta rodando...

Agora precisaremos criar uma pasta de nome
aula_01 onde salvaremos nossos scripts.
C:\xampp\htdocs\aula_01

Acessando o painel do Xampp. Notem que estamos usando a porta 8080.
Resultado
http://localhost:8080/aula_01/test1.php
04 - Servidor gratuito online - orgfree.com 
Vamos criar a página em PHP abaixo e fazer upload no servidor.

Vamos usar agora o servidor que criamos quando usamos a nossa primeira página em HTML
que tambem disponibiliza
http://www.freewebhostingarea.com/members/

Veja imagem abaixo:
Acessando servidor de arquivos FTP para enviarmos os arquivos para internet...
FTP server:
aula01.orgfree.com
username :
aula01.orgfree.com
Password :
senha123
Clique no botão:
Login para acessar o painel...

Será mostrada a imagem abaixo, vamos fazer o upload do nosso primeiro código em PHP
para o servidor online gratuito.

Clique no botão
Escolher arquivo, escolha o arquivo
php_01.php que é o nosso primeiro
arquivo e clique o ícone verde ( check ) para fazer o upload para o servidor.

Arquivo carregado com sucesso.

Veja abaixo o nosso arquivo
php_01.php

Vamos testar nossa primeira página :)
http://aula01.orgfree.com/php_01.php
05 - Criando banco de dados em MySQL no servidor online
Vamos usar agora o servidor que criamos quando usamos a nossa primeira página em HTML
que tambem disponibiliza
http://www.freewebhostingarea.com/members/

Clique em
Manage DB para criarmos banco de dados em MySQL.
06 - Lista Registros 1 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<?php
$hostname = "localhost";
$username = "root";
$password = "123";
$db = "banco_dados";
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
?>
<table border="1" align=“left”>
<tr>
<td>Nome</td>
<td>Cidade</td>
</tr>
<?php
$query = mysqli_query($dbconnect, "SELECT * FROM amigos")
or die (mysqli_error($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo
"<tr>
<td>{$row['nome']}</td>
<td>{$row['cidade']}</td>
</tr>\n";
}
?>
</table>
</body>
</html>
07 - Listra Registros 2 
<?php
$host = "localhost";
$user = "root";
$pass = "123";
$db_name = "banco_dados";
$connection = mysqli_connect($host, $user, $pass, $db_name);
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$result = mysqli_query($connection,"SELECT * FROM amigos");
$all_property = array();
echo '<table class="data-table">
<tr class="data-heading">';
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>';
array_push($all_property, $property->name);
}
echo '</tr>';
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>';
}
echo '</tr>';
}
echo "</table>";
?>
08 - PHP System - Add - Edit - Del - Search 
PHP System
Users - add users
Friends - add - edit - delete - search
===========
uname -a
Linux debian 4.9.0-8-amd64 #1 SMP Debian 4.9.144-3.1 (2019-02-19) x86_64 GNU/Linux
===========
php -v
PHP 7.0.33-0+deb9u1 (cli) (built: Dec 7 2018 11:36:49) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.33-0+deb9u1, Copyright (c) 1999-2017, by Zend Technologies
===========
Files
users
-rw-r--r-- 1 root root 2283 Mar 17 19:41 register.php
-rw-r--r-- 1 root root 1852 Mar 17 19:02 login.php
-rw-r--r-- 1 root root 107 Mar 17 15:30 logout.php
friends
-rw-r--r-- 1 root root 1406 Mar 6 13:18 add.html
-rw-r--r-- 1 root root 1908 Mar 17 17:48 add.php
-rw-r--r-- 1 root root 3858 Mar 17 17:53 edit.php
-rw-r--r-- 1 root root 190 Feb 26 18:47 delete.php
-rw-r--r-- 1 root root 5833 Mar 17 17:51 search.php
-rw-r--r-- 1 root root 3333 Mar 4 18:50 styles.css
-rw-r--r-- 1 root root 3382 Mar 17 20:06 database.txt
===========
mysql -u root -p123=
create database my_db;
use my_db;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(40) NOT NULL,
`email` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `user` (`id`, `username`, `password`, `email`) VALUES
(1, 'jura', '123', NULL),
(2, 'mike', '123', NULL),
(3, 'isa', '123=', NULL),
(4, 'eric', 'curious=A', NULL);
-- --------------------------------------------------------
select * from user;
+----+----------+-----------+-------+
| id | username | password | email |
+----+----------+-----------+-------+
| 11 | jura | 123 | NULL |
| 12 | mike | 123 | NULL |
| 13 | isa | 123= | NULL |
| 14 | eric | curious=A | NULL |
+----+----------+-----------+-------+
describe user;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(50) | NO | UNI | NULL | |
| password | varchar(40) | NO | | NULL | |
| email | varchar(100) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
-- --------------------------------------------------------
--
-- Table: friends - add - edit - delete - search
--
-- --------------------------------------------------------
CREATE TABLE `friends` (
`id` int(10) NOT NULL,
`name` varchar(100) NOT NULL,
`city` varchar(90) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`notes` mediumtext NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `friends` (`id`, `name`, `city`, `email`, `notes`) VALUES
(1, 'Jurandir x', 'London x', 'way.jap@gmail.com x', 'xxx===='),
(2, 'Eric', 'London', 'eric@gmail.com', 'Note 2'),
(3, 'Mike Allan ', 'USA', 'mike@gmail.com', 'Note 3333'),
(4, 'Isa', 'USA', 'isa@gmail.com', 'Note 4'),
(5, 'Luisa', 'Germany', 'isa@gmail.com', 'Note 5'),
(6, 'Dora', 'Italy', 'dora@gmail.com', 'Note 6'),
(7, 'Father', 'Italy', 'dad@gmail.com', 'Note 7'),
(8, 'Flintstones ', 'Timbo', 'flint@gmail.com', 'notes111'),
(09, 'Mike Santos', 'China', 'x', 'x'),
(10, 'Mike', 'Italy', '9', '9'),
(11, 'Mike Petersen', 'USA', 'peter@gmail', 'Hey there'),
(12, 'Mike Cunha', 'San Francisco', 'xx', 'xxx'),
(13, 'Mike Cunha', 'Idaho', 'aa', 'aaa'),
(14, 'Cat', 'DogLand', '81', '81'),
(15, 'Mike Flier', 'Dublin', 'm', ''),
(16, 'Mike Tyson', 'Sinsinaty', 'x', 'x'),
(17, 'Mike Steven', 'Rio', 'xxxx', ''),
(18, 'Jurassic', 'Timbó', 'way@tpa.com.br', 'xxx'),
(19, 'Jura Peter', 'aaaa', 'way', 'xxx'),
(20, 'Jussara', 'aaaa', 'way', 'xxx'),
(21, 'Zebra', 'LOL', 'xxxx', 'xxxx'),
(22, 'Peter Pan', 'Disney', 'disney@gmail.com ', 'Happy days'),
(23, 'Dog X', 'Food', 'xxx', 'xxx');
===========
mkdir /var/www/html/sys_recs
cd /var/www/html/sys_recs
=================================
R E G I S T R A T I O N
register.php
<!doctype html>
<html>
<head>
<title>User Registration</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<style>
input {
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 2px;
margin-bottom: 2px;
font-size: 21px;
}
table, th, td { border: none; }
input[type=submit] { background-color: #4CAF50; color: white;}
</style>
</head>
<body OnLoad="document.form.user.focus();">
<center>
<form action="" method="post" name="form">
<table width="320" border="4" cellpadding="4" cellspacing="4" class="tabela_cor_fundo">
<tr>
<th colspan="2" bgcolor="#006699" class="titulo"> R E G I S T E R </th>
</tr>
<tr>
<th width="73" align="right">User:</th>
<th width="188" align="left"><input type="text" name="user"></th>
</tr>
<tr>
<th align="right">Password:</th>
<th align="left"><input type="password" name="pass"></th>
</tr>
<tr>
<th colspan="2" height="20"><input type="submit" name="submit" value="Save" class="but1" /></th>
</tr>
<tr>
<th colspan="2" align="left"><a href="login.php">Login</a></th>
</tr>
</table>
</center>
</form>
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['user']) && !empty($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$conn = new mysqli('localhost', 'root', '123=') or die (mysqli_error());
$db = mysqli_select_db($conn, 'my_db') or die("DB Error");
$query = mysqli_query($conn, "SELECT * FROM user WHERE username='".$user."'");
$numrows = mysqli_num_rows($query);
if($numrows == 0)
{
$sql = "INSERT INTO user (username,password) VALUES('$user','$pass')";
$result = mysqli_query($conn, $sql);
if($result){
echo "<br><br><center><font color='blue' size='4pt' font face='verdana'> <br> Your Account Was Created Successfully";
}
else
{
echo "<br><br><center><font color='red' size='4pt' font face='verdana'> <b> Failure!";
}
}
else
{
echo "<br><br><center><font color='red' size='4pt' font face='verdana'> <b><br> That Username already exists! <br><br> <b class='msg3'> Please try again dude!";
}
}
else
{
echo "<br><br><center><font color='red' size='4pt' font face='verdana'> <b><br> Name for the new user and password, please..";
?>
<?php
}
}
?>
</body>
</html>
=================================
L O G I N
login.php
<!doctype html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body OnLoad="document.form.user.focus();">
<center>
<form action="" method="post" name="form">
<table width="300" border="4" cellpadding="4" cellspacing="4" class="tabela_cor_fundo">
<tr>
<th colspan="2" bgcolor="#006699" class="titulo"> L O G I N </th>
</tr>
<tr>
<th width="73" align="right">User:</th>
<th width="188" align="left"><input type="text" name="user"></th>
</tr>
<tr>
<th align="right">Password:</th>
<th align="left"><input type="password" name="pass"></th>
</tr>
<tr>
<th colspan="2" height="20"><input type="submit" name="submit" value="Login" class="but1" /></th>
</tr>
<tr>
<th colspan="2"><p><a href="register.php"> New User Registeration! </a></p></th>
</tr>
</table>
</center>
</form>
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['user']) && !empty($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$conn = new mysqli('localhost', 'root', '123=') or die(mysqli_error());
$db = mysqli_select_db($conn, 'my_db') or die("databse error");
$query = mysqli_query($conn, "SELECT * FROM user WHERE username='".$user."' AND password='".$pass."'");
$numrows = mysqli_num_rows($query);
if($numrows !=0)
{
while($row = mysqli_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($user == $dbusername && $pass == $dbpassword)
{
session_start();
$_SESSION['sess_user']=$user;
header("Location:search.php");
}
}
else
{
echo "<br><br><center><font color='red' size='4pt' font face='verdana'> <b> Invalid Username or Password!";
}
}
else
{
echo "<br><br><center><font color='red' size='4pt' font face='verdana'> <b> Please, input user and password. ";
}
}
?>
</body>
</html>
=================================
L O G O U T
logout.php
<?php
session_start();
unset($_SESSION['sess_user']);
session_destroy();
header("Location: login.php");
?>
=================================
A D D
add.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Add Data </title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload=document.form.name.focus()>
<form action="add.php" method="post" name="form">
<table align="center" width="427" height="91" border="3" cellpadding="4" cellspacing="4" class="tabela_cor_fundo" >
<tr>
<td colspan="2" bgcolor="#006699" class="titulo"><div align="center" ><strong> ADDING DATA </strong></div></td>
</tr>
<tr>
<td align="right"><strong>*Name:</strong></td>
<td width="310"><input name="name" type="text" size="90" /></td>
</tr>
<tr>
<td align="right"><strong>*City:</strong></div></td>
<td><input name="city" type="text" size="90" /></td>
</tr>
<tr>
<td align="right"><strong>*Email:</strong></div></td>
<td><input type="text" name="email" size="90" /></td>
</tr>
<tr>
<td align="right"><strong>Notes:</strong></div></td>
<td><textarea name="notes" cols="90" rows="10"></textarea></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="Submit" class="but1" value="[ Adding Record ]">
<input class="but1" type="button" onClick="location.href='search.php';" value=" Pesquisa " />
</td>
</tr>
</table>
</form>
</body>
</html>
=================================
A D D
add.php
<?php
session_start();
if(!isset($_SESSION["sess_user"])){
header("Location: login.php");
}
else
{
//--- session starts here --------------
?>
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
$link = mysqli_connect("localhost", "root", "123=", "my_db") or die($link);
if(isset($_POST['Submit']))
{
//----------------------------------------------------------
$name = mysqli_real_escape_string($link, $_POST['name']);
$city = mysqli_real_escape_string($link, $_POST['city']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$notes = mysqli_real_escape_string($link, $_POST['notes']);
//----------------------------------------------------------
if(empty($name) || empty($city) || empty($email)) {
if(empty($name)) {
echo "<br><center><font color='red' size='4pt' face='verdana'> <b> Name </b> field is empty. </font><br/>";
}
if(empty($city)) {
echo "<br><center><font color='red' size='4pt' face='verdana'> <b> City </b> field is empty. </font><br/>";
}
if(empty($email)) {
echo "<br><center><font color='red' size='4pt' face='verdana'> <b> Email </b> field is empty. </font><br/>";
}
echo "<br><center> <font color=blue font face='arial' size='4pt'> <a href='javascript:self.history.back();'> <b> [ Go Back ] </b> </a>";
}
else {
$result = mysqli_query($link, "INSERT INTO friends (name,city,email,notes) VALUES('$name','$city','$email','$notes')");
echo "<br><br><center><font color='green' size='4pt' font face='verdana'> <b> Data added successfully. </b> </center>";
echo "<br>";
echo "<center><br/><a href='search.php' size='4pt' font face='verdana'> <b> B a c k </b> </a> </center>";
}
}
?>
</body>
</html>
<?php
//--- session ends here -------
}
?>
=================================
E D I T
edit.php
<?php
session_start();
if(!isset($_SESSION["sess_user"])){
header("Location: login.php");
}
else
{
//--- session starts here --------------
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Alterando Registro</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<?php
//ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
$link = mysqli_connect("localhost", "root", "123=", "my_db") or die($link);
if(isset($_POST['update']))
{
$id = $_POST['id'];
$name = mysqli_real_escape_string($link, $_POST['name']);
$city = mysqli_real_escape_string($link, $_POST['city']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$notes = mysqli_real_escape_string($link, $_POST['notes']);
if(empty($name) || empty($city) || empty($email)) {
if(empty($name)) {
$nm = "<font color='red' size='4pt' face='verdana'>Please, type in your <b> name </b>. Thank you. </font>";
}
if(empty($city)) {
$cy = "<font color='red' size='4pt' face='verdana'>Please, type in your <b> city </b>. Thank you. </font>";
}
if(empty($email)) {
$em = "<font color='red' size='4pt' face='verdana'>Please, type in your <b> email </b>. Thank you. </font>";
}
//echo "<br><center> <font color=blue font face='arial' size='4pt'> <a href='javascript:self.history.back();'> <b> [ Go Back ] </b> </a>";
}
else
{
$result = mysqli_query($link, "UPDATE friends SET name='$name',city='$city',email='$email',notes='$notes' WHERE id=$id");
header("Location: search.php");
}
}
?>
<!-- ------------------------------------------------- -->
<?php
// show record on the screen
$id = $_GET['id'];
$result = mysqli_query($link, "SELECT * FROM friends WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$name = $res['name'];
$city = $res['city'];
$email = $res['email'];
$notes = $res['notes'];
}
?>
<!-- ------------------------------------------------- -->
<html>
<head>
<title> Edit Data </title>
</head>
<body OnLoad="document.form1.name.focus();">
<form name="form1" method="post" action="edit.php">
<table align="center" width="427" height="91" border="3" cellpadding="4" cellspacing="4" class="tabela_cor_fundo" >
<tr>
<td colspan="2" bgcolor="#006699" class="titulo"><div align="center" ><strong> EDITING RECORD </strong></div></td>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
</tr>
<tr>
<td align="right"><strong>*Name:</strong></td>
<td width="310"><input name="name" type="text" value="<?php echo $name; ?>" size="90" /></td>
</tr>
<tr>
<td align="right"><strong>*City:</strong></div></td>
<td><input name="city" type="text" value="<?php echo $city; ?>" size="90" /></td>
</tr>
<tr>
<td align="right"><strong>*Email:</strong></div></td>
<td><input type="text" name="email" value="<?php echo $email; ?>" size="90" /></td>
</tr>
<tr>
<td align="right"><strong>Notes:</strong></div></td>
<td><textarea name="notes" cols="90" rows="10"><?php echo $notes;?></textarea></td>
</tr>
<tr>
<td> </td>
<td>
<input type="hidden" name="id" value=<?php echo $_GET['id'];?>>
<input type="submit" name="update" class="but1" value="Update">
<input class="but1" type="button" onClick="location.href='search.php';" value=" Pesquisa " />
</td>
</tr>
<tr>
<td> </td>
<td><?php echo $nm;?> <br> <?php echo $cy;?> <br> <?php echo $em;?> </td>
</tr>
</table>
</form>
</body>
</html>
<?php
//--- session ends here -------
}
?>
=================================
D E L E T E
delete.php
<?php
$link = mysqli_connect("localhost", "root", "123=", "my_db") or die($link);
$id = $_GET['id'];
$result = mysqli_query($link, "DELETE FROM freinds WHERE id=$id");
header("Location:search.php");
?>
=================================
S E A R C H
search.php
<?php
session_start();
if(!isset($_SESSION["sess_user"])){
header("Location: login.php");
}
else
{
// God is Great
//--- session starts here --------------
?>
<html>
<head>
<meta name="description" content="Php Code for View, Search, Edit and Delete Record" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="styles.css">
<title> Searching for Records </title>
<!-- ----------------------------------------------------- -->
<style style="text/css">
/* Highlight yellow rows */
.hoverTable{
border-collapse:collapse;
}
.hoverTable td{
padding:7px; border:#4e95f4 1px solid;
}
/* Define the default color for all the table rows */
.hoverTable tr{
background: #b8d1f3;
}
/* Define the hover highlight color for the table row */
.hoverTable tr:hover {
background-color: #ffff99;
}
</style>
<!-- ----------------------------------------------------- -->
<style style="text/css">
/* Balloon */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 240px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<!-- ----------------------------------------------------- -->
</head>
<?php
// check for errors - when needed
//ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
$link = mysqli_connect("localhost", "root", "123=", "my_db") or die($link);
?>
<body OnLoad="document.frmSearch.query.focus();">
<form name="frmSearch" method="get" action="<?=$_SERVER['SCRIPT_NAME'];?>">
<center>
<table width="746" border="4" cellpadding="4" cellspacing="4" bordercolor="#006699" >
<tr>
<th width="720">
<p>Welcome <u> <?=$_SESSION['sess_user'];?>! </u> <a href="logout.php">Logout</a></a></p>
</th>
</tr>
<tr>
<th> <p> Keyword
<div class="tooltip">
<input name="query" type="text" id="query" placeholder="Search field..." value="<?=$_GET["query"];?>" >
<span class="tooltiptext">Search for name and city </span>
</div>
<input type="submit" value="Search" class="but1">
<input class="but1" type="button" onClick="location.href='add.html';" value="Novo" /></p> </th>
</tr>
</table>
</form>
<?php
//--------------------------------------------
$query = $_GET['query'];
// get the word typed in the search field
$min_length = 2;
if(strlen($query) >= $min_length){
$query = htmlspecialchars($query);
// muda os caracteres usados pelo HTML
$query = mysqli_real_escape_string($link, $query);
// evite que usem o formulário para fazer SQL injection (um tipo de invasão de sistema)
//--- starts paging ---1
$pagina = isset($_GET["pagina"]) ? $_GET["pagina"] : "1";
$limite = 3;
$links = 3;
$inicio = ($pagina-1) * $limite;
$sqlPaginacao = mysqli_query($link,"SELECT * FROM friends ORDER BY id ASC");
$paginas = intval((mysqli_num_rows($sqlPaginacao)-1) / $limite);
//--- ends paging --- 1
// Paging ... humm... needs improvement ;)
$raw_results = mysqli_query($link, "SELECT * FROM friends WHERE (`name` LIKE '%".$query."%') OR (`city` LIKE '%".$query."%') order by id ASC LIMIT $inicio, $limite") or die(mysqli_error());
if(mysqli_num_rows($raw_results) > 0){
echo "<table class='hoverTable' width='747' border='2' cellpadding='2' cellspacing='2' bordercolor='#006699' >";
//echo "<tr>";
echo "<th width='10' align='left' bgcolor='#009999'><p class='grid_tit'> Id </p></th>";
echo "<th width='180' align='left' bgcolor='#009999'><p class='grid_tit'> Name </p></th>";
echo "<th width='180' align='left' bgcolor='#009999'><p class='grid_tit'> City </p></th>";
echo "<th width='10' align='center' bgcolor='#009999'><p> E </p></th>";
echo "<th width='10' align='center' bgcolor='#009999'><p> D </p></th>";
while($results = mysqli_fetch_array($raw_results)){
echo "<tr>";
echo "<td width='10' align='left'>" .$results['id']. "</td>";
echo "<th width='170' align='left'>" .$results['name']. "</td>";
echo "<th width='170' align='left'>" .$results['city']."</td>";
echo "<td width=10 align='center'> <a href=\"edit.php?id=$results[id]\"> Edit </a>";
echo "<td width='10'> <a href=\"delete.php?id=$results[id]\" onClick=\"return confirm('Delete record?')\"> Delete </a> </td>";
echo "</tr>";
}
echo "</table>";
//--- paging ---
if(($pagina) > 1) {
echo '<a href="?pagina=1">« First</a> ';
$anterior = $pagina - 1;
echo '<a href="?pagina='.$anterior.'&query='.$query.'">Previous</a> ';
}
for ($i = ($pagina-1)-$links; $i<($paginas + 1); $i++) {
if ($i == $pagina -1) {
echo ($i+1) . ' ';
} else {
if($i+1>0 && $i<$pagina+$links) {
$pag = $i+1;
echo '<a href="?pagina='.$pag.'&query='.$query.'">'.$pag.'</a> ';
}
}
}
if ($pagina-1 < $paginas) {
$proxima = $pagina+1;
echo '<a href="?pagina='.$proxima.'&query='.$query.'">Next ›</a>';
$ultima = $paginas + 1;
echo ' <a href="?pagina='.$ultima.'&query='.$query.'">Last »</a>';
}
//--- end paging ---
}
else
{
echo "<br><br><center><font color='red' size='4pt' font face='verdana'> <b> Sorry, nothing was found... <br><br>";
echo "<a href='search.php'> [ New Search ] </a>";
}
}
else
{
echo "<br><br> <br><br><center><font color='red' size='4pt' font face='verdana'> <b> Please, type in at least ".$min_length." characters long in the search field... <br><br>";
}
?>
</body>
</html>
<?php
//--- session ends here -------
}
?>
=================================
S T Y L E S
styles.css
/* ---------------------------------------------------------------------- */
/*--------------------------------------------------------------------
Below - Balloon
*/
#dhtmltooltip{
position: absolute;
left: -300px;
width: 150px;
border: 1px solid black;
padding: 2px;
background-color: lightyellow;
visibility: hidden;
z-index: 100;
/*Remove below line to remove shadow. Below line should always appear last within this CSS*/
filter: progid:DXImageTransform.Microsoft.Shadow(color=gray,direction=135);
}
#dhtmlpointer{
position:absolute;
left: -300px;
z-index: 101;
visibility: hidden;
}
/*--------------------------------------------------------------------
Below - setting different backgound image for different pages
*/
/* sets base style for each page */
html {
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
/* set background image per page */
.pass_bg{
background: url(imgs/pass_bg.gif) center center fixed;
}
.login_bg {
background: url(imgs/login_bg.gif) center center fixed;
}
.contact-bg {
background: url(images/contact-bg.jpg) no-repeat center center fixed;
}
/* ------------------------------------------------------------------------ */
body { font-family: verdana, arial; font-size=12px; }
hr {color:blue;}
p {font-family: verdana, arial; font-size=12px; }
/* cor nos links */
a:link {color:#009900;font-weight: bold;font-family: verdana, arial; text-decoration:none; }
a:visited {color:#CC3300;font-weight: bold;font-family: verdana, arial; text-decoration:none; }
a:hover {color:#FFFF33;font-weight: bold;font-family: verdana, arial; font-size=150%; background:#0066CC; }
.titulo {color:#FFFFFF;font-weight: bold;font-family: verdana, arial; font-size:18px; }
.grid_tit {color:#FFFFFF;font-weight: bold;font-family: verdana, arial; font-size:14px; }
.pass_error {color:#000;font-weight: bold;font-family: verdana, arial; font-size:18px; }
.tot_recs {color:# F00;font-weight: bold;font-family: verdana, arial; font-size:12px; }
.tot_recs_red {color:# F00;font-weight: bold;font-family: verdana, arial; font-size:12px; }
.but1{
background-color: rgb( 43, 153, 91 );
border: 1px solid rgb( 33, 126, 74 );
color:#FFFFFF;font-weight: bold;font-family: verdana, arial;
}
.tabela_cor_fundo { bordercolor=#006699; }
/* ------------------------------------------------------------------------ */
#content
{
width: 900px;
margin: 0 auto;
font-family:Arial, Helvetica, sans-serif;
}
.page
{
float: right;
margin: 0;
padding: 0;
}
.page li
{
list-style: none;
display:inline-block;
}
.page li a, .current
{
display: block;
padding: 5px;
text-decoration: none;
color: #8A8A8A;
}
.current
{
font-weight:bold;
color: #000;
}
.button
{
padding: 5px 15px;
text-decoration: none;
background: #333;
color: #F3F3F3;
font-size: 13PX;
border-radius: 2PX;
margin: 0 4PX;
display: block;
float: left;
}
/* ----------------------------------------------------------------------- */
/* highlight borders of the fields */
input[type=text], textarea
{
border: 1px solid #ccc;
}
input[type=text]:focus, textarea:focus
{
background-color: #E6E6FF;
border: 1px solid #ccc;
}
input[type=password]:focus, textarea:focus
{
background-color: #E6E6FF;
border: 1px solid #ccc;
}
/* ---------------------------------------------------------------------- */
=====
Download - PHP System - Add - Edit - Del - Search
08 - Executando comandos de Linux / PHP 
<?php
if($_POST["comando"])
{
$strRetorno = shell_exec($_POST["comando"]);
}
?>
<html>
<body>
<form action="" method="post">
Executar comando:
<input type="text" name="comando"><br>
<input type="submit" value="enviar">
</form>
<?php
if($strRetorno != "")
{
echo "<b>Comando executado---:".$_POST["comando"]."</b><br>";
echo "<pre>".$strRetorno."</pre>";
}
?>
</body>
</html>
09 - Procurando arquivos / Linux / PHP 
<?php
if($_POST["procura"])
{
$strRetorno = shell_exec("find -name '".$_POST["procura"]."'");
}
?>
<html>
<body>
<h1> Procurando arquivos com find: </h1>
<form action="" method="post">
Procurar por:<input type="text" name="procura"><br>
<input type="submit" value="enviar">
</form>
<?php
if($strRetorno != "")
{
echo "<b> Foi encontrado: : ".$_POST["procura"]."<br>";
echo "<pre>".$strRetorno."</pre>";
}
?>
</body>
</html>
"Wisdom is like a river, the deeper it is the less noise it makes"
Afim de aprender mais? Fale comigo:
linux1.noip@gmail.com