Selain sumber daya/objek koneksi mysqli yang hilang, ada beberapa masalah lain dengan skrip:
- ini rentan terhadap injeksi sql
- Anda tidak menguji koneksi mysql seperti yang ditunjukkan di http://docs.php .net/mysqli.quickstart.connections
- skrip secara umum tidak memiliki penanganan kesalahan. Salah satu fungsi/metode mysqli_* mungkin gagal. Misalnya. peringatan tentang
mysqli_num_rows
terkait dengan tidak memeriksa nilai kembalianmysqli_query
. - fungsi Anda test_input() tidak menguji apa pun kecuali mengubah nilainya; dan alamat email tidak ada hubungannya dengan htmlspecialchars() et al. Jatuhkan saja fungsi itu.
- validasi alamat email tampaknya terlalu rumit tanpa jelas prestasi.
- Alih-alih kombo SELECT/INSERT untuk menghalangi alamat email dimasukkan dua kali, buat saja indeks unik di bidang itu dan server mysql akan andal mencegah duplikat.
misalnya
<?php
define('MYSQL_ER_DUP_KEY', 1022); // see https://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html#error_er_dup_key
$errors = array();
if($_POST) // might be superfluous
{
// simplified email validation
// improve if needed
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ( !$email ) {
// removed html/style from error message, better do that when printing the error
$errors['email1'] = "A valid email address is required";
}
// you only need the database connection after the email address is validated
$mysqli = new mysqli('localhost', 'root', '','ecommerce');
// see http://docs.php.net/mysqli.quickstart.connections
if ($mysqli->connect_errno) {
trigger_error("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error, E_USER_ERROR);
}
// not checking if this email address is already in the database
// instead create a unique index for that field
// see https://dev.mysql.com/doc/refman/5.6/en/constraint-primary-key.html
// - otherwise you'd at least have to lock the table to avoid race conditions -
// sql injections: see http://docs.php.net/security.database.sql-injection
// to prevent sql injections you either have to make sure string literals are
// properly encoded/escaped or use preparead statements+parameters
$stmt = $mysqli->prepare('INSERT INTO subscriptions (email) VALUES (?)');
if ( !$stmt ) {
trigger_error("prepare statement failed (" . $mysqli->errno . ") " . $mysqli->error, E_USER_ERROR);
}
else if ( !$stmt->bind_param('s', $email) ) {
trigger_error("bind_param failed (" . $stmt->errno . ") " . $stmt->error, E_USER_ERROR);
}
else if ( !$stmt->execute() ) {
// email has a unique index, inserting an email address a second time
// results in a ER_DUP_KEY error
if ( MYSQL_ER_DUP_KEY==$stmt->errno ) {
$errors['email2'] = "email address already in subsription list";
}
else { // otherwise it's "really" an error
trigger_error("execute failed (" . $stmt->errno . ") " . $stmt->error, E_USER_ERROR);
}
}
else {
[... inserted ...]
}
}