Introducción a la programación en PHP y MySQL
clase 2
Tecnologías:
¿Que es MySQL?
es un sistema de gestión de bases de datos relacional, multihilo y multiusuario con más de seis millones de instalaciones.
Sentencias de definición de datos
- Database
- Table
- Function
- Procedure
- View
- Trigger
-- Create Database
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_specification] ...
create_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
-- Drop Database
DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
-- Create Table
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
select_statement
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_tbl_name | (LIKE old_tbl_name) }
-- Drop Table
DROP [TEMPORARY] TABLE [IF EXISTS]
tbl_name [, tbl_name] ...
[RESTRICT | CASCADE]
-- Create Function
CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
-- Drop Function
DROP FUNCTION [IF EXISTS] sp_name
-- Create Procedure
CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
-- Drop Procedure
DROP PROCEDURE [IF EXISTS] sp_name
-- Create View
CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
-- Drop View
DROP VIEW [IF EXISTS]
view_name [, view_name] ...
[RESTRICT | CASCADE]
-- Create Trigger
CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name FOR EACH ROW
trigger_body
trigger_time: { BEFORE | AFTER }
trigger_event: { INSERT | UPDATE | DELETE }
-- Drop Trigger
DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name
Cuerpo de funciones y procedimientos
- Sentencia Simple
- begin ... end;
- Estructuras de control
-- Sentencia simple
create or replace function
suma(arg1 int, arg2 int)
returns int
return arg1 + arg2;
create or replace procedure persona(v_id int)
select * from person where id = v_id;
delimiter //
create or replace function maxSueldo(v_id int)
returns decimal(7,2)
begin
declare v_max int;
select max(sueldo) into v_max
from (
select sueldo
from empleado
where id = v_id
union
select max(sueldo)
from historico
where empleado_id = v_id
) s;
return v_max;
end;
//
delimiter ;
-- Case
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE
-- If
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
/* Sólo puede aparecer dentro de estructuras
LOOP, REPEAT y WHILE */
ITERATE label
/* Puede aparecer dentro de estructuras
LOOP, REPEAT, WHILE y BEGIN ... END */
LEAVE label
-- Loop
[begin_label:] LOOP
statement_list
END LOOP [end_label]
-- Repeat
[begin_label:] REPEAT
statement_list
UNTIL search_condition
END REPEAT [end_label]
-- While
[begin_label:] WHILE search_condition DO
statement_list
END WHILE [end_label]
Sentencias de manipulación de datos
CALL sp_name([parameter[,...]])
CALL sp_name[()]
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[PARTITION (partition_name,...)]
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
[(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
[(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
[PARTITION (partition_name,...)]
[(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
[PARTITION (partition_name,...)]
[(col_name,...)]
SELECT ...
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[PARTITION partition_list]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
Ejercicio 1
Ejercicio 1
Restricciones:
- Todo nombre y apellido de persona debe guardarse en mayúsculas (tanto en insert como en update)
- No pueden crear cuenta personas menores a 13 años.
MySQL y PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* comprobar la conexión */
if ($mysqli->connect_errno) {
printf("Falló la conexión: %s\n", $mysqli->connect_error);
exit();
}
/* Crear una tabla que no devuelve un conjunto de resultados */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Se creó con éxtio la tabla myCity.\n");
}
/* Consultas de selección que devuelven un conjunto de resultados */
if ($resultado = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("La selección devolvió %d filas.\n", $resultado->num_rows);
/* liberar el conjunto de resultados */
$resultado->close();
}
$mysqli->close();
?>
MySQL y PHP
/* sentencia preparada */
if ($sentencia = $mysqli->prepare("SELECT Code, Name FROM Country
where Continent = ? ORDER BY Name LIMIT 5")) {
$sentencia->execute();
/* ligar parámetros para marcadores */
$sentencia->bind_param('s', 'Europa');
/* vincular variables a la sentencia preparada */
$sentencia->bind_result($col1, $col2);
/* obtener valores */
while ($sentencia->fetch()) {
printf("%s %s\n", $col1, $col2);
}
/* cerrar la sentencia */
$sentencia->close();
}
/* cerrar la conexión */
$mysqli->close();
Ejercicio 2
- Crear un script php que inserte 500 personas y 1000 comentarios (los nombres pueden ser "nombre1 apellido1", y el texto del comentario puede ser "texto 1".
- La relación entre personas y comentarios debe ser aleatoria (el id de las personas debería ser entre 1 y 500).
- Realizar una consulta mostrando las personas y la cantidad de comentarios que realizó cada una, ordenado por la cantidad de comentarios de manera decreciente.
¿Preguntas?
Links de Interés
php y mysql - Clase 2
By Agustin Moyano
php y mysql - Clase 2
- 885