我一直在慢慢学习PHP OOP,我认为是时候开始向表中插入了,但是似乎没有在插入。我将代码与工作版本进行了比较,但我看不出问题出在哪里,我尝试了var_dump(),查询按预期返回,我通过创建一个新用户来测试数据库类,它已成功创建,所以我假设不是那样,我测试了SQL查询并且能够插入,因为现在可能是我茫然了
表格
<?php
session_start();
require ("classes/Review.php");
require ("classes/Database.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$reviewing = new ReviewValidation();
$review = $reviewTitle = "";
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$reviewTitle = $post['reviewTitle'];
$review = $post['review'];
$errors = array();
$fields = array(
'title' => array(
'validate' => 'title',
'message' => 'Title must be at least fife characters',
'value' => $reviewTitle,
),
'review' => array(
'validate' => 'review',
'message' => 'Your review must be at least three hundred characters',
'value' => $review,
)
);
foreach($fields as $key => $value)
{
$validation_result = $reviewing->{$value['validate']}($value['value']);
if(!$validation_result)
{
$errors[] = ['name' => $key, 'error' => $value['message']];
}
}
if(empty($errors))
{
try
{
$db = new Database;
$success = ["message" => "Review subbbmitted"];
$process = $db->prepare('INSERT INTO reviews (reviewTitle)
VALUES
(:reviewTitle');
$process->bindValue(':reviewTitle', $reviewTitle);
$process->execute();
}
catch(Exception $e)
{
$errors[] = ['response' => 'fail'];
}
}
}
header('Content-Type: application/json');
if (empty($errors))
{
echo json_encode($success);
}
else
{
echo json_encode(["errors" => $errors]);
}
班
<?php
class ReviewValidation
{
private
$db,
$review,
$reviewTitle;
private static
$reviewLength = 50,
$rewviewtitleLength = 5;
public static function title($reviewTitle)
{
return(strlen($reviewTitle) >= self::$rewviewtitleLength);
}
public static function review($review)
{
return(strlen($review) >= self::$reviewLength);
}
}
答案 0 :(得分:2)
看起来您可能在插入查询中缺少):
$process = $db->prepare('INSERT INTO reviews (reviewTitle)
VALUES
(:reviewTitle)');
如果在:reviewTitle之后添加右括号,则单引号之前的语法将是正确的(如上所示)。
我还注意到,您对ReviewValidation类中的静态方法的调用使用的是对象运算符(->)。要访问静态方法,您需要使用scope resolution operator。
因此,您的$ validation_result行应如下所示:
$validation_result = ReviewValidation::{$value['validate']}($value['value']);
我认为正因为如此,验证可能已经通过,这就是为什么您遇到无默认值问题的原因。