我有以下PHP代码:
<?php
$email = 'email@email.com';
$phone = '+1 800 555 555';
//clean up phone number
$phone = preg_replace("/[^0-9]/", '', $phone);
$plan = 'europe';
$ip = '99.55.44.44';
$sendEmails = True;
function addInfoToDatabase($token) {
//function that adds data to temporary table. token is passed through
//put new user info in database
$mysqli = new mysqli('localhost', 'php', '', 'php');
$stmt = $mysqli->prepare("INSERT INTO `temp_users` VALUES (?, ?, ?, ?, ?, ?, '')");
$stmt->bind_param('ssssss', $email, $phone, $plan, $sendEmails, $token, $ip);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
addInfoToDatabase('24_tok');
?>
并且运行时不会返回错误。但是,当我检查我的数据库时,尚未添加一行。我的代码看起来是正确的,为什么这个函数什么都不做?
编辑:D'哦,我想我的问题在于没有将变量传递给函数。这非常有效。
<?php
$email = 'email@email.com';
$phone = '+1 800 555 555';
//clean up phone number
$phone = preg_replace("/[^0-9]/", '', $phone);
$plan = 'europe';
$ip = '99.55.44.44';
$sendEmails = True;
function addInfoToDatabase($email, $phone, $plan, $sendEmails, $token, $ip) {
//function that adds data to temporary table. token is passed through
//put new user info in database
$mysqli = new mysqli('localhost', 'php', '', 'php');
$stmt = $mysqli->prepare("INSERT INTO `temp_users` VALUES (?, ?, ?, ?, ?, ?, '')");
$stmt->bind_param('ssssss', $email, $phone, $plan, $sendEmails, $token, $ip);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
addInfoToDatabase($email, $phone, $plan, $sendEmails, '24_tok', $ip);
?>
答案 0 :(得分:1)
您正在尝试在函数中使用变量$email
,$phone
,$plan
,$sendEmails
和$ip
,但它们仅在外部设置功能。这意味着它们是全局变量,因此只有在将它们作为参数传递给函数时才能访问它们。
不这样做的结果是您将null
值传递给数据库。如果使用NOT NULL
(并且它们可能是)定义了任何相关列,则查询将失败。您可以通过运行此代码来验证失败的原因:
echo 'error '.$mysqli->errno().': '.$mysqli->error().'<br/>';