@robi_ds

В чем может быть проблема? Не работает скрипт, который проработал 2 дня?

проработал скрипт 2 суток, после последней проверки пошел пить чай на 3 часа, вернувшись обнаружил что не работает. Взбесился, создал новый сервер, настроил и залил заведомо рабочий код и нифига не работает все равно.. Может может кто подскажать или толкнуть в правильно русло. Сервер ubuntu 16.04, mysql, php7, вот код после которого ничего не происходит.
<spoiler title=""><?php 

	//getting the dboperation class
	require_once '../includes/DbOperation.php';

	//function validating all the paramters are available
	//we will pass the required parameters to this function 
	function isTheseParametersAvailable($params){
		//assuming all parameters are available 
		$available = true; 
		$missingparams = ""; 
		
		foreach($params as $param){
			if(!isset($_POST[$param]) || strlen($_POST[$param])<=0){
				$available = false; 
				$missingparams = $missingparams . ", " . $param; 
			}
		}
		
		//if parameters are missing 
		if(!$available){
			$response = array(); 
			$response['error'] = true; 
			$response['message'] = 'Parameters ' . substr($missingparams, 1, strlen($missingparams)) . ' missing';
			
			//displaying error
			echo json_encode($response);
			
			//stopping further execution
			die();
		}
	}
	
	//an array to display response
	$response = array();
	
	//if it is an api call 
	//that means a get parameter named api call is set in the URL 
	//and with this parameter we are concluding that it is an api call
	if(isset($_GET['apicall'])){
		
		switch($_GET['apicall']){
			
			//the CREATE operation
			//if the api call value is 'createhero'
			//we will create a record in the database
			case 'createhero':
				//first check the parameters required for this request are available or not 
				isTheseParametersAvailable(array('name','realname','rating','teamaffiliation'));
				
				//creating a new dboperation object
				$db = new DbOperation();
				
				//creating a new record in the database
				$result = $db->createHero(
					$_POST['name'],
					$_POST['realname'],
					$_POST['rating'],
					$_POST['teamaffiliation']
				);
				

				//if the record is created adding success to response
				if($result){
					//record is created means there is no error
					$response['error'] = false; 

					//in message we have a success message
					$response['message'] = 'Hero addedd successfully';

					//and we are getting all the heroes from the database in the response
					$response['heroes'] = $db->getHeroes();
				}else{

					//if record is not added that means there is an error 
					$response['error'] = true; 

					//and we have the error message
					$response['message'] = 'Some error occurred please try again';
				}
				
			break; 
			
			//the READ operation
			//if the call is getheroes
			case 'getheroes':
				$db = new DbOperation();
				$response['error'] = false; 
				$response['message'] = 'Request successfully completed';
				$response['heroes'] = $db->getHeroes();
			break; 
			
			
			//the UPDATE operation
			case 'updatehero':
				isTheseParametersAvailable(array('id','name','realname','rating','teamaffiliation'));
				$db = new DbOperation();
				$result = $db->updateHero(
					$_POST['id'],
					$_POST['name'],
					$_POST['realname'],
					$_POST['rating'],
					$_POST['teamaffiliation']
				);
				
				if($result){
					$response['error'] = false; 
					$response['message'] = 'Hero updated successfully';
					$response['heroes'] = $db->getHeroes();
				}else{
					$response['error'] = true; 
					$response['message'] = 'Some error occurred please try again';
				}
			break; 
			
			//the delete operation
			case 'deletehero':

				//for the delete operation we are getting a GET parameter from the url having the id of the record to be deleted
				if(isset($_GET['id'])){
					$db = new DbOperation();
					if($db->deleteHero($_GET['id'])){
						$response['error'] = false; 
						$response['message'] = 'Hero deleted successfully';
						$response['heroes'] = $db->getHeroes();
					}else{
						$response['error'] = true; 
						$response['message'] = 'Some error occurred please try again';
					}
				}else{
					$response['error'] = true; 
					$response['message'] = 'Nothing to delete, provide an id please';
				}
			break; 
		}
		
	}else{
		//if it is not api call 
		//pushing appropriate values to response array 
		$response['error'] = true; 
		$response['message'] = 'Invalid API Call';
	}
	
	//displaying the response in json structure 
	echo json_encode($response);


В ответ получаю 5ad3da3f2e813351571026.png
  • Вопрос задан
  • 205 просмотров
Решения вопроса 1
Hocopor
@Hocopor
Ищу интересную работу
Все дело в том что вы передаете в apicall название функции но ловите уже не ее.

createhero != createHero

Что-бы это отловить добавьте в конструкцию switch:
default:
    $response = 'undefined api';
break;


P.S.: Предыдущий ответ намекает вам на то что у вас ошибка в логике функции.
Если у вас будет задана 1 переменная вместо 6, но последняя, то скрипт не увидит ошибки, потому как available будет равен true
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Exploding
@Exploding
wtf?
Может как-то так? Код не проверял, поэтому если вдруг что - поправите там уже...
function isTheseParametersAvailable($params){
	//assuming all parameters are available 
	$missingparams = array();
	
	foreach($params as $param){
		if(!isset($_POST[$param]) || !strlen($_POST[$param]))
			$missingparams[] = $param; 
	}
	
	if(count($missingparams)){
		$response['error'] = true; 
		$response['message'] = 'Parameters ' . implode(", ", $missingparams) . ' missing';
		exit(json_encode($response));
	}
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы