Curs Php-mysql

In acest tutorial vom crea si testa o aplicatie CRUD simpla cu Laravel (Create-Read-Update-Delete) folosind date stocate intr-o Baza de Date MySQL, folosind clasa DB pentru interogari SQL.
- Acest exemplu il puteti folosi ca punct de inceput pentru un CMS.

• Pentru a descarca fisierele cu codurile prezentate aici, clic pe: Laravel MySQL Exemplu CRUD.

1. Cream un resource controller numit PagesMysql.
Copiati urmatorul cod si salvati-l in "app/Http/Controllers/PagesMysql.php".
<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

//resource controller to Insert, Update, Show, delete pages in mysql
class PagesMysql extends Controller {
 protected $table ='pages';

 //create the table if not exists
 //@return string
 public function createTable(){
 $sql ='CREATE TABLE IF NOT EXISTS '. $this->table .' (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(100), description VARCHAR(150), content MEDIUMTEXT, dtreg TIMESTAMP NOT NULL DEFAULT NOW()) CHARACTER SET utf8 COLLATE utf8_general_ci';
 if(DB::statement($sql)) return 'Table: '. $this->table .' successfully created.<br><a href="/mysql">Main Page</a>';
 else return 'Unable to create table: '. $this->table;
 }

 //@return view() with list of pages
 public function index(){
 $pages = DB::select('select id, title from '. $this->table);
 return view('pages.index',['title'=>'Pages List', 'pages'=>$pages]);
 }

 //Show the form for creating a new page
 //@return view
 public function create(){
 return view('pages.form_insert', ['title'=>'Create New Page']);
 }

 //Insert /Store a newly created page
 //@return string
 public function store(Request $request){
 $re ='No valid request';
 if($request->has(['title', 'description', 'content'])){
 $sql ='INSERT INTO '. $this->table .' (title, description, content) VALUES (:title, :description, :content)';
 $vals =['title'=>$request->title, 'description'=>$request->description, 'content'=>$request->content];

 if(DB::insert($sql, $vals)){
 $idpg = DB::getPdo()->lastInsertId(); //auto-increment id for newly created page
 $re ='Record inserted successfully.<br><a href="/page/'. $idpg .'">See the page</a>';
 }
 else $re = 'Unable to insert data in table: '. $this->table;
 }
 return $re;
 }

 //Display the specified page
 //@param int $id
 //@return view
 public function show($id){
 $page = DB::select('select title, description, content from '. $this->table .' where id =:id LIMIT 1', ['id'=>$id]);

 //keep data for variables in view
 $page =[
 'title'=>$page[0]->title,
 'description'=>$page[0]->description,
 'content'=>$page[0]->content
 ];
 return view('pages.page', $page);
 }

 //Show the form for editing the specified page
 //@param int $id
 //@return view
 public function edit($id){
 $page = DB::select('select id, title, description, content from '. $this->table .' where id =:id LIMIT 1', ['id'=>$id]);

 //keep data for variables in view
 $page =[
 'title'=>'Edit page',
 'id'=>$page[0]->id,
 'f_title'=>$page[0]->title,
 'f_description'=>$page[0]->description,
 'f_content'=>$page[0]->content
 ];
 return view('pages.form_update', $page);
 }

 //Update the specified resource in storage.
 //@param Request $request
 //@param int $id
 //@return string
 public function update(Request $request, $id){
 $re ='No valid request';
 if($request->has(['title', 'description', 'content'])){
 $sql ='UPDATE '. $this->table .' SET title=:title, description=:description, content=:content WHERE id=:id';
 $vals =['title'=>$request->title, 'description'=>$request->description, 'content'=>$request->content, 'id'=>$id];

 if(DB::update($sql, $vals)){
 $re ='Record updated successfully.<br><a href="/page/'. $id .'">See the page</a>';
 }
 else $re = 'Unable to update data in table: '. $this->table;
 }
 return $re;
 }

 //Remove the specified page
 //@param int $id
 //@return string
 public function destroy($id){
 $nrd = DB::delete('delete from '. $this->table .' where id =:id LIMIT 1', ['id'=>$id]);
 if($nrd >.0) return 'Record deleteed successfully.<br><a href="/mysql">Click Here</a> to go back.';
 else return 'Unable to delete data in table: '. $this->table;
 }
}
2. Creati un director numit "pages" in directorul resources/views/. In directorul "pages/" vom crea cinci fisiere blade template pentru aceasta aplicatie.

a) Creati un template pt. sectiunea <head> a paginilor, in fisierul: resources/views/pages/head.blade.php. Copiati urmatorul cod in acel fisier. Acest fisier va fi inclus in celelalte.
<!doctype html>
<html lang="{{app()->getLocale()}}">
<head>
<meta charset="utf-8">
<title>{{$title}}</title>
</head>
<body>
<h1>{{$title}}</h1>
b) Creati inca un fisier template in: resources/views/pages/index.blade.php si copiati urmatorul cod in acel fisier. Va afisa o pagina cu un link catre formularul de adaugare date in mysql, si o lista cu paginile existente in baza de date.
@include('pages.head')

<a href="{{route('mysql.create')}}" title='Create New Page'>Create New Page</a>
<div id='pages'>
@if($pages && count($pages)>0)
 <ol>
 @foreach($pages as $page)
 <li><a href="/page/{{$page->id}}">{{$page->title}}</a> - <a href="/mysql/{{$page->id}}/edit">Edit</a> - <form method="post" action="/mysql/{{$page->id}}" style='display:inline'>{{ csrf_field() }} {{method_field('DELETE')}} <input type='submit' value='DELETE'/></form></li>
 @endforeach
 </ol>
@endif
</div>

</body>
</html>
c) Acum cream al treilea fisier view in "pages/". Copiati si salvati acest cod in: resources/views/pages/page.blade.php.
- Acest view va arata datele paginii cand e accesata o adresa de forma: 'page/{id}'.
@include('pages.head')

Description: {{$description}}
<h3>Content</h3>
{!!$content !!}
</body>
</html>
d) Creati formularul pentru introducere date in MySQL. Copiati si salvati acest cod in: resources/views/pages/form_insert.blade.php.
- Acest view este returnat cand e accesata pagina: /mysql/create
@include('pages.head')

<form method="post" action="/mysql">
{{ csrf_field() }}

Title: <input type='text' name='title' required /><br>
Description: <input type='text' name='description' /><br>
Content:<br>
<textarea name='content'>Content</textarea><br>
<input type='submit' value='Store'/>
</form>

</body>
</html>
e) Creati formularul pentru update date in MySQL. Copiati si salvati acest cod in: resources/views/pages/form_update.blade.php.
- Acest view este returnat cand e accesata o pagina de forma: /mysql/{id}/edit
@include('pages.head')

<form method="post" action="/mysql/{{$id}}">
{{ csrf_field() }}
{{method_field('PUT')}}

 Title: <input type='text' name='title' value='{{$f_title}}' required /><br>
 Description: <input type='text' name='description' value='{{$f_description}}' /><br>
 Content:<br>
 <textarea name='content'>{!!$f_content!!}</textarea><br>
<input type='submit' value='Update'/>
</form>

</body>
</html>
3. Acum se defineste codul pt. Route care foloseste controller-ul PagesMysql; adaugati urmatorul cod in fisierul routes/web.php:
//calls the method to create the table in mysql
Route::get('mysql/createtable','PagesMysql@createTable');

//on /page/{id} request, calls the method to show page data
Route::get('page/{id}','PagesMysql@show')->where('id', '[0-9]+');

/*
This resource handle multiple requests to Insert, Update, Show, delete pages in mysql
Automatically calls methods according to request
*/
Route::resource('mysql','PagesMysql');

Folosire aplicatie CRUD

Acum puteti folosi aceasta aplicatie simpla CRUD pentru a stoca, edita si sterge date de pagini web in mysql.

1. Mai intai, accesati urmatoarea adresa URL pentru a crea tabelul in baza de date:
//localhost:8000/mysql/createtable
- Rezultat:
Table: pages successfully created.
Main Page
2. Vizitati acest URL (sau apasati pe link-ul "Main Page"):
//localhost:8000/mysql
- Rezultatul va aparea precum se vede in imaginea urmatoare:
mysql list pages

3. Apasati pe link-ul Create New Page. Va deschide o pagina cu un formular pentru a aduga datele unei noi pagini; cum se vede in aceasta imagine:
Laravel mysql create page

4. Adaugati date in campurile formularului, apoi apasati pe butonul "Store" pentru a trimite formularul. Ar trebui sa returneze un raspuns ca acesta:
Record inserted successfully.
See the page
- Daca apasati pe link-ul "See the page", va deschide pagina pe care tocmai ati creat-o.

5. Acum, accesati din nou adresa:
//localhost:8000/mysql
- Va afisa un link catre pagina pe care ati creat-o, si butoane Edit si Delete; ca in aceasta imagine:
mysql list pages-2

Acum, puteti crea inca o pagina, sau edita si sterge pagina existenta.

- Daca apasati pe link-ul "Edit", va afisa o pagina cu un formular ca in aceasta imagine:
Laravel mysql edit page

• Pentru a descarca fisierele cu codurile prezentate aici, apasati pe: Laravel MySQL Exemplu CRUD.

Un Test simplu in fiecare zi

HTML
CSS
JavaScript
PHP-MySQL
Engleza
Spaniola
Ce atribut face ca valoarea din caseta de text sa nu poata fi modificata de utilizator?
checked="checked" readonly="readonly" disabled="disabled"
<input type="text" value="valoare-fixa" readonly="readonly" name="a_name" />
Ce proprietate CSS permite crearea de colturi rotunjite?
background-size border-size border-radius
.class {
  border:2px solid blue;
  border-radius:1.2em;
}
Ce instructiune afiseaza o fereastra cu mesaj si butoane OK si Cancel?
indexOf() confirm() prompt()
var ques = window.confirm("Rezultatul lui 0+0 este 0?");
if (ques) alert("Corect");
else alert("Incorect");
Indicati functia PHP care returneaza numarul cel mai mic dintr-o multime de numere.
floor() ceil() min()
$min_nr = min(12, 8, 25, 13);
echo $min_nr;        // 8
Alegeti verbul corect care trebuie in propozitia: "Its ears ... big".
are is has
Its ears are big.
- Urechile lui sunt mari.
Alegeti verbul corect care trebuie in propozitia: "Los niños ... deportistas"
soy son está
Los niños son deportistas.
- Copii sunt sportivi.
Exemplu simplu de aplicatie CRUD cu MySQL in Laravel

Last accessed pages

  1. Creare si editare pagini HTML (52266)
  2. Preluare date din formular si adaugare in MySQL (1840)
  3. Afisare si chenare din CSS la elemente HTML (2582)
  4. Data si Ora in engleza - Date and Time (14989)
  5. Viitor perfect si Viitorul perfect continuu - Future perfect and Continuous (14979)

Popular pages this month

  1. Cursuri si Tutoriale: Engleza, Spaniola, HTML, CSS, Php-Mysql, JavaScript, Ajax (903)
  2. Curs HTML gratuit Tutoriale HTML5 (815)
  3. Curs si Tutoriale JavaScript (665)
  4. Curs CSS Online Tutoriale CSS3 (618)
  5. Curs PHP MySQL, Tutoriale si Scripturi PHP (613)