Php 为什么下面函数中的数组执行会引发异常?
我正在开发一个ussd投票应用程序,除了将投票保存到数据库和更新表格之外,我什么都做对了 处理save_投票的函数如下所示Php 为什么下面函数中的数组执行会引发异常?,php,sql,sqlite,Php,Sql,Sqlite,我正在开发一个ussd投票应用程序,除了将投票保存到数据库和更新表格之外,我什么都做对了 处理save_投票的函数如下所示 function save_vote($phone_number, $voted_for) { // Just the digits, please $phone_number = preg_replace('/\D/', '', $phone_number); // Check to see if person has a
function save_vote($phone_number, $voted_for) {
// Just the digits, please
$phone_number = preg_replace('/\D/', '', $phone_number);
// Check to see if person has already voted
$stmt = $this->db->prepare('SELECT COUNT(*) FROM voters WHERE phone_number=?');
$stmt->execute(array($phone_number));
// If not, save their vote
if ($stmt->fetchColumn() == 0)
{
// Save voter
$stmt = $this->db->prepare('INSERT INTO voters (phone_number, voted_for) VALUES (?, ?)');
$stmt->execute(array($phone_number, $voted_for));
// Update vote count
$stmt = $this->db->prepare('UPDATE brands SET votes = votes + 1 WHERE id=?');
$stmt->execute(array($voted_for));
return 'Thank you, your vote has been recorded';
}
else {
return 'Sorry, you can only vote once.';
}
}
传递到函数中的值是DB->save_vote'02778995805',2
服务器日志抛出一个异常,如下所示
1{main}
2019-02-28813:50:49.813224+00:00应用程序[web.1]:在第57行输入/app/db.php
第57行代码为$stmt->executearray$phone\u number;在
如果您能帮助解释可能出现的问题,我们将不胜感激
谢谢
根据评论的要求,请参见下文
db.php代码:
<?php
/**
* Created by PhpStorm.
* User: kqwameselase
* Date: 2019-02-27
* Time: 22:53
*/
class DB {
const DB_NAME = 'votes.sqlite';
protected $db;
function __construct() {
$this->db = new PDO('sqlite:'.self::DB_NAME);
}
function init() {
// Create two tables, one to store the brands being voted on and their vote counts (brands) and one to store the people that have voted (voters).
$this->db->exec('CREATE TABLE IF NOT EXISTS brands (id INTEGER PRIMARY KEY, name TEXT, votes INTEGER);');
$this->db->exec('CREATE TABLE IF NOT EXISTS voters (id INTEGER PRIMARY KEY, phone_number TEXT, voted_for INTEGER);');
}
function add_brand($name) {
// Check to make sure the brand name doesn't already exist
$stmt = $this->db->prepare('SELECT COUNT(*) FROM brands WHERE name=?');
$stmt->execute(array($name));
// If not, insert it
if ($stmt->fetchColumn() == 0)
{
$stmt = $this->db->prepare('INSERT INTO brands (name, votes) VALUES (?, 0)');
$stmt->execute(array($name));
}
}
function get_brands() {
$result = $this->db->query('SELECT * FROM brands');
foreach ($result as $row)
{
$brand['id'] = $row['id'];
$brand['name'] = $row['name'];
$brand['votes'] = $row['votes'];
$brands[] = $brand;
}
return $brands;
}
/**
* @param $phone_number
* @param $voted_for
* @return string
*/
function save_vote($phone_number, $voted_for) {
// Just the digits, please
$phone_number = intval(preg_replace('/\D/', '', $phone_number));
// Check to see if person has already voted
$stmt = $this->db->prepare('SELECT COUNT(*) FROM voters WHERE phone_number=?');
$stmt->bindParam(1, $phone_number, PDO::PARAM_INT);
$stmt->execute();
// If not, save their vote
if ($stmt->fetchColumn() == 0)
{
// Save voter
$stmt = $this->db->prepare('INSERT INTO voters (phone_number, voted_for) VALUES (?, ?)');
$stmt->bindParam(1, $phone_number, PDO::PARAM_INT);
$stmt->bindParam(2, $voted_for, PDO::PARAM_INT);
$stmt->execute();
// Update vote count
$stmt = $this->db->prepare('UPDATE brands SET votes = votes + 1 WHERE id=?');
$stmt->bindParam(1,$voted_for, PDO::PARAM_INT);
$stmt->execute();
return 'Thank you, your vote has been recorded';
}
else {
return 'Sorry, you can only vote once.';
}
}
/* function save_vote($phone_number, $voted_for) {
// Just the digits, please
$phone_number = intval(preg_replace('/\D/', '', $phone_number));
// Check to see if person has already voted
$stmt = $this->db->prepare('SELECT COUNT(*) FROM voters WHERE phone_number=?');
$stmt->bindParam('i', $phone_number);
$stmt->execute();
// If not, save their vote
if ($stmt->fetchColumn() == 0)
{
// Save voter
$stmt = $this->db->prepare('INSERT INTO voters (phone_number, voted_for) VALUES (?, ?)');
$stmt->bindParam('ii', $phone_number, $voted_for); // we suppose tha rhe $voted_for is integer if not use intval
$stmt->execute();
// Update vote count
$stmt = $this->db->prepare('UPDATE brands SET votes = votes + 1 WHERE id=?');
$stmt->bindParam('i',$voted_for);// we suppose tha rhe $voted_for is integer if not use intval
$stmt->execute();
return 'Thank you, your vote has been recorded';
}
else {
return 'Sorry, you can only vote once.';
}
}*/
/* function save_vote($phone_number, $voted_for) {
// Just the digits, please
$phone_number = preg_replace('/\D/', '', $phone_number);
// Check to see if person has already voted
$stmt = $this->db->prepare('SELECT COUNT(*) FROM voters WHERE phone_number=?');
$stmt->bind_param(int, $phone_number);
$stmt->execute();
//$stmt->execute(array($phone_number));
// If not, save their vote
if ($stmt->fetchColumn() == 0)
{
// Save voter
$stmt = $this->db->prepare('INSERT INTO voters (phone_number, voted_for) VALUES (?, ?)');
$stmt->execute(array($phone_number, $voted_for));
// Update vote count
$stmt = $this->db->prepare('UPDATE brands SET votes = votes + 1 WHERE id=?');
$stmt->execute(array($voted_for));
return 'Thank you, your vote has been recorded';
}
else {
return 'Sorry, you can only vote once.';
}
}*/
}
下面是用户与系统交互的vote-now.php代码
<?php
/**
* Created by PhpStorm.
* User: kqwameselase
* Date: 2019-02-27
* Time: 10:29
*/
date_default_timezone_set('Africa/Ghana');
require_once('db.php');
header('Content-type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: http://apps.smsgh.com");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
// Begin by reading the HTTP request body contents.
// Since we expect is to be in JSON format, let's parse as well.
$ussdRequest = json_decode(@file_get_contents('php://input'));
// Our response object. We shall use PHP's json_encode function
// to convert the various properties (we'll set later) into JSON.
$ussdResponse = new stdClass;
// Check if no errors occured.
if ($ussdRequest != NULL)
switch ($ussdRequest->Type) {
// Initiation request. This is the first type of request every
// USSD application will receive. So let's display our main menu.
case 'Initiation':
$ussdResponse->Message =
"Welcome to Ghana Beverage Awards 2019. Vote for your preferred product of the year.\n" .
"1. Origin Beer \n2. Club Beer \n3. Star Beer \n4. Guinness \n5. Gulder";
$ussdResponse->Type = 'Response';
break;
// Response request. This is where all other interactions occur.
// Every time the mobile subscriber responds to any of our vote options,
// this will be the type of request we shall receive.
case 'Response':
switch ($ussdRequest->Sequence) {
// Menu selection. Note that everytime we receive a request
// in a particular session, the Sequence will increase by 1.
// Sequence number 1 was that of the initiation request.
case 2:
$items = array('1' => 'Origin Beer', '2' => 'Club Beer', '3' => 'Star Beer', '4' => 'Guinness', '5' => 'Gulder');
if (isset($items[$ussdRequest->Message])) {
$ussdResponse->Message = 'Please confirm your preferred product of the year is '
. $items[$ussdRequest->Message] . "?\n1. Yes\n2. No";
$ussdResponse->Type = 'Response';
$ussdResponse->ClientState = $items[$ussdRequest->Message];
} else {
$ussdResponse->Message = 'Invalid option.';
$ussdResponse->Type = 'Release';
}
break;
// Order confirmation. Here the user has responded to our
// previously sent menu (i.e. Please confirm your preferred product of the year is...)
// Note that we saved the option the user selected in our
// previous dialog into the ClientState property.
case 3:
switch ($ussdRequest->Message) {
case '1':
$db = new DB();
// save_vote will check to see if the person has already voted
$phone_number = $ussdRequest->Mobile;
//Return the array number for the selected vote to be used when updated votes
$items2 = array('1' => 'Origin Beer', '2' => 'Club Beer', '3' => 'Star Beer', '4' => 'Guinness', '5' => 'Gulder');
$voted_for = array_search($ussdRequest->ClientState, $items2) ;
$response = $db->save_vote($phone_number, $voted_for);
//echo $response;
//Display Success message after vote saved.
$ussdResponse->Message =
'Thank you. You have successfully voted for '
. $ussdRequest->ClientState . ' as your preferred Product of the Year.';
break;
case '2':
$ussdResponse->Message = 'Vote cancelled.';
break;
default:
$ussdResponse->Message = 'Invalid selection.';
break;
}
$ussdResponse->Type = "Release";
break;
// Unexpected request. If the code here should ever
// execute, it means the request is probably forged.
default:
$ussdResponse->Message = 'Unexpected request.';
$ussdResponse->Type = 'Release';
break;
}
break;
// Session cleanup.
// Not much to do here.
default:
$ussdResponse->Message = 'Duh.';
$ussdResponse->Type = 'Release';
break;
}
// An error has occured.
// Probably the request JSON could not be parsed.
else {
$ussdResponse->Message = 'Invalid USSD request.';
$ussdResponse->Type = 'Release';
}
// Let's set the HTTP content-type of our response, encode our
// USSD response object into JSON, and flush the output.
header('Content-type: application/json; charset=utf-8');
echo json_encode($ussdResponse);
每个heroku日志的完整错误:
2019-02-28816:31:19.510613+00:00应用程序[web.1]:[28-Feb-2019 16:31:19
UTC]PHP致命错误:未捕获错误:调用成员函数
bool上的bindpram in/app/db.php:62 2019-02-28T16:31:19.510703+00:00
应用程序[web.1]:堆栈跟踪:2019-02-28T16:31:19.510862+00:00应用程序[web.1]:
0/app/vote-now.php77:DB->save_vote2776558052019-02-28161:31:19.510947+00:00 app[web.1]:1{main}
2019-02-28816:31:19.511072+00:00应用程序[web.1]:输入/app/db.php
在线62 2019-02-28T16:31:19.512333+00:00应用程序[网站1]:10.45.101.19-
-[28/Feb/2019:16:31:19+0000]POST/vote-now.php HTTP/1.1500-Mozilla/5.0 Macintosh;英特尔
Mac OS X 10_14_3 AppleWebKit/537.36 KHTML,如Gecko
Chrome/72.0.3626.109 Safari/537.36
准备好的语句无法接受execute函数中的数组。您需要绑定每个参数,例如,将s替换为所需的数据类型,即string、int等:
$stmt = $this->db->prepare('SELECT COUNT(*) FROM voters WHERE phone_number=?');
$stmt->bind_param("s", $phone_number);
$stmt->execute();
我认为您没有使用所需的类型->我使用的是您输入的更新代码: 我看到两个问题: 电话号码是字符串而不是整数。 您希望$ussdRequest->Mobile为int,但它会给出一个字符串。 如果您正在将电话号码另存为号码,我建议切换为字符。。。 但是为了确保我们需要您的表结构+$ussdRequest类,以便进一步检查 尝试使用以下方法: 这个。和intval只是为了确保您传递的是正确的类型,如果有效的话,请重新考虑您的类型并检查转换发生的位置
希望我能帮忙 这就是所有的错误显示吗?你能显示所有的错误日志吗?或者显示app/db.php的代码你使用的是哪种数据库抽象层?$stmt->是否执行接受数组?多了解一些上下文可能会有所帮助。在执行查询之前,还要检查$phone_号码包含哪些内容。如果他使用PDO作为抽象层,会是什么?execute方法接受PDO抽象中的数组。此外,如果他使用int或bigint数据类型作为电话号码,他将不得不在bind_param中使用i。我编辑了我的代码,如下所示,并想知道它是否正确?//检查此人是否已经投票$stmt=$this->db->prepare'SELECT COUNT*FROM voctors WHERE phone_number=?'$stmt->bind_参数,$phone_号码$stmt->execute;它应该是$stmt->bind_param'i',$phone_number;正如@Wolverine所说的。@Selase你在使用PDO吗?是的,请@Wolverine。您可以建议一个最有效的替代方案,并教我如何实现它,以防PDO被证明是顽固的。
$stmt = $this->db->prepare('SELECT COUNT(*) FROM voters WHERE phone_number=?');
$stmt->bind_param("s", $phone_number);
$stmt->execute();
$stmt2query->bindParam(1, $phone_number.'';, PDO::PARAM_STR);
$stmt2query->bindParam(2, intval($voted_for), PDO::PARAM_INT);