I have the following error when I go to view.php: {"success":0,"message":"SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected"}, can someone help to solve this issue?
My code is this:
db_connect.php
<?php
class Operations{
private $db_host = "localhost";
private $db_name = "supplierInquiry";
public function dbConnection()
{
try {
$conn = new PDO('mysql:host=' . $this->db_host . ';dbName=' . $this->db_name);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo "Connection error " . $e->getMessage();
exit;
}
}
}
?>
in the view.php the code is:
<?php
error_reporting(E_ERROR);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Content-Type: application/json; charset=UTF-8");
if ($_SERVER['REQUEST_METHOD'] !== 'GET') :
http_response_code(405);
echo json_encode([
'success'=>0,
'message'=>'Bad Request Detected! Only get method is allowed',
]);
exit;
endif;
require 'db_connect.php';
$database = new Operations();
$conn = $database->dbConnection();
if (isset($_GET['id'])) {
$suppliers_id = filter_var($_GET['id'], FILTER_VALIDATE_INT, [
'options' => [
'default' => 'all_suppliers',
'min_range' => 1
]
]);
}
try {
$sql = is_numeric($suppliers_id) ? "SELECT * FROM `supplier` WHERE id='$suppliers_id'" : "SELECT * FROM `supplier`";
$stmt = $conn->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) :
$data = null;
if (is_numeric($suppliers_id)) {
$data = $stmt->fetch(PDO::FETCH_ASSOC);
} else {
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode([
'success' => 1,
'data' => $data,
]);
else :
echo json_encode([
'success' => 0,
'message' => 'No Record Found!',
]);
endif;
}
// The error is from this catch
catch (PDOException $e) {
http_response_code(500);
echo json_encode([
'success' => 0,
'message' => $e->getMessage()
]);
exit;
}
?>
This is the video tutorial from where I'm learning https://www.youtube.com/watch?v=5huuXugiVNU.
CodePudding user response:
The MySQL DSN you are using has a typo: it should be dbname
and not dbName
Tested in https://extendsclass.com/php-bin/8c2096d