Требуется добавить продукт в базу данных MySql (удаленно)
по ионному приложению Существует страница продукта. При нажатии кнопки submit метод post вызывается со страницы ionicApp «Product.ts» функцией createEntry ().
Запись была успешно создана, если нет ошибки ограничения с помощью файла PHP с именем manage_products.php.
В ионном приложении if (data.status === 200) имеет значение true, тогда выполняется тело. Но нет никакого способа, если запись была создана или нет. если есть какая-то проблема, например, какое-то нулевое ограничение (сторона Db), то только через вкладку Chrome Network я узнаю о некоторой ошибке ограничения. Есть ли способ получить текст ошибки из файла PHP в ионном приложении.
Вот функция createEntry, вызываемая из ionicApp «Product.ts»
createEntry()
{
let id = "0000";
let name = "Some Product";
let description = "Some Product description";
let manufacturer_name = "manufacturer_name";
let weight = "some weight is here";
let weight_unit = "kg";
let halal_status = "HALAL";
let body : string = "key=create&id=" + id + "&name=" + name + "&description=" + description + "&manufacturer_name=" + manufacturer_name + "&weight=" + weight + "&weight_unit=" + weight_unit + "&halal_status=" + halal_status ,
type : string = "application/x-www-form-urlencoded; charset=UTF-8",
headers : any = new Headers({ 'Content-Type': type}),
options : any = new RequestOptions({ headers: headers }),
url : any = this.baseURI + "manage_products.php";
this.http.post(url, body, options)
.subscribe((data) =>
{
// If the request was successful notify the user
if(data.status === 200)
{
// this.hideForm = true;
console.log(`Congratulations the technology: ${name} was successfully added`);
console.log('successfully added the record. .......');
}
// Otherwise let 'em know anyway
else
{
// this.sendNotification('Something went wrong!');
console.log('Couldnt add the record.....xxx');
}});
}
Приведенный выше код вызывает файл php. Вот код для файла php.
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'username';
$pwd = 'password';
$db = 'name-of-database';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$key = strip_tags($_REQUEST['key']);
$data = array();// Determine which mode is being requested
switch($key)
{
// Add a new record to the technologies table
case "create":
// Sanitise URL supplied values
$id = filter_var($_REQUEST['id'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$manufacturer_name = filter_var($_REQUEST['manufacturer_name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight = filter_var($_REQUEST['weight'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight_unit = filter_var($_REQUEST['weight_unit'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$halal_status = filter_var($_REQUEST['halal_status'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$description = filter_var($_REQUEST['description'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);// Attempt to run PDO prepared statement
try {
$sql = "INSERT INTO Products(id,name,manufacturer_name,weight,weight_unit,halal_status,description) VALUES(:id, :name, :manufacturer_name, :weight, :weight_unit, :halal_status, :description)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':manufacturer_name', $manufacturer_name, PDO::PARAM_STR);
$stmt->bindParam(':weight', $weight, PDO::PARAM_STR);
$stmt->bindParam(':weight_unit', $weight_unit, PDO::PARAM_STR);
$stmt->bindParam(':halal_status', $halal_status, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record ' . $name . ' was added to the database'));
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;// Update an existing record in the technologies table
case "update":
// Sanitise URL supplied values
/*
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$description = filter_var($_REQUEST['description'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$recordID = filter_var($_REQUEST['recordID'], FILTER_SANITIZE_NUMBER_INT);
*/
$id = filter_var($_REQUEST['id'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$manufacturer_name = filter_var($_REQUEST['manufacturer_name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight = filter_var($_REQUEST['weight'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight_unit = filter_var($_REQUEST['weight_unit'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$halal_status = filter_var($_REQUEST['halal_status'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
// Attempt to run PDO prepared statement
try {
$sql = "UPDATE Products SET id = :id, name = :name,manufacturer_name = :manufacturer_name,weight = :weight,weight_unit = :weight_unit,halal_status = : halal_status, description = :description WHERE id = :id";
$stmt = $pdo->prepare($sql);
/*
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->bindParam(':id', $recordID, PDO::PARAM_INT);
*/
$stmt->bindParam(':id', $name, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':manufacturer_name', $description, PDO::PARAM_STR);
$stmt->bindParam(':weight', $name, PDO::PARAM_STR);
$stmt->bindParam(':weight_unit', $name, PDO::PARAM_STR);
$stmt->bindParam(':halal_status', $description, PDO::PARAM_STR);
$stmt->bindParam(':description', $name, PDO::PARAM_STR);
$stmt->execute();
echo json_encode('Congratulations the record ' . $name . ' was updated');
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;// Remove an existing record in the technologies table
case "delete":
// Sanitise supplied record ID for matching to table record
$recordID = filter_var($_REQUEST['id'], FILTER_SANITIZE_NUMBER_INT);
// Attempt to run PDO prepared statement
try {
$pdo = new PDO($dsn, $un, $pwd);
$sql = "DELETE FROM Products WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $recordID, PDO::PARAM_INT);
$stmt->execute();
echo json_encode('Congratulations the record ' . $name . ' was removed');
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
}
?>
Вы можете использовать alertcontroller или toastcontroller и отображать сообщение об ошибке, добавляя перехват после того, как вы подписались на данные … вот так
catch((err)=>{
this.AlertMessage("error", err);
});
Других решений пока нет …