TypeError: invalid 'in' operand e - php

I have the following code for displaying the json response which is thrown by php file when I am displaying it on the console it gives me TypeError: invalid 'in' operand e
Json response:
[{"keyword":"free dental care","svol":27100},{"keyword":"low cost dental care","svol":2900}]
JQuery:
$('#specialty').change(function(){
var spevalue=$( "#specialty option:selected" ).text();
var dataString='specialty='+ spevalue;
$.ajax({
type:"post",
datatype : 'json',
url:"GetKeyWordBids.php",
data:"specialty="+ spevalue,
success: function(data) {
$.each(data, function( index, value ) {
console.log(value.keyword);
});
},
});
});
Response :
TypeError: invalid 'in' operand e
GetKeyWordBids.php
<?php
require_once dirname(__FILE__).'/googleads-php-lib-master/examples/AdWords/v201409/init.php';
/**
* Runs the example.
* #param AdWordsUser $user the user to run the example with
*/
$specialty=$_POST['specialty'];
$ret=array();
// Include the initialization file
require_once UTIL_PATH . '/MapUtils.php';
function GetKeywordIdeasExample(AdWordsUser $user) {
global $ret;
$ret=array();
// Get the service, which loads the required classes.
$targetingIdeaService =
$user->GetService('TargetingIdeaService', ADWORDS_VERSION);
// Create seed keyword.
$keyword =$_POST['specialty'];
// Create selector.
$selector = new TargetingIdeaSelector();
$selector->requestType = 'IDEAS';
$selector->ideaType = 'KEYWORD';
$selector->requestedAttributeTypes = array('KEYWORD_TEXT', 'SEARCH_VOLUME',
'CATEGORY_PRODUCTS_AND_SERVICES');
// Create language search parameter (optional).
// The ID can be found in the documentation:
// https://developers.google.com/adwords/api/docs/appendix/languagecodes
// Note: As of v201302, only a single language parameter is allowed.
$languageParameter = new LanguageSearchParameter();
$english = new Language();
$english->id = 1000;
$languageParameter->languages = array($english);
// Create related to query search parameter.
$relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
$relatedToQuerySearchParameter->queries = array($keyword);
$selector->searchParameters[] = $relatedToQuerySearchParameter;
$selector->searchParameters[] = $languageParameter;
// Set selector paging (required by this service).
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $targetingIdeaService->get($selector);
// Display results.
if (isset($page->entries)) {
foreach ($page->entries as $targetingIdea) {
$data = MapUtils::GetMap($targetingIdea->data);
$keyword = $data['KEYWORD_TEXT']->value;
$search_volume = isset($data['SEARCH_VOLUME']->value)
? $data['SEARCH_VOLUME']->value : 0;
$categoryIds =
implode(', ', $data['CATEGORY_PRODUCTS_AND_SERVICES']->value);
// printf("Keyword idea with text '%s', category IDs (%s) and average "
//. "monthly search volume '%s' was found.\n",
// $keyword, $categoryIds, $search_volume);
array_push($ret,array("keyword"=>$keyword,"svol"=>$search_volume));
//$temp=array();
//$ret = array_merge($ret, array("keyword"=>$keyword,"svol"=>$search_volume));
//array_push($ret,$temp);
//$json=json_encode($temp);
//array_push($ret,$json);
}
//print_r($ret);
echo json_encode($ret);
}
else {
print "No keywords ideas were found.\n";
}
// Advance the paging index.
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);
}
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log every SOAP XML request and response.
$user->LogAll();
//$user->SetClientCustomerId(3310773561);
// Run the example.
GetKeywordIdeasExample($user);
} catch (Exception $e) {
printf("An error has occurred: %s\n", $e->getMessage());
}

Related

Removing document root from file path Zend Framework 2

I'm trying to display an image but I am running into the error of Not allowed to load local resource: file:///C:/xampp/htdocs/public/images/profile/jimmy/status/boned.jpg in the browser console. What I am trying to do is use the base path provided by Zend Framework 2 but I'm retrieving the images in the model so (as far as I know), I can't use $this->basePath() like I would in the view.
This is my json string I am returning but would like to just be able to return /images/profile/jimmy/status/boned.jpg and whatever other images are in there.
I'm getting all the files outside of the directory 'status'. I am trying to get the files inside the status directory. When I did a var_dump this is what I get string(43) "C:\xampp\htdocs/public/images/profile/jimmy" I'm unclear why it is omitting the status directory after '/jimmy'
json string being returned:
{"feed":{"username":"Timmy","status":["this is jimmy, test"],"images":["videos","status","sithtoon.jpg","sith.jpg","edited_photos","diploma.jpg","current","albums","Screenshot_2016-08-09_21_28_13_361272.jpg","Screenshot_2016-08-05_17_55_48_500802.jpg","515gIIJ-Imgur.png",".htaccess"]}}
Here is the relevant PHP code (in the model):
public function listFriendsStatus()
{
$user_id = $this->getUserId()['id'];
// get the friend ids based on user id
// and then compare the friend id to the id in status table
$friend_query = new Select('friends');
$friend_query->columns(array('friend_id'))
->where(array('user_id' => $user_id));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($friend_query),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
$friend_id = array();
foreach ($query as $result) {
$friend_id[] = $result['friend_id'];
}
$status = new Select('status');
$status->columns(array('status'))
->where(array('id' => $friend_id));
$status_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($status),
Adapter::QUERY_MODE_EXECUTE
);
if ($status_query->count() > 0) {
// check if a image was used
$members = new Select('members');
$members->columns(array('username'))
->where(array('id' => $friend_id));
$image_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($members),
Adapter::QUERY_MODE_EXECUTE
);
if ($image_query->count() > 0) {
foreach ($image_query as $value) {
if (is_dir(getcwd() . '/images/profile/' . $value['username'] . '/status/')) {
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
}
}
$images = array();
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
// retrieve the image inside the status directory
foreach (array_diff(scandir($status_dir['dirname'], 1), array('.', '..')) as $values) {
$images[] = $values;
}
} else {
throw new FeedException("The user does not exist in the user table.");
}
$status = array();
// get all the statuses
foreach ($status_query as $rows) {
$status[] = $rows['status'];
}
return array('username' => ucfirst($value['username']), 'status' => $status, 'images' => $images); // how to just get the basePath path with zf2
} else {
throw new FeedException("No status was found for your friends.");
}
} else {
throw new FeedException(sprintf("Could not locate any friends for %s", $this->user));
}
}
controller code:
public function getfriendstatusAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try {
echo json_encode(array('feed' => $this->getStatusService()->listFriendsStatus()));
} catch (FeedException $e) {
echo json_encode(array('fail' => $e->getMessage()));
}
return $view_model;
}
jquery code:
$.getJSON('/members/feed/get-friend-status', function(data) {
$.each(data, function(i, item) {
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('h4').html(data[i].username);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('p').html(data[i].status);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response);
});
I've been trying to use other directory functions provided with PHP but if I try anything, I run into the error directory could not be found. Basically what I am trying to do is use the similiar approach of $this->basePath() but in a model.
I hope that is clear enough..
Thanks!
Here is a screenshot of what I'm getting and how I want to get the status directory, not the directory outside of it.
I have an idea.
In your code is:
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
// ..............
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
Try:
var_dump($status_dir);
I guess 'status' will be in 'basename' and / or in 'filename'
pathinfo gets last segment of argument string path as 'basename'.
Pathinfo only parses string as path and return array info, don't check it for isDir or isFile. Your correct chdir should looks like chdir($status_dir['dirname'] . '/' . $status_dir['basename'] ); if you need use of pathinfo.
In other words: dirname of 'images/profile/jimmy/status' is 'images/profile/jimmy' and its a reason why you don't see status in var_dump($status_dir['dirname']) and why chdir($status_dir['dirname']) not working correctly.

vTiger Custom Field Validation beforesave

I have created a custom module on vTiger 6.5.
I have made an event handler for the module but I am wondering how I could perform some sort of validation on this field. So fat I have done this but I am unable to get it work, I have tested the handler just echoing a sting and it works fine.
Please see my code below. Thanks!
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
# getModuleName : Returns the module name of the entity.
# getId : Returns id of the entity, this will return null if the id has not been saved yet.
# getData : Returns the fields of the entity as an array where the field name is the key and the fields value is the value.
# isNew : Returns true if new record is being created, false otherwise.
# 'vtiger.entity.beforesave.modifiable' : Setting values : $data->set('simple_field', 'value');
class isaHandler extends VTEventHandler {
function handleEvent($eventName, $entityData) {
global $adb;
$moduleName = $entityData->getModuleName();
if($moduleName=='isa'){
if($eventName == 'vtiger.entity.beforesave.modifiable') {}
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}
if($eventName == 'vtiger.entity.beforesave.final') {}
if($eventName == 'vtiger.entity.aftersave') {
}
}
}
}
?>
After doing some searching around and looking at other peoples event handlers I managed to solve this by changing:
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
to
if($eventName == 'vtiger.entity.beforesave') {
$price = $entityData->get('currentamount');
if($price > 20000){
echo "Please go back and enter less than 20000";
exit;
}
Now I want to see if I can display the message and then give a link to go back to the entity module with all the fields still full.
In my opinion you should use the recordPreSave function.
It's allow you to display an information/error message before to save data on the database
Here is an example:
In your Edit.js:
donCache : {},
checkDon : function(details) {
// alert("checkOverlap");
var aDeferred = jQuery.Deferred();
var params = {
'module' : 'Affectations',
'action' : "checkAffectAmount",
'mode': 'CtrlAffectAmount',
'recordId' : details.don,
'montant' : details.montant
}
AppConnector.request(params).then(
function(data) {
if (data.success == true) {
// console.log(data.result);
var statut = data.result.statut;
var reste = data.result.reste;
if(statut == "error"){
aDeferred.reject(data);
}else {
aDeferred.resolve(data);
}
}
},
function(error,err){
aDeferred.reject();
}
);
return aDeferred.promise();
},
registerRecordPreSaveEvent : function(form) {
var thisInstance = this;
if (typeof form == 'undefined') {
form = this.getForm();
}
form.on(Vtiger_Edit_Js.recordPreSave, function(e, data) {
var check = false;
var recordId = jQuery('input[name="record"]').val();
if (!recordId || recordId) {
var montant_affectation = jQuery("input[name='affectations_montant']").val();
var don_id = jQuery("input[name='affectations_potentialid']").val();
var params = {};
if (!(check in thisInstance.donCache)) {
thisInstance.checkDon({
'montant' : montant_affectation,
'don': don_id
}).then(
function(data){
thisInstance.donCache[check] = data['success'];
form.submit();
},
function(data, err){
thisInstance.donCache[check] = data['success'];
var reste = data.result.reste;
var msg = app.vtranslate("<strong>Attention!</strong> La somme des affectations est supérieure de ")+ reste +app.vtranslate(" Euros au montant du don");
Vtiger_Helper_Js.showPnotify(msg);
delete thisInstance.donCache[check];
}
);
} else {
delete thisInstance.donCache[check];
return true;
}
e.preventDefault();
}
})
},
The PHP part in modules/isa/actions:
<?php
/***********************************
** DEBUT ALTAIR - JPR 15/06/2016 ***
***********************************/
class Affectations_checkAffectAmount_Action extends Vtiger_Action_Controller {
function __construct() {
$this->exposeMethod('CtrlAffectAmount');
}
public function checkPermission(Vtiger_Request $request) {
$moduleName = $request->getModule();
$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
$userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
$permission = $userPrivilegesModel->hasModulePermission($moduleModel->getId());
if(!$permission) {
throw new AppException('LBL_PERMISSION_DENIED');
}
}
public function process(Vtiger_Request $request) {
$mode = $request->getMode();
if(!empty($mode) && $this->isMethodExposed($mode)) {
$this->invokeExposedMethod($mode, $request);
return;
}
}
function CtrlAffectAmount(Vtiger_Request $request){
global $adb,$log;
$log->debug("ALTAIR CtrlAffectAmount OK");
$recordId = $request->get('recordId');
$montant = $request->get('montant');
// $query = $adb->pquery("SELECT SUM(unit_price) AS sommeaffectation FROM vtiger_products INNER JOIN vtiger_crmentity ON vtiger_products.productid = vtiger_crmentity.crmid WHERE don_affecte = ? AND vtiger_crmentity.deleted=0",array($recordId));
$query = $adb->pquery("SELECT SUM(affectations_montant) AS sommeaffectation FROM vtiger_affectations INNER JOIN vtiger_crmentity ON vtiger_affectations.affectationsid = vtiger_crmentity.crmid WHERE vtiger_affectations.affectations_potentialid = ? AND vtiger_crmentity.deleted=0",array($recordId));
$sommeAffectation = $adb->query_result($query,0,"sommeaffectation");
$query = $adb->pquery("SELECT amount FROM vtiger_potential INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid WHERE potentialid = ? AND vtiger_crmentity.deleted = 0", array($recordId));
$montantDon = $adb->query_result($query,0,"amount");
if ( ($sommeAffectation + $montant) == $montantDon) {
$statut = "ok";
$reste = "";
} else if( ($sommeAffectation + $montant) > $montantDon) {
$statut = "error";
$reste = ($sommeAffectation + $montant) - $montantDon;
}
$value = array('statut'=>$statut, 'reste'=>$reste);
$response = new Vtiger_Response();
$response->setEmitType(Vtiger_Response::$EMIT_JSON);
$response->setResult($value);
$response->emit();
}
}
Oh. you have 1 invalid error here. please change:
if($eventName == 'vtiger.entity.beforesave') {
$currentAmount = $entityData->get('currentamount');
if($currentAmount > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}

AS3 not recieving myStatus from php login page

I am not receiving the myStatus when retrieving it from the php login. I get p_id and full name but not the status. I am parsing it to separate out the & but keep getting a null result from login. section 6 and section 7 are the areas I think I am having issues can anyone help?
login AS3
package {
import flash.display.MovieClip;
import flash.text.*;
import flash.events.*;
import flash.ui.Keyboard;
import flash.net.*;
import MainDocument;
public class Login extends MovieClip {
public function Login() {
// constructor code
// modify existing text boxes
login_txt.tabEnabled = true;
login_txt.tabIndex = 1;
login_txt.border = true;
login_txt.borderColor = 0xAAAAAA;
login_txt.background = true;
login_txt.backgroundColor = 0xFFFFDD;
pwd_txt.tabEnabled = true;
pwd_txt.tabIndex = 2;
pwd_txt.border = true;
pwd_txt.borderColor = 0xAAAAAA;
pwd_txt.background = true;
pwd_txt.backgroundColor = 0xFFFFDD;
login_btn.tabEnabled = true;
login_btn.tabIndex = 3;
//add button event listeners
login_btn.addEventListener(MouseEvent.MOUSE_UP, doLogin);
login_close_btn.addEventListener(MouseEvent.MOUSE_UP, doClose);
addEventListener(KeyboardEvent.KEY_DOWN, onEnter);
} // end construtor
private function onEnter(e:KeyboardEvent):void{
// nothing yet
if(e.keyCode == Keyboard.ENTER){
trace("User presses keyboard ENTER key");
doLogin(null); // must be null to meet the need for a parameter
}// end if
}// end function
// SECTION 1 – This is a function we need for removing extra whitespace coming from CWP server
function trimWhitespace($string:String):String {
if ($string == null) {
return "";
} //end if
return $string.replace(/^\s+|\s+$/g, ""); // see regular expressions
} // end function
private function doLogin(e:MouseEvent):void{
//trace("User presses OK button");
// SECTION 2 – URL request variable declared with path to server script
var req:URLRequest=new URLRequest(MainDocument.localPath + "login.php");
req.method = URLRequestMethod.POST;
// SECTION 3 – Upload variables are named as URL variables
var vars:URLVariables=new URLVariables();
vars.login = login_txt.text;
vars.pwd = pwd_txt.text;
req.data = vars;
// SECTION 4 – The URL Loader class instance is set to perform the HTTP POST
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(req);
// SECTION 5 – listeners are added for both the HTTP status and COMPLETE
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,onHTTPStatus);
loader.addEventListener(Event.COMPLETE, retrieveData);
// SECTION 6 – The complete handler function is embedded within the doLogin() function
function retrieveData(e:Event):void {
// For the CWP server we must parse our own incoming data
var rawString:String = trimWhitespace(unescape(e.target.data));
var stArray:Array = rawString.split("&"); //split on ampersand character
trace("retrieve data");
for(var i:uint; i<stArray.length; i++){
stArray[i] = trimWhitespace(stArray[i]);
var pair:Array = stArray[i].split("=");
pair[0] = trimWhitespace(pair[0]);
switch (pair[0]){
case "myStatus":
var ms:String = trimWhitespace(pair[1]); // status data value
break;
case "p_id":
var id:int = int(trimWhitespace(pair[1])); // player id
break;
case "fullname":
var fn:String = trimWhitespace(pair[1]); // fullname
break;
default: // this is all the other junk---> dump
//do nothing
} // end switch
} //end for
// SECTION 7 – A switch statement to deal with cases of myStatus
switch (ms){
case "NOTOK" :
MainDocument.doc.showMsg("There is a communication problem\nTry Again!");
break;
case "OK" :
if(fn != "INVALID"){
MainDocument.doc.showMsg("Welcome " + fn);
//MainDocument.player_id = id;
//MainDocument.player_name = fn;
MainDocument.doc.removeLogin();
MainDocument.doc.turnOffButton("both");
//MainDocument.doc.enable_chat_button();
//MainDocument.doc.activateConsole();
////////////////////////
// start game here
////////////////////////
}else{
MainDocument.doc.showMsg("Login or password is incorrect. Try again, or \nif you are not a member, please register");
MainDocument.doc.turnOnButton("register");
MainDocument.doc.turnOffButton("login");
}
break;
default:
//MainDocument.doc.showMsg("An unknown problem has occured");
} // end switch
} // end function
// SECTION 8 – Handler function for HTTP status – also embedded
function onHTTPStatus(event:HTTPStatusEvent):void {
//trace("HTTP response code " + event.status);
if(event.status!=200){
MainDocument.doc.showMsg("There is an I/O Error #" + event.status);
} // end if
} // end function
} // end function doLogin
private function doClose(e:MouseEvent):void{
// nothing yet
trace("User presses Close button");
MainDocument.doc.showMsg(""); // clears any message
MainDocument.doc.removeLogin();
MainDocument.doc.turnOnButton("both");
}// end function
}//end class
}// end package
login.php
<?php
require_once("settings.inc.php");
// Create vars and load with incoming POST data
$login = $_POST['login'];
if(!isset($login)){
$login = $_GET['login'];
}
$pwd = $_POST['pwd'];
if(!isset($pwd)){
$pwd = $_GET['pwd'];
}
//=========================================================================================
// MAIN
//=========================================================================================
if(!(isset($login) && isset($pwd))){
print "myStatus=NOTOK&dummy=dummy";
}else{
$query = "SELECT `p_id`,`p_name` FROM `player` WHERE `p_login`='$login' AND `p_pwd`='$pwd'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_row($result);
if($row[0] != null && $row[0] != ''){
$p_id = $row[0];
$fullname = trim($row[1]);
$myStatus = $row[2];
print "myStatus=OK&p_id=" . trim($p_id) . "&fullname=" . trim($fullname) . "&dummy=dummy";
}else{
$fullname = "INVALID";
print "myStatus=OK&fullname=" . trim($fullname) . "&dummy=dummy";
} //end else
} //end else
?>

ajax to a php and get JSON from it

I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?
Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.
I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()

How to create a new .MDB file with php?

In our in house system, we have csv & xls files generated for users (phpexcel) from our MySQL database, but my boss is asking if is's possible to create a mdb file.
I've never come across any sample on creating a new MDB file on the fly, and I wonder if it's possible. I'm not an expert programmer by any chance, but I can manage if anyone could guide me on how I should proceed.
We're trying to reduce user load/mistakes by providing them with mdb instead of CSV that they have to import into Access. Currently they have to import over 100 csv files into Access.
Thank you.
You can use COM for accessing the MDB driver, There is a simple class located at phpclasses that acts as a wrapper for this, you can either use it for inspiration or port it directly, either way it's perfectly possible:
Here is the class, the source link is provided below:
<?php
class mdb
{
var $RS = 0;
var $ADODB = 0;
var $RecordsAffected;
var $strProvider = 'Provider=Microsoft.Jet.OLEDB.4.0';
var $strMode = 'Mode=ReadWrite';
var $strPSI = 'Persist Security Info=False';
var $strDataSource = '';
var $strConn = '';
var $strRealPath = '';
var $recordcount = 0;
var $ok = false;
/**
* Constructor needs path to .mdb file
*
* #param string $dsn = path to *.mdb file
* #return boolean success
*/
function mdb( $dsn='Please enter DataSource!' )
{
$this->strRealPath = realpath( $dsn );
if( strlen( $this->strRealPath ) > 0 )
{
$this->strDataSource = 'Data Source='.$this->strRealPath;
$result = true;
}
else
{
echo "<br>mdb::mdb() File not found $dsn<br>";
$result = false;
}
$this->RecordsAffected = new VARIANT();
$this->open();
} // eof constructor mdb()
function open( )
{
if( strlen( $this->strRealPath ) > 0 )
{
$this->strConn =
$this->strProvider.';'.
$this->strDataSource.';'.
$this->strMode.';'.
$this->strPSI;
$this->ADODB = new COM( 'ADODB.Connection' );
if( $this->ADODB )
{
$this->ADODB->open( $this->strConn );
$result = true;
}
else
{
echo '<br>mdb::open() ERROR with ADODB.Connection<br>'.$this->strConn;
$result = false;
}
}
$this->ok = $result;
return $result;
} // eof open()
/**
* Execute SQL-Statement
* #param string $strSQL = sql statement
* #param boolean $getrecordcount = true when a record count is wanted
*/
function execute( $strSQL, $getrecordcount = false )
{
$this->RS = $this->ADODB->execute( $strSQL, &$this->RecordsAffected );
if( $getrecordcount == true )
{
$this->RS->MoveFirst();
$this->recordcount = 0;
# brute force loop
while( $this->RS->EOF == false )
{
$this->recordcount++;
$this->RS->MoveNext();
}
$this->RS->MoveFirst();
}
} // eof execute()
function eof()
{
return $this->RS->EOF;
} // eof eof()
function movenext( )
{
$this->RS->MoveNext();
} // eof movenext()
function movefirst()
{
$this->RS->MoveFirst();
} // eof movefirst()
function close()
{
#$this->RS->Close(); // Generates a warning when without "#"
$this->RS=null;
#$this->ADODB->Close();
$this->ADODB=null;
} // eof close()
function fieldvalue( $fieldname )
{
return $this->RS->Fields[$fieldname]->value;
} // eof fieldvalue()
function fieldname( $fieldnumber )
{
return $this->RS->Fields[$fieldnumber]->name;
} // eof fieldname()
function fieldcount( )
{
return $this->RS->Fields->Count;
} // eof fieldcount()
} // eoc mdb
?>
And an example:
include 'class_mdb.php';
$mdb = new mdb('mymdbfile.mdb'); // your own mdb filename required
$mdb->execute('select * from table'); // your own table in the mdb file
#
# first example: using fieldnames
#
while( !$mdb->eof() )
{
echo $mdb->fieldvalue('description'); // using your own fields name
echo ' = ';
echo $mdb->fieldvalue( 1 ); // using the fields fieldnumber
echo '<br>';
$mdb->movenext();
}
echo '<br><hr><br>';
#
# Going back to the first recordset for the second example
#
$mdb->movefirst();
#
# This works, too: Make each Field an object. The values change
# when the data pointer advances with movenext().
#
$url = $mdb->RS->Fields(1);
$bez = $mdb->RS->Fields(2);
$kat = $mdb->RS->Fields(3);
while( !$mdb->eof() )
{
# works!
echo $bez->value;
echo ' = ';
echo $url->value;
echo '<br>';
$mdb->movenext();
}
$mdb->close();
Source: http://www.phpclasses.org/package/1700-PHP-Access-Microsoft-Access-mdb-database-files.html
To create a new empty Microsoft Access Database we can use ADOX.
The code below creates an empty Test.mdb file in c:\
$adox_catalog = new COM("ADOX.Catalog");
$adox_catalog->create('Provider = Microsoft.Jet.OLEDB.4.0; Data Source=c:\Test.mdb');
$adodb_conection = $adox_catalog->activeconnection();

Categories