我试图弄清楚为什么这段代码有时会插入,而其他时候却不会插入。没有错误消息或错误日志。
代码逻辑是,如果电子邮件记录在电子邮件表中,那么它将获得id并插入到customer表中。如果找不到电子邮件,则会将其插入电子邮件表,然后插入客户。
<?php
/* Default */
$terms = $_POST['terms'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
/* Database conections */
include 'config.php';
try
{
$conn = new PDO('mysql:host=localhost;dbname='.$config['dataBaseName'], $config['userName'], $config['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failded' . $e->getMessage();
}
/* Post data */
if (isset($_POST["firstName"]))
{
$firstName = trim(ucfirst($_POST["firstName"]));
}
if (isset($_POST["email"]))
{
$email = trim(ucfirst($_POST["email"]));
}
if (isset($_POST["postCode"]))
{
$postCode = trim(strtoupper($_POST["postCode"]));
}
if (isset($_POST["url"]))
{
$url = trim(ucfirst($_POST["url"]));
}
if (isset($_POST["terms"]))
{
$terms = trim(ucfirst($_POST["terms"]));
}
/* Check if email is in database returns array */
try
{
echo 'Finding Email ->' .$email;
$stmt = $conn->prepare("SELECT id,email FROM email WHERE email = :email");
$stmt->bindParam(':email',$email);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
echo 'Check if email is in table' . $e->getMessage();
}
/* Insert Logic + functions */
try
{
if(empty($result) or is_null($result))
{
/* Insert into email table */
$stmt = $conn->prepare("INSERT INTO email (`email`) values(:email)");
$stmt->bindParam(':email',$email);
$stmt->execute();
/* grab id from email table */
$stmt = $conn->prepare("SELECT id FROM email WHERE email = :email");
$stmt->bindParam(':email',$email);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $result["id"];
/* insert into customer table */
$stmt = $conn->prepare(
"INSERT INTO customer (`emailid`, `firstname`, `postcode`, `terms`, `browser`, `ipaddress`)
VALUES(:emailid, :firstname, :postcode, :terms, :browser, :ipaddress)");
$stmt->bindParam(':emailid',$result);
$stmt->bindParam(':firstname',$firstName);
$stmt->bindParam(':postcode',$postCode);
$stmt->bindParam(':terms',$terms);
$stmt->bindParam(':browser',$url);
$stmt->bindParam(':ipaddress',$ipAddress);
$stmt->execute();
}
else
{
/* grabs id from email table */
$stmt = $conn->prepare("SELECT id FROM email WHERE email = :email");
$stmt->bindParam(':email',$email);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $result["id"];
/* insert into customer table */
$stmt = $conn->prepare(
"INSERT INTO customer (`emailid`, `firstname`, `postcode`, `terms`, `browser`, `ipaddress`)
VALUES(:emailid, :firstname, :postcode, :terms, :browser, :ipaddress)");
$stmt->bindParam(':emailid',$result);
$stmt->bindParam(':firstname',$firstName);
$stmt->bindParam(':postcode',$postCode);
$stmt->bindParam(':terms',$terms);
$stmt->bindParam(':browser',$url);
$stmt->bindParam(':ipaddress',$ipAddress);
$stmt->execute();
}
$conn->commit();
}
catch (PDOException $e)
{
echo 'Insert error -->' . $e->getMessage();
}
?>