-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd.php
88 lines (70 loc) · 2.65 KB
/
add.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
include('config/db_connect.php');
$nickname = $email = $songs = '';
$errors = ['email'=>'', 'nickname'=>'', 'songs'=>''];
if(isset($_POST['submit'])){
//check
if(empty($_POST['email'])){
$errors['email'] = 'An email is required <br/>';
} else {
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email'] = 'Email must be a valid email address';
}
}
if(empty($_POST['nickname'])){
$errors['nickname'] = 'A nickname is required <br/>';
} else {
$nickname = $_POST['nickname'];
if(!preg_match('/^[a-zA-Z\s]+$/', $nickname)){
$errors['nickname'] = 'Nickname must be letters and spaces only';
}
}
if(empty($_POST['songs'])){
$errors['songs'] = 'Enter 3 songs <br/>';
} else {
$songs = $_POST['songs'];
if(!preg_match('/^([a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $songs)){
$errors['songs'] = 'Songs must be a comma separated list';
}
}
if(array_filter($errors)){
} else {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$nickname = mysqli_real_escape_string($conn, $_POST['nickname']);
$songs = mysqli_real_escape_string($conn, $_POST['songs']);
//create sql
$sql = "INSERT INTO songs(nickname, email, songs) VALUES('$nickname', '$email', '$songs')";
//save to db and check
if(mysqli_query($conn, $sql)){
//success
header('Location: index.php');
} else {
//error
echo 'query error: ' . mysqli_error($conn);
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include('templates/header.php') ?>
<section class="container grey-text">
<h4 class="center">Add your favorite songs</h4>
<form action="add.php" method="POST" class="white">
<label>Your Email:</label>
<input type="text" name="email" value="<?php echo htmlspecialchars($email) ?>">
<div class="red-text"><?php echo $errors['email'] ?></div>
<label>Your Nickname:</label>
<input type="text" name="nickname" value="<?php echo htmlspecialchars($nickname) ?>">
<div class="red-text"><?php echo $errors['nickname'] ?></div>
<label>3 favorite songs (comma separated):</label>
<input type="text" name="songs" value="<?php echo htmlspecialchars($songs) ?>">
<div class="red-text"><?php echo $errors['songs'] ?></div>
<div class="center">
<input type="submit" name="submit" value="submit" class="btn brand">
</div>
</form>
</section>
<?php include('templates/footer.php') ?>
</html>