我一直在尝试匹配Laravel项目中来自数据库的数据,但始终会向我发出警报:未定义偏移量:0 。我已经检查了该网站上的其他帖子,但是可能会出现这种情况。
奇怪的是,如果我不执行匹配过程,则程序可以正常运行,反之亦然。只是不确定我的代码有什么问题。
这是控制器。
func setGradientBackground(Colors: [UIColor]) {
var updatedFrame = bounds
updatedFrame.size.height += self.frame.origin.y
if UIDevice().userInterfaceIdiom == .phone {
if UIScreen.main.nativeBounds.height == 2436{
updatedFrame.size.height += 44
} else {
updatedFrame.size.height += 20
}
}
let gradientLayer = CAGradientLayer(frame: updatedFrame, colors: Colors)
setBackgroundImage(gradientLayer.createGradientImage(), for: UIBarMetrics.default)
}
这是错误消息:
public function addProductAction(Request $request) {
/*
check if any input is empty, if validation is fail, error message will display.
Get required information from addProduct view. And then pass then in the $sql variables.
DB class will map then to get result.
*/
$this->validate($request,[
"product_name" => "required | max:20",
"description" => "required | max:255",
"date_of_release" => "required",
"id" => "required"
]);
$product_name = request("product_name");
// dd($product_name);
$description = request("description");
$manufacturer_id = request("id");
$date_of_release = request("date_of_release");
$sql = "SELECT product_name FROM PRODUCT where product_name = ?";
$existingProducts = DB::select($sql, array($product_name));
$existingProduct = $existingProducts[0] -> product_name;
//dd($existingProduct);
if ($product_name == $existingProduct) {
echo "product exists";
} else {
$sql = "insert into product (product_name, description, date_of_release) values (?, ?, ?)";
DB::insert($sql, array($product_name, $description, $date_of_release));
$id = DB::getPdo()->lastInsertId();
//dd($id);
$sql = "insert into PRODUCT_ORIGINAL (product_id, manufacturer_id ) values (?, ?)";
DB::insert($sql, array($id, $manufacturer_id));
// dd($newProduct);
return redirect("product-detail/$id");
}
return redirect('/');
}
答案 0 :(得分:1)
如您在错误日志中所见:
在HandleExceptions-> handleError(8,'Undefined offset:0', ....'existingProducts'=> array()))
您的existingProducts
数组为空。
因此,您可以尝试在行中访问索引0:
$existingProduct = $existingProducts[0] -> product_name;
您可以使用以下方法解决它:
$existingProducts = DB::select($sql, array($product_name));
if (!empty(existingProducts ) && $product_name == $existingProducts[0]->product_name) {
echo "product exists";
} else {