function conectar() { $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password,[PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch (Exception $ex) { echo $ex->getMessage(); } }
Select con city
<?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); print_r($_GET); $address = filter_input(INPUT_GET, "address"); $district = filter_input(INPUT_GET, "district"); $city_id = filter_input(INPUT_GET, "city_id"); $postal_code = filter_input(INPUT_GET, "postal_code"); $phone = filter_input(INPUT_GET, "phone"); if(!empty($address) && !empty($district) &&!empty($city_id) && !empty($phone)){ $sql="insert into address (address,district,city_id,postal_code,phone) values "; $sql.="('$address','$district',$city_id,'$postal_code','$phone')"; $conn->exec($sql); } $sql = "select city_id,city from city order by city"; $resul = $conn->query($sql); $ciudades = $resul->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $ex) { echo $ex->getMessage(); } ?> <form> Dirección: <input type="text" name="address"><br/> Distrito: <input type="text" name="district"><br/> Ciudad: <select name="city_id"> <option value="0">Seleccione la ciudad</option> <?php foreach ($ciudades as $ciudad) { ?> <option value="<?= $ciudad['city_id'] ?>"><?= $ciudad['city'] ?></option> <?php } ?> </select><br/> Código postal: <input type="text" name="postal_code"><br/> Teléfono: <input type="text" name="phone"><br/> <input type="submit"> </form>
Galería de imágenes
<h1>Galería de imágenes</h1> <?php $borrar= filter_input(INPUT_GET, 'borrar'); if(!empty($borrar)){ unlink("images/".$borrar); } if (isset($_FILES['imagen'])) { if (explode("/", $_FILES['imagen']['type'])[0] == 'image') { move_uploaded_file($_FILES['imagen']['tmp_name'], "images/" . $_FILES['imagen']['name']); ?> <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Ok</strong> El archivo se ha subido con éxito. </div> <?php } else { ?> <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Error</strong> El archivo subido no es de tipo imagen. </div> <?php } } ?> <form action='index.php' method="post" enctype="multipart/form-data"> <input type="file" name="imagen" > <input type="submit" class="btn btn-success" value="Enviar imagen"> </form> <hr/> <div style='display:flex;flex-wrap: wrap;'> <?php $imagenes = scandir("./images"); for ($i = 2; $i < count($imagenes); $i++) { ?> <div class="card" style="width:400px" > <img class="card-img-top" src="images/<?= $imagenes[$i] ?>" alt="Card image"> <div class="card-body"> <h4 class="card-title"><?= $imagenes[$i] ?></h4> <a href="?borrar=<?= $imagenes[$i] ?>" class="btn btn-danger">Borrar imagen</a> </div> </div> <?php } ?> </div>
El hombre de la factura de 10000 dólares
CRUD actores Sakila
Index.php
<h1>Mantenimiento actores de Sakila</h1> <form> <input type="hidden" name="action" value="insert"> Nombre:<input type="text" name="first_name"> Apellidos:<input type="text" name="last_name"> <input type="submit" class="btn btn-info"> </form> <table class="table"> <tr><td>Id</td><td>Nombre</td><td>Apellidos</td><td>Acciones</td></tr> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; $action = filter_input(INPUT_GET, 'action'); $last_name = filter_input(INPUT_GET, 'last_name', FILTER_SANITIZE_STRING); $first_name = filter_input(INPUT_GET, 'first_name', FILTER_SANITIZE_STRING); $actor_id = filter_input(INPUT_GET, 'actor_id', FILTER_VALIDATE_INT); try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Acciones sobre la base de datos if ($action == 'insert' && !empty($first_name) && !empty($last_name)) { $sql = "insert into actor (first_name, last_name) values ('$first_name','$last_name')"; $conn->exec($sql); } if ($action == "delete" && !empty($actor_id)) { $sql = "delete from actor where actor_id=$actor_id"; $conn->exec($sql); } if ($action == 'update' && !empty($first_name) && !empty($last_name) && !empty($actor_id)) { $sql = "update actor set first_name='$first_name', last_name='$last_name' where actor_id=$actor_id"; $conn->exec($sql); } $sql = "select * from actor"; $resul = $conn->query($sql); while ($fila = $resul->fetch(PDO::FETCH_ASSOC)) { ?> <tr><td><?= $fila['actor_id'] ?></td> <td><?= $fila['first_name'] ?></td> <td><?= $fila['last_name'] ?></td> <td><a href="?action=delete&actor_id=<?= $fila['actor_id'] ?>">Borrar</a> <a href="update.php?actor_id=<?= $fila['actor_id'] ?>">Editar</a></td></tr> <?php } } catch (Exception $ex) { echo "Ha ocurrido un error<br/>" . $ex->getMessage(); } ?></table>
update.php
<h1>Editar actor</h1> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; $actor_id = filter_input(INPUT_GET, 'actor_id', FILTER_VALIDATE_INT); if (!empty($actor_id)) { try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "select * from actor where actor_id=$actor_id"; $resul=$conn->query($sql); $fila=$resul->fetch(); } catch (Exception $ex) { echo "Ha ocurrido un error<br/>" . $ex->getMessage(); } } ?> <form action="index.php"> <input type="hidden" name="action" value="update"> <input type="hidden" name="actor_id" value="<?=$actor_id?>"> Nombre:<input type="text" name="first_name" value="<?=$fila['first_name']?>"> Apellidos:<input type="text" name="last_name" value="<?=$fila['last_name']?>"> <input type="submit" class="btn btn-info"> </form>
final.php
<h1>Consulta actores de Sakila</h1> <form> Nombre:<input type="text" name="first_name"> Apellidos:<input type="text" name="last_name"> <input type="submit" class="btn btn-info" value="Buscar"> </form> <table class="table"> <tr><td>Id</td><td>Nombre</td><td>Apellidos</td></tr> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; $last_name = filter_input(INPUT_GET, 'last_name', FILTER_SANITIZE_STRING); $first_name = filter_input(INPUT_GET, 'first_name', FILTER_SANITIZE_STRING); try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "select * from actor where 1"; if (!empty($first_name)){ $sql.=" and first_name like '%$first_name%'"; } if (!empty($last_name)){ $sql.=" and last_name like '%$last_name%'"; } $resul = $conn->query($sql); while ($fila = $resul->fetch(PDO::FETCH_ASSOC)) { ?> <tr><td><?= $fila['actor_id'] ?></td> <td><?= $fila['first_name'] ?></td> <td><?= $fila['last_name'] ?></td> </tr> <?php } } catch (Exception $ex) { echo "Ha ocurrido un error<br/>" . $ex->getMessage(); } ?></table>
Web scrapping páginas amarillas
<?php function extraeRegexp($cadena, $inicio, $fin) { preg_match_all('#' . $inicio . '(.*?)' . $fin . '#', $cadena, $matches); return $matches[1]; } $total = []; for ($i = 1; $i <= 6; $i++) { $url = "https://www.paginasamarillas.es/search/mascotas-y-tiendas-de-animales/all-ma/barcelona/all-is/barcelona/all-ba/all-pu/all-nc/$i?what=mascotas+y+tiendas+de+animales&where=barcelona&ub=false&qc=true"; $web = file_get_contents($url); $urls = extraeRegexp($web, "<div class=\"envio-consulta\"><a href=\"", "\""); $total = array_merge($total, $urls); } $fichero = fopen("mascotas.csv", "w"); fwrite($fichero, utf8_decode( "Nombre;Categoria;Telefono;Direccion;Cp;Ciudad;Provincia;Web\n")); foreach ($total as $url) { $web = file_get_contents($url); $nombre = extraeRegexp($web, '<h1 itemprop="name">', '</h1>')[0]; $categoria = extraeRegexp($web, '<span class="category">', '</span>')[0]; $telefono = extraeRegexp($web, '<span itemprop="telephone">', '</span>')[0]; $direccion = extraeRegexp($web, '<span itemprop="streetAddress">', '</span>')[0]; $cp = extraeRegexp($web, '<span itemprop="postalCode">', '</span>')[0]; $ciudad = extraeRegexp($web, '<span itemprop="addressLocality">', '</span>')[0]; $provincia = @extraeRegexp($web, '<span class="addressState">', '</span>')[0]; $webaddress = @str_replace("?utm_campaign=paginasamarillas&utm_source=paginasamarillas&utm_medium=referral", "", extraeRegexp($web, 'class="fa icon-link"></i><a href="', '"')[0]); echo $nombre . ";" . $categoria . ";" . $telefono . ";" . $direccion . ";" . $cp . ";" . $ciudad . ";" . $provincia . ";" . $webaddress . "<br/>"; fwrite($fichero, utf8_decode($nombre . ";" . $categoria . ";" . $telefono . ";" . $direccion . ";" . $cp . ";" . $ciudad . ";" . $provincia . ";" . $webaddress . "\n")); } fclose($fichero); ?>
Subir archivos
Subir archivos:
<form method="post" enctype="multipart/form-data"> <input type="file" name="nombre"> <input type="submit"> </form> <?php if (isset($_FILES['nombre'])) { $tipo = explode("/", $_FILES['nombre']['type']); if ($tipo[0] == "image") { $carpeta = "images"; } else { $carpeta = "upload"; } move_uploaded_file($_FILES['nombre']['tmp_name'], "./" . $carpeta . "/" . $_FILES['nombre']['name']); } ?>
Ver contenido carpetas:
<h1>Contenido de upload</h1> <?php $archivos = scandir("upload/"); for ($i = 2; $i < count($archivos); $i++) { ?> <p><a href="upload/<?= $archivos[$i] ?>"><?= $archivos[$i] ?></a> <a href="borrar.php?archivo=upload/<?= $archivos[$i] ?>">Borrar archivo</a> </p> <?php } ?> <h1>Contenido de images</h1> <?php $archivos = scandir("images/"); for ($i = 2; $i < count($archivos); $i++) { ?> <img width="100" src="images/<?= $archivos[$i] ?>"> <a href="borrar.php?archivo=images/<?= $archivos[$i] ?>">Borrar archivo</a> <?php } ?>
Borrar archivo:
<?php $mensaje="Archivo borrado con éxito"; $archivo= filter_input(INPUT_GET, "archivo"); if (file_exists($archivo)){ if(!unlink($archivo)){ $mensaje="ha habido un error borrando el archivo"; } } else { $mensaje="El archivo que ha enviado ($archivo) no existe"; } ?> <h1><?=$mensaje?></h1> <a href="carpetas.php">Volver a carpetas</a>
Php mysql
¡No hay que pestañear!
Web scrapping
//Url a escrapear $url="http://trifulcas.com"; //Archivo para guardar $file="scrap.txt"; $visitadas=[]; $fichero=fopen($file,"w"); scrap($url); fclose($fichero); die(); function scrap($url){ global $visitadas,$fichero; //Guardo la url en visitadas $visitadas[]=$url; //Leo el contenido de la web $web= file_get_contents($url); //Proceso de datos: en este caso simplemente guardo el texto fwrite($fichero,$url); fwrite($fichero,strip_tags($web)); //Busco todos los enlaces de la web preg_match_all("<a href=[\"\'](.+?)[\"\']>", $web, $matches); foreach($matches[1] as $enlace){ //Si son enlaces internos y no han sido visitados llamamos a la función recursivamente if (strpos($enlace,$url)!==false && !in_array($enlace, $visitadas)){ scrap($enlace); } } }