[英]PHP Inserting into mysql issue
运行以下命令时遇到麻烦:
$stmt = $this->db->prepare("INSERT INTO checked_in (attendee_id) VALUES (?)");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
这是更大页面的一部分,但是这是行不通的。 我首先从SQL数据库中提取$ id,所以我知道已经建立了连接。 我似乎无法使此更新部分正常工作。
mysql > CREATE TABLE checked_in (
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
attendee_id int NOT NULL,
check_in_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
这是我用来构建表的代码。 难道我做错了什么? 我认为我的问题是它可以与数据库对话,但是我不知道我在期望手动输入ID和时间戳的地方是否设置了错误的表。 如果我在sql提示符下并使用此命令,它将起作用
mysql> INSERT INTO checked_in (attendee_id) VALUES (1);
这是程序的主要部分(在使教程适应我自己的过程中):
function checkIn() {
// Check for required parameters
if (isset($_POST["phone"])) {
// Put parameters into local variables
$phone = $_POST['phone'];
// Look up code in database
$user_id = 0;
$stmt = $this->db->prepare('SELECT id, first, last, email FROM attendees WHERE phone=?');
$stmt->bind_param("s", $phone);
$stmt->execute();
$stmt->bind_result($id, $first, $last, $email);
while ($stmt->fetch()) {
break;
}
$stmt->close();
// Bail if number doesn't exist
if ($id <= 0) {
sendResponse(400, 'Invalid number');
return false;
}
// Check to see if this device already redeemed
$stmt = $this->db->prepare('SELECT id FROM checked_in WHERE attendee_id=?');
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($checkedInID);
while ($stmt->fetch()) {
break;
}
$stmt->close();
// Bail if number already checked in
if ($checkedInID > 0) {
sendResponse(403, 'Number already checked in');
return false;
}
// Add tracking of redemption
$stmt = $this->db->prepare("INSERT INTO checked_in (attendee_id) VALUES (?)");
$stmt->bind_param("i", $id);
$stmt->execute();
// Return unlock code, encoded with JSON
$result = array(
"checked_in" => "true",
);
sendResponse(200, json_encode($result));
return true;
}
sendResponse(400, 'Invalid request');
return false;
}
}
好的,所以我检查了我的apache错误日志,这就是它的意思:
[Fri Jul 25 15:06:41.996107 2014] [:error] [pid 16824] [client 127.0.0.1:52699] PHP Notice: Undefined variable: db in /var/www/html/index.php on line 129
[Fri Jul 25 15:06:41.996171 2014] [:error] [pid 16824] [client 127.0.0.1:52699] PHP Fatal error: Call to a member function prepare() on a non-object in /var/www/html/index.php on line 129
如果在查询中使用问号时绑定了参数,则不应使用i
作为参数。 请改用数字参数。
尝试
$stmt->bind_param(1, $id);
从他们手册 :
对于使用命名占位符的准备好的语句,这将是形式为
:name
的参数:name
。 对于使用问号占位符的准备好的语句,这将是参数的1索引位置。
也就是说,请描述在此函数中分配的$id
。
尝试这个:
$stmt = $this->db->prepare("INSERT INTO checked_in (attendee_id) VALUES (?)");
$stmt->execute( array( $id ) );
应该管用。
如果要检查错误,则应该执行以下操作:
$stmt = $this->db->prepare("INSERT INTO checked_in (attendee_id) VALUES (?)");
$check = $stmt->execute( array( $id ) );
if ( $check ) {
echo 'Nice work!';
} else {
$error = $stmt->errorInfo();
echo $error[2];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.