Sunteți pe pagina 1din 11

Workshop1.

Crearea mediului de lucru si conectarea MySQL cu PHP (parte 1: Create, Read)

1. Creati un director nou „Repository“


2. Creati un repository, folosind comanda „Create repository hare“ din meniul
„TortoiseSVN“

3. „Create folder structure“ + „Start Repobrowser“

- Vertraulich / Confidential -
Obtineti o structura de directoare ( momentan goale) care va permit dezvoltarea
continua a unei aplicatii, pastrand versiuni stabile sau personalizate ale acesteia.
In Trunk se va pastra codul curent, modificabil

4. Deoarece in Trunk pot pastra mai multe proiecte, este necesar ca pentru fiecare
proiect sa am creat cate un folder nou.
Crearea unui folder in reposirory se realizeaza cu comanda „Create folder....“ din
meniul contextual:

Pentru a pastra proiectul viitor vom crea directorul cu numele „AppPhp“ ( puteti alege
orice alta denumire doriti)

Pana acum avem pregatit mediul de pastrare al tuturor versiunilor proiectului pe care
il vom incepe .

5. Crearea directorului de lucru si legatura cu repository-ul se face astfel:


- Creati un folder nou, in zona de lucru aleasa ( partitie, cale....)
- Din meniul contextual alegeti comanda „SVN Checkout...“

- Vertraulich / Confidential -
Selectati „...“ din „URL of repository:“
Alegeti folderul din repository, anume creat pentru proiect.

Dupa acceptare si checkout-ul corect facut, primiti mesajul:


- Vertraulich / Confidential -
Crearea conexiunii dintre MySql si PHP:

Cerinte preliminarii:

- Cunostinte minime de HTML


- Cunostinte minime de PHP
- Un mediu local PHP+MySQL ( XAMPP )

Obiective:

- Conectarea unei baze de date MySQL cu PHP utilizand metoda PDO (PHP Data
Objects) (http://php.net/manual/ro/book.pdo.php)
- Crearea unui script care creaza o baza de date noua si o noua structura de tabele
- Adaugarea de inregistrari nou in baza de date utilizand un „form“ HTML si
„Prepared Statements“
- Filtrarea intrarilor din baza de date si afisarea lor intr-o pagina

In directorul de lucru se creaza o structura de directoare si fisiere :

- Common.php contine o functie care converteste caracterele speciale in entitati


HTML ( detalii aici: http://php.net/manual/ro/function.htmlspecialchars.php)

<?php

/**
* Escapes HTML for output
*
*/

function escape($html) {
- Vertraulich / Confidential -
return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
- Config.php – configureaza conexiunea bazei de date:

<?php

/**
* Configuration for database connection
*
*/

$host = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
$dsn = "mysql:host=$host;dbname=$dbname";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);

- Install.php – Deschide o conexiune folosind PDO, pentru a creea o noua baza de


date si o structura de tabele:

<?php

/**
* Open a connection via PDO to create a
* new database and table with structure.
*
*/

require "config.php";

try {
$connection = new PDO("mysql:host=$host", $username, $password, $options);
$sql = file_get_contents("data/init.sql");
$connection->exec($sql);

echo "Database and table users created successfully.";


} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}

- Vertraulich / Confidential -
- In „data“ cream fisierul init.sql care contine:

CREATE DATABASE test;

use test;

CREATE TABLE users (


id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
age INT(3),
location VARCHAR(50),
date TIMESTAMP
);

-In „public“ cream o noua structura de directoare si fisiere:

In „css“ vom avea un fisier style.css

label
{
display: block;
margin: 5px 0;
}

table {
border-collapse: collapse;
border-spacing: 0;
}

td,
th {
padding: 5px;
border-bottom: 1px solid #aaa;

- Vertraulich / Confidential -
}

In „templates“ vom avea doua fisiere footer.php cu urmatorul continut:

</body>
</html>

si header.php cu urmatorul continut:

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Simple Database App</title>

<link rel="stylesheet" href="css/style.css">


</head>

<body>
<h1>Simple Database App</h1>

Create.php

<?php

/**
* Use an HTML form to create a new entry in the
* users table.
*
*/

if (isset($_POST['submit'])) {
require "../config.php";
require "../common.php";

try {
$connection = new PDO($dsn, $username, $password, $options);

- Vertraulich / Confidential -
$new_user = array(
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"email" => $_POST['email'],
"age" => $_POST['age'],
"location" => $_POST['location']
);

$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"users",
implode(", ", array_keys($new_user)),
":" . implode(", :", array_keys($new_user))
);

$statement = $connection->prepare($sql);
$statement->execute($new_user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>

<?php require "templates/header.php"; ?>

<?php if (isset($_POST['submit']) && $statement) { ?>


<blockquote><?php echo $_POST['firstname']; ?> successfully
added.</blockquote>
<?php } ?>

<h2>Add a user</h2>

<form method="post">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname">
<label for="email">Email Address</label>
<input type="text" name="email" id="email">
<label for="age">Age</label>
<input type="text" name="age" id="age">
<label for="location">Location</label>
<input type="text" name="location" id="location">
- Vertraulich / Confidential -
<input type="submit" name="submit" value="Submit">
</form>

<a href="index.php">Back to home</a>

<?php require "templates/footer.php"; ?>

Read.php

<?php

/**
* Function to query information based on
* a parameter: in this case, location.
*
*/

if (isset($_POST['submit'])) {
try {

require "../config.php";
require "../common.php";

$connection = new PDO($dsn, $username, $password, $options);

$sql = "SELECT *
FROM users
WHERE location = :location";

$location = $_POST['location'];

$statement = $connection->prepare($sql);
$statement->bindParam(':location', $location, PDO::PARAM_STR);
$statement->execute();

$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php require "templates/header.php"; ?>

- Vertraulich / Confidential -
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>

<table>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>Age</th>
<th>Location</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["id"]); ?></td>
<td><?php echo escape($row["firstname"]); ?></td>
<td><?php echo escape($row["lastname"]); ?></td>
<td><?php echo escape($row["email"]); ?></td>
<td><?php echo escape($row["age"]); ?></td>
<td><?php echo escape($row["location"]); ?></td>
<td><?php echo escape($row["date"]); ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<blockquote>No results found for <?php echo escape($_POST['location']);
?>.</blockquote>
<?php }
} ?>

<h2>Find user based on location</h2>

<form method="post">
<label for="location">Location</label>
<input type="text" id="location" name="location">
<input type="submit" name="submit" value="View Results">
</form>
- Vertraulich / Confidential -
<a href="index.php">Back to home</a>

<?php require "templates/footer.php"; ?>

Index.php

<?php include "templates/header.php"; ?>


<ul>
<li><a href="create.php"><strong>Create</strong></a> - add a user</li>
<li><a href="read.php"><strong>Read</strong></a> - find a user</li>
</ul>

<?php include "templates/footer.php"; ?>

- Vertraulich / Confidential -