Zend framework $db->update result - php

Zend_Db_Adapter::update() returns the number of rows affected by the update operation.
What is best way to determine if the query was successful?
$data = array(
'updated_on' => '2007-03-23',
'bug_status' => 'FIXED'
);
$n = $db->update('bugs', $data, 'bug_id = 2');

$data = array(
'updated_on' => '2007-03-23',
'bug_status' => 'FIXED',
);
$n = 0;
try {
$n = $db->update('bugs', $data, 'bug_id = 2');
} catch (Zend_Exception $e) {
die('Something went wrong: ' . $e->getMessage());
}
if (empty($n)) {
die('Zero rows affected');
}

If you are just looking for a boolean return value, this solution is the best for handling success in the model:
class Default_Model_Test extends Zend_Db_Table {
public function updateTest($testId, $testData){
try {
$this->_db->update('test', $testData, array(
'id = ?' => $testId
));
return true;
}
catch (Exception $exception){
return false;
}
}
}
But, a better solution would be to handling success from the controller level, because it is making the request:
class Default_Model_Test extends Zend_Db_Table {
public function updateTest($testId, $testData){
$this->_db->update('test', $testData, array(
'id = ?' => $testId
));
}
}
class Default_TestController extends Zend_Controller_Action {
public function updateAction(){
try {
$testId = $this->_request->getParam('testId');
if (empty($testId)) throw new Zend_Argument_Exception('testId is empty');
$testData = $this->_request->getPost();
if (empty($testId)) throw new Zend_Argument_Exception('testData is empty');
$testModel->updateTest($testId, $testData);
}
catch (Exception $exception){
switch (get_class($exception)){
case 'Zend_Argument_Exception': $message = 'Argument error.'; break;
case 'Zend_Db_Statement_Exception': $message = 'Database error.'; break;
case default: $message = 'Unknown error.'; break;
}
}
}
}
This is an excellent solution when working with multiple resource types, using a switch on the exception type, and doing what is appropriate based on your program's needs. Nothing can escape this vacuum.

Maybe:
$data = array(
'updated_on' => '2007-03-23',
'bug_status' => 'FIXED'
);
$result = $db->update('bugs', $data, 'bug_id = 2');
if ($result < $numRows) {//pass in numRows as method arg or hardcode integer.
//handle error
} else {
return TRUE;
}
Try something like this with the idea being you want to verify that the number of records you wanted updated got updated.

Related

php redis insert a data at a same time with few queues error

There are 3 queues in redis.
If I insert a data at a same time with different browsers, both requests are accepted.
I get 2 duplicated records. Any helps?
For example, the first request is on the 1st queue.
At the second request, 2nd queue is searched for finding the data.
But the data doesn't exist in the queue.
The second request is inserted on the queue.
Is it understandable?
public function save($evt_no, $type = "redis") {
$name = '';
$res = true;
try{
$headers = getallheaders();
$bodys = $_REQUEST;
$session = $_SESSION;
foreach ($_FILES as $fileKey=>$fileVal) {
if ($fileVal['error'] == 0) {
try {
$uploaded_row = $this->fileL->upload('queueEventParticipant', $fileKey, array() ,'queue');
} catch (\Exception $ex) {
throw $ex;
}
$bodys['file'][_return_numeric($fileKey)] = $uploaded_row;
}
}
$data = array(
'header' => $headers,
'body' => $bodys,
'session' => $session
);
$data['body']['evt_no'] = $evt_no;
$data = json_encode($data);
if($type == "redis"){
$name = $this->attendQueueRedisService->setNewRsvp($data);
} else {
throw new \Exception("No exist");
}
} catch (\Exception $ex){
log_message("error", $ex->getMessage());
throw $ex;
}
if($res){
return $name;
} else {
return "Error";
}
}
class AttendQueueRedisService extends CI_Model {
private $redisClient;
private $redisConfig;
const PREFIX_DONE = 'done_';
const PREFIX_ERROR = 'error_';
public function __construct() {
parent::__construct();
if ($this->load->config('redis', true, true)) {
$this->redisConfig = $this->config->config['redis'];
}
$this->redisClient = new Redis();
$this->redisClient->connect($this->redisConfig['hostname'], $this->redisConfig['port']);
$this->redisClient->auth($this->redisConfig['auth']);
$this->redisClient->select($this->redisConfig['queue']);
}
public function setNewRsvp($data) {
$key = uniqid('rsvp_'.gethostname().'_',true).':redis';
$this->redisClient->set($key, $data, 60 * 30);
return $key;
}
}

How to update or insert new data on codeigniter

I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios
I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}
Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}

unexpected 'A' Postman php api with JSON Response

Recently I try to create an API with PHP. all thing goes alright till suddenly I face unexpected 'a' error when trying to parse a JSON from the request throw Postman. I found something related to my issue but there is no solution in my case here : link
I send
{
"teacher_code":"sas"
}
JSON to teachers.php file to assign a student to the teacher
here is the teacher.php file content :
require_once ("classes/Rest.php");
require_once ("classes/api.php");
$api = new Api();
if($api->getHttpmethod() === 'POST'){
$api->validateParameter('teacher_code' ,$teacher_code = $api->getParam('teacher_code') , STRING , true);
$api->checkUserAccessablity();
$api->teacherCodeinRange($teacher_code);
$query = "INSERT INTO `group_users` (`user_id`,`group_id` )
VALUES (:user_id , (SELECT group_id FROM `groups` WHERE group_name = 'all' AND user_id =
(SELECT user_id FROM `teachers` WHERE t_code = :teacher_code)) )";
$keyValue = [
"user_id" => $api->getUserid() ,
"teacher_code" => $teacher_code
];
$result = $api->queryExecute($query , $keyValue );
$api->returnResponse(SUCCESS , SUCCESS_MESSAGE);
}
and api.php file :
require_once ("dbConnect.php");
require_once ("JWT.php");
class Api extends Rest
{
public $dbConn;
private $userId;
public function __construct()
{
parent::__construct();
$db = new dbConnect();
$this->dbConn = $db->connect();
}
public function setUserid($id){
$this->userId = $id;
}
public function getUserid(){
return $this->userId;
}
public function checkUserAccessablity(){
$payload = $this->deCodetoken();
$this->setUserid($payload->user_id);
$this->validateUser();
}
public function validateUser(){
$query = "SELECT * FROM `users` WHERE user_id = :id";
$keyValue = [
"id" => $this->getUserid()
];
$result = $this->queryExecute($query , $keyValue,true );
if(!$result){
$this->throwError(SYSTEM_ERROR , SYSTEM_ERROR_MESSAGE );
}
if(!is_array($result)){
$this->throwError(USER_NOT_FOUND_CODE , USER_NOT_FOUND_MESSAGE . $this->getUserid());
}
//TODO CHECK USER ACTIVE
return true;
}
public function teacherCodeinRange($tCode){
$query = "SELECT * FROM `teachers` INNER JOIN `licenses` ON (licenses.user_id = teachers.user_id)
WHERE teachers.t_code = :tcode LIMIT 1";
$keyValue = [
"tcode" => $tCode
];
$this->queryExecute($query , $keyValue,true );
return true;
}
public function teacherCodeinStudentrange($teacherID){
//TODO SELECT TEACHER STUDENT RANGE
$query = "SELECT DISTICT user_id FROM `teachers` INNER JOIN `groups` ON (groups.user_id = teachers.user_id)
INNER JOIN `group_users` ON (group_users.group_id = groups.group_id)
WHERE teachers.user_id = :teacherID AND groups.group_name = 'all' AND group_users.user_id = :userID ";
$keyValue = [
"userID" => $this->getUserid(),
"teacherID" => $teacherID,
];
$result = $this->queryExecute($query , $keyValue,true );
if(!is_array($result)){
$this->throwError(TEACHER_NOT_FOUND , TEACHER_NOT_FOUND_MESSAGE);
}
return true;
}
public function getHttpmethod(){
return $this->HttpMethod;
}
public function getParam($key){
return $this->arrayFinddeep($this->data , $key);
}
public function queryExecute($query , $keyArray , $isSelect = false){
$queryExec = $this->dbConn->prepare($query);
if(is_array($keyArray) || !empty($keyArray)) {
foreach ($keyArray as $key => &$value) {
$queryExec->bindParam(':' . $key, $value);
}
}
if($isSelect) {
$queryExec->execute();
$result = $queryExec->fetch(PDO::FETCH_ASSOC);
}else {
$result = $queryExec->execute();
}
return $result;
}
public function getLastuserId(){
return $this->dbConn->lastInsertId();
}
public function generateToken($payload , $secretKey){
try{
return \Firebase\JWT\JWT::encode($payload , $secretKey);
}catch (Exception $exception){
$this->throwError(JWT_PROCESSING_ERROR , $exception->getMessage());
}
}
public function deCodetoken(){
try{
$token = $this->getBearerToken();
$payload = \Firebase\JWT\JWT::decode($token , SECURITY_KEY , ['HS256']);
return $payload;
}catch (Exception $exception){
$this->throwError(ACCESS_TOKEN_ERROR , $exception->getMessage());
}
}
}
and the last class is Rest.php :
require_once ("Constans.php");
class Rest
{
protected $HttpMethod;
protected $request;
protected $data;
public function __construct(){
$this->HttpMethod = $_SERVER['REQUEST_METHOD'];
if($this->checkValidhttpMethod()) {
try{
$handler = fopen('php://input', 'r');
$this->request = stream_get_contents($handler);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
$this->validateRequest();
}
}
public function checkValidhttpMethod(){
if(empty($this->HttpMethod) or !in_array($this->HttpMethod,ACCEPTABLE_HTTP_METHOD)){
$this->throwError(NOT_VALID_HTTP_METHOD,NOT_VALID_HTTP_METHOD_Message);
}
return true;
}
public function setJsonheader(){
header("content-type: application/json");
}
public function validateRequest(){
if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
$this->throwError(REQUEST_CONTENT_NOT_VALID , REQUEST_CONTENT_NOT_VALID_MESSAGE);
}
try{
$this->data = json_decode($this->request , true);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
}
public function processAPI(){
}
public function throwError($code , $message){
$this->setJsonheader();
echo json_encode(['error' => ['status' => $code , 'message' => $message]]);
exit;
}
public function returnResponse($code , $data){
$this->setJsonheader();
echo json_encode(['response' => ['status' => $code , 'result' => $data ]]);
exit;
}
//TODO SQL injection Validate
public function validateParameter($fieldName , $value , $dataType , $required = true){
if($required && empty($value)){
$this->throwError(PARAMETR_REQUIRED,PARAMETR_REQUIRED_MESSAGE . $fieldName);
}
//TODO SQL injection
//TODO CHECK The All Data Type
switch ($dataType){
case BOOLEAN :
if(!is_bool($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case INTEGER :
if(!is_numeric($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case STRING :
if(!is_string($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case DONT_CARE :
break;
default:
break;
}
return $value;
}
public function arrayFinddeep($array, $search)
{
foreach($array as $key => $value) {
if (is_array($value)) {
$sub = $this->arrayFinddeep($value, $search);
if (count($sub)) {
return $sub;
}
} elseif ($key === $search) {
return $value;
}
}
return array();
}
/**
* Get hearder Authorization
* */
function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = $this->getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
$this->throwError(AUTHORIZATION_HEADER_NOT_FOUND , AUTHORIZATION_HEADER_NOT_FOUND_MESSAGE);
}
}
all queries go along queryExecute function in api.php class and recently I got that the bindParam function is not going to work fine too.
I really don't have any idea where the problem is, as In the reference said its somehow related to DB queries result. I try to use mysqli also but it did not work.
any help will be appreciated :-)

mongodb update exception 'document fragment is too large'

Updating my collection record field with 'MongoBinData', exception is triggered:
"document fragment is too large: 21216456, max: 16777216"
I find some web discussion about 'allowDiskUse:true' for aggregate, but nothing ubout 'update'.
Here a part of code in PHP:
try {
$criteria = array( '_id' => $intReleaseId);
$fileData = file_get_contents( $_FILES[ $fileKey]["tmp_name"]);
$mongoBinData = new MongoBinData( $fileData, MongoBinData::GENERIC)
$docItem['data'] = $mongoBinData;
$docItem['fileType'] = $strFileType;
$docItem['fileSize'] = $intFileSize;
$docItem['fileExtension'] = $strFileExtension;
$docItem['fileName'] = $strFileName;
$options = array( "upsert" => true,
'safe' => true, 'fsync' => true,
'allowDiskUse' => true ); // this option doesn't change anything
$reportJson = self::GetCollection('releases')->update( $criteria, $docItem, $options);
...
MongoDb release is db version v3.0.6
Some idea ?
Self resolved.
Use gridFS is immediate and simple.
$_mongo = new MongoClient();
$_db = $_mongo->selectDB($_mDbName);
$_gridFS = $_db->getGridFS();
/* */
function saveFileData($intReleaseId, $binData) {
$criteria = array( '_id' => $intReleaseId);
// if exist or not, remove previous value
try {
$_gridFS->remove( $criteria);
}
catch(Exception $e) {}
// store new file content
$storeByteCompleted = false;
try {
$reportId = $_gridFS->storeBytes(
$binData,
array("_id" => $intReleaseId));
if ($reportId == $intReleaseId) {
$storeByteCompleted = true;
}
catch(Exception $e) {}
return $storeByteCompleted;
}
function loadFileData($intReleaseId) {
$gridfsFile = null;
$binData = null;
try {
$gridfsFile = $_gridFS->get($intReleaseId);
}
catch(Exception $e) {}
if ($gridfsFile != null) {
$binData = $gridfsFile->getBytes()
}
return $binData;
}
That's all.

Form not validate at Symfony side, what could be possible wrong?

I have this code in my controller:
/**
* #Secure(roles="IS_AUTHENTICATED_FULLY")
* #Route("/rpni/registro/producto/1/guardar", name="productoGuardarPasoUno")
* #Method("POST")
*/
public function guardarPaso1Action(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$response['success'] = false;
$status = 400;
if ($request->isXmlHttpRequest()) {
$productoSolicitudRequest = $request->request->get('productoSolicitud');
$entProductoSolicitud = $em->getRepository("AppBundle:ProductoSolicitud")->find($session->get('productoSolicitudId'));
$entProducto = $em->getRepository("AppBundle:Producto")->find($productoSolicitudRequest['producto']['nombre']);
$entCondicionProducto = $em->getRepository("AppBundle:CondicionProducto")->find($productoSolicitudRequest['condicion_producto']);
$entFinalidadProducto = $em->getRepository("AppBundle:FinalidadProducto")->find($productoSolicitudRequest['finalidad_producto']);
$entProcedenciaProducto = $em->getRepository("AppBundle:ProcedenciaProducto")->find($productoSolicitudRequest['procedencia_producto']);
$entSolicitudUsuario = $em->getRepository("AppBundle:SolicitudUsuario")->find($session->get('solicitudUsuarioId'));
if ($entProductoSolicitud)
{
$entProductoSolicitud->setProducto($entProducto);
$entProductoSolicitud->setCondicionProducto($entCondicionProducto);
$entProductoSolicitud->setFinalidadProducto($entFinalidadProducto);
$entProductoSolicitud->setProcedenciaProducto($entProcedenciaProducto);
$entProductoSolicitud->setSolicitudUsuario($entSolicitudUsuario);
try {
$em->flush();
} catch (\Exception $e) {
$response['error'] = $e->getMessage();
return new JsonResponse($response, $status);
}
} else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
if ($formProductoSolicitud->isValid())
{
try {
$em->persist($newEntProductoSolicitud);
$em->flush();
$session->set('productoSolicitudId', $newEntProductoSolicitud->getId());
$session->set('productoId', $entProducto->getId());
$response['success'] = true;
// Debug: remover cuando se termine el Bundle
$response['productoSolicitudId'] = $session->get('productoSolicitudId');
$response['productoId'] = $session->get('productoId');
$status = 200;
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
$response['error'] = $this->get('translator')->trans('formularioNoValido');
$response['formError'] = $this->getFormErrors($formProductoSolicitud);
return new JsonResponse($response, $status);
}
}
return new JsonResponse($response, $status);
}
}
Which I'm trying to use for create and for update purposes. When I send the form through Ajax I get this response from Symfony2:
{
"success":false,
"error":"formularioNoValido",
"formError":{
"producto":{
"nombre":[
]
},
"lote":[
],
"procedencia_producto":[
],
"finalidad_producto":[
],
"condicion_producto":[
]
}
}
And nothing else to give me a clue. The weird part is that checking Post tab in Firebug give me this output:
Parameters application/x-www-form-urlencodedDo not sort
productoSolicitud[_token] wC_MAeVs7ZAGSpkvLYux6RKrLq46aivxXxiCZr6pNeU
productoSolicitud[condici... 1
productoSolicitud[finalid... 1
productoSolicitud[lote] 11
productoSolicitud[procede... 1
productoSolicitud[product... 4
Source
productoSolicitud%5Bproducto%5D%5Bnombre%5D=4&productoSolicitud%5Bprocedencia_producto%5D=1&productoSolicitud%5Bfinalidad_producto%5D=1&productoSolicitud%5Bcondicion_producto%5D=1&productoSolicitud%5Blote%5D=11&productoSolicitud%5B_token%5D=wC_MAeVs7ZAGSpkvLYux6RKrLq46aivxXxiCZr6pNeU
See the image below:
So, where the error is? Why form is not valid? Any clue? Advise?
If I'm not mistaken, your action only returns that response from this else statement :
else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
if ($formProductoSolicitud->isValid())
{
try {
$em->persist($newEntProductoSolicitud);
$em->flush();
$session->set('productoSolicitudId', $newEntProductoSolicitud->getId());
$session->set('productoId', $entProducto->getId());
$response['success'] = true;
// Debug: remover cuando se termine el Bundle
$response['productoSolicitudId'] = $session->get('productoSolicitudId');
$response['productoId'] = $session->get('productoId');
$status = 200;
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
$response['error'] = $this->get('translator')->trans('formularioNoValido');
$response['formError'] = $this->getFormErrors($formProductoSolicitud);
return new JsonResponse($response, $status);
}
}
I find it weird that you're checking your form's validity right after you created it from a new instance of ProductoSolicitud, is that really what you want to do ? Shouldn't you make this validity check in the case you got some data from the request ?
Maybe something like this :
if ($entProductoSolicitud)
{
$entProductoSolicitud->setProducto($entProducto);
$entProductoSolicitud->setCondicionProducto($entCondicionProducto);
$entProductoSolicitud->setFinalidadProducto($entFinalidadProducto);
$entProductoSolicitud->setProcedenciaProducto($entProcedenciaProducto);
$entProductoSolicitud->setSolicitudUsuario($entSolicitudUsuario);
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $entProductoSolicitud);
if ($formProductoSolicitud->isValid()) {
try {
$em->flush();
} catch (\Exception $e) {
$response['error'] = $e->getMessage();
return new JsonResponse($response, $status);
}
}
}
But I might have just misunderstood the problem :S
Well, since I found where the issue was I'll answer myself so others won't make the same mistake. At my code I never tell the form to handle the request so there is where the issue is. The code in the else turns in to this:
} else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
$formProductoSolicitud->handleRequest($request);
if ($formProductoSolicitud->isValid())
{
...
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
....
}
}
return new JsonResponse($response, $status);
}
}
That's all, happy coding!!

Categories