Ud over den manglende mysqli-forbindelsesressource/-objekt er der nogle andre problemer med scriptet:
- det er tilbøjeligt til sql-injektioner
- du tester ikke mysql-forbindelsen som vist på http://docs.php .net/mysqli.quickstart.connections
- scriptet mangler generelt fejlhåndtering. Enhver af mysqli_*-funktionerne/-metoderne kan mislykkes. For eksempel. advarslen vedrørende
mysqli_num_rows
er relateret til ikke at kontrollere returværdien af mysqli_query
. - din funktion test_input() tester ikke noget, men ændrer værdien; og en e-mailadresse har intet at gøre med htmlspecialchars() et al. Bare slip den funktion.
- e-mail-adressevalideringen virker alt for kompleks uden at være indlysende fortjeneste.
- I stedet for en SELECT/INSERT-kombination for at forhindre en e-mailadresse i at blive indsat to gange skal du bare oprette en unikt indeks på det felt, og mysql-serveren vil pålideligt forhindre dubletter.
for eksempel.
<?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 ...]
}
}