How to handle checkbox values in a query string? - php

I have a query string that has a bunch of form field values in it. One of the fields is a checkbox and it creates duplicate parameters, for example:
?employee_selection_needs=cat&employee_selection_needs=dog&employee_selection_needs=pig
I need to place all of these checkbox values into one variable to be submitted to the HubSpot API. How can I accomplish that? I've tried it with a foreach loop but that does not seem to work.
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$organization_name = $_POST["organization_name"];
$phone = $_POST["phone"];
$best_describes_org = $_POST["best_describes_org"];
$organizations_safety = $_POST["organizations_safety"];
$confident_interview_process = $_POST["confident_interview_process"];
$needs_around_leadership = $_POST["needs_around_leadership"];
$used_employee_assessments = $_POST["used_employee_assessments"];
$hire_annually = $_POST["hire_annually"];
foreach($_POST['employee_selection_needs'] as $needs) {
$employee_selection_needs .= $needs;
}
//Need to populate these variable with values from the form.
$str_post = "firstname=" . urlencode($firstname)
. "&lastname=" . urlencode($lastname)
. "&email=" . urlencode($email)
. "&phone=" . urlencode($phonenumber)
. "&organization_name=" . urlencode($organization_name)
. "&best_describes_org=" . urlencode($best_describes_org)
. "&employee_selection_needs=" . urlencode($employee_selection_needs)
. "&organizations_safety=" . urlencode($organizations_safety)
. "&confident_interview_process=" . urlencode($confident_interview_process)
. "&needs_around_leadership=" . urlencode($needs_around_leadership)
. "&used_employee_assessments=" . urlencode($used_employee_assessments)
. "&hire_annually=" . urlencode($hire_annually)
. "&hs_context=" . urlencode($hs_context_json); //Leave this one be

Hei man! I'll try to answer You as easily as possible
Method 1 : From Query String (Your case)
Using ?employee_selection_needs=cat&employee_selection_needs=dog&employee_selection_needs=pig the PHP parser consider only last Key:Value (pig) and for this You haven't an Array to iterate
It' necessary to split URL. See below
<?php
/** CODE */
/** Create an Array of Query Strings Values
*
* OUTPUT EXAMPLE
* array(
* 0 => 'employee_selection_needs=cat',
* 1 => 'employee_selection_needs=dog',
* 2 => 'employee_selection_needs=pig',
* 3 => 'other_key=other_value',
* ...
* )
*/
$queryArray= explode('&', $_SERVER['QUERY_STRING']);
/** Init a variable for append Query Values */
$myOutputString = "";
/** Need for separate append values */
$myOutputToken = "|";
/** Append to $myOutputString the correct Query Value */
foreach($queryArray as $queryArrayElement) {
/** Create an Array starting from a Query String
*
* OUTPUT EXAMPLE
* array(
* 0 => 'employee_selection_needs',
* 1 => 'cat',
* )
*/
$tArray= explode('=', $queryArrayElement);
/** Filter only "employee_selection_needs" key and append Query Value
* to $myOutputString
*/
if(!empty($tArray[0]) && $tArray[0] == 'employee_selection_needs') {
if(!empty($tArray[1]))
$myOutputString .= $tArray[1].$myOutputToken;
}
}
/** Remove last Token */
if(!empty($myOutputString))
$myOutputString = substr($myOutputString, 0, -strlen($myOutputToken));
print_r($myOutputString); // Expected result cat|dog|pig
/** OTHER APPEND HERE */
?>
Method 2 : From HTML Form
You need to use "employee_selection_needs[]" instead of "employee_selection_needs" on checkbox. See below
<form ...>
<input type="checkbox" value="dog" name="employee_selection_needs[]" />
<input type="checkbox" value="cat" name="employee_selection_needs[]" />
<input type="checkbox" value="fish" name="employee_selection_needs[]" />
...
</form>
On submit You'll have an Array of values instead Single value
<?php
/** ... CODE ... */
/** Now is an array =)) */
$used_employee_assessments = $_POST["used_employee_assessments"];
/** ... CODE ... */
/** Convert to String, if You need */
$myOutputString = "";
foreach($used_employee_assessments as $assessment)
$myOutputString .= $assessment;
/** OR use implode ( string $glue , array $pieces )
* $myOutputString = implode(" %MY_TOKEN% ", $used_employee_assessments);
*/
/** OTHER APPEND HERE */
?>

In order to pass multiple parameters with the same name you should include [] in the end of the name. So your url should look like this:
?employee_selection_needs[]=cat&employee_selection_needs[]=dog&employee_selection_needs[]=pig
To do this your checkbox should have
name="employee_selection_needs[]"

Related

Pagination with google ads api in php

I am trying to do the pagination with google-ads-php at the bottom of my page in php, so I get through my ads, like PREVIOUS 1,2,3 NEXT
So this is my code:
public function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves all ads.
$query = "SELECT campaign.name, ad_group.name, "
. "ad_group_ad.ad.responsive_display_ad.marketing_images, "
. "ad_group_ad.ad.app_ad.images, ad_group_ad.ad.app_ad.youtube_videos, "
. "ad_group_ad.ad.responsive_display_ad.youtube_videos, ad_group_ad.ad.local_ad.videos, "
. "ad_group_ad.ad.video_responsive_ad.videos, ad_group_ad.ad.video_ad.media_file, "
. "ad_group_ad.ad.app_engagement_ad.images, ad_group_ad.ad.app_engagement_ad.videos, "
. "ad_group_ad.ad.display_upload_ad.media_bundle, ad_group_ad.ad.gmail_ad.product_images, "
. "ad_group_ad.ad.gmail_ad.product_videos, ad_group_ad.ad.gmail_ad.teaser.logo_image, "
. "ad_group_ad.ad.image_ad.image_url, ad_group_ad.ad.legacy_responsive_display_ad.square_marketing_image, "
. "ad_group_ad.ad.local_ad.marketing_images, ad_group_ad.ad.responsive_display_ad.logo_images, "
. "ad_group_ad.ad.responsive_display_ad.square_logo_images, "
. "ad_group_ad.ad.responsive_display_ad.square_marketing_images, "
. "ad_group_ad.ad.responsive_display_ad.youtube_videos, "
. "metrics.impressions, campaign.campaign_budget, campaign.status, "
. "campaign.start_date, campaign.end_date, metrics.all_conversions, "
. "metrics.average_cost, ad_group_ad.ad.type, ad_group_ad.ad.id, "
. "campaign.campaign_budget, metrics.cost_micros, ad_group_ad.status, metrics.impressions "
. "FROM ad_group_ad "
. "WHERE segments.date >= '{$this->from}' AND segments.date <= '{$this->to}' "
. "ORDER BY campaign.name ASC";
// Issues a search stream request.
/** #var GoogleAdsServerStreamDecorator $stream */
$stream = $googleAdsServiceClient->search($customerId, $query, ['pageSize' => 10]);
$ads = [];
foreach ($stream->iterateAllElements() as $googleAdsRow) {
dump($googleAdsRow->serializeToJsonString());
/** #var GoogleAdsRow $googleAdsRow */
$ads[] = json_decode($googleAdsRow->serializeToJsonString(), true);
}
As you see the pageSize is set to 10, so it will be 23 pages, because I have 230 ads.
How can I do the pagination, now the $stream returns all ads in one response. How can return only 10 ads, and then when user click for example second page button, it will return the next 10 ads, and so on?
Thanks in advance!
here is how it can be done in Python though -
import sys
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
client = GoogleAdsClient.load_from_storage()
ga_service = client.get_service("GoogleAdsService")
search_request = client.get_type("SearchGoogleAdsRequest")
try:
search_request.query = QUERY_STRING
search_request.customer_id = CUSOMER_ID
search_request.page_size = PAGE_SIZE
df = pd.DataFrame()
while True:
response = ga_service.search(search_request)
dictobj = MessageToDict(response._pb)
df = df.append(pd.json_normalize(dictobj,record_path=['results']))
if response.next_page_token == '':
break
else:
search_request.page_token = response.next_page_token
except GoogleAdsException as ex:
print(ex)
To achieve pagination, you may slightly change the display.
Say, if you want to display 10 records per page, so for the 2nd page, it will be
records 11 to 20.
So , to display page 2, you may revising the part :
foreach ($stream->iterateAllElements() as $googleAdsRow) {
dump($googleAdsRow->serializeToJsonString());
/** #var GoogleAdsRow $googleAdsRow */
$ads[] = json_decode($googleAdsRow->serializeToJsonString(), true);
}
to
$index=0;
foreach ($stream->iterateAllElements() as $googleAdsRow) {
$index++;
if ($index >=11 && $index <=20) {
dump($googleAdsRow->serializeToJsonString());
/** #var GoogleAdsRow $googleAdsRow */
$ads[] = json_decode($googleAdsRow->serializeToJsonString(), true);
}
}
Please see whether the above works, and if so, you may amend the codes to show the data according to page number
Google Ads API provides native pagination that as of now is not very well documented. However, you can only paginate by "next" and "previous" pages.
Here is a working example on keywords since that's the use case most people probably get stuck upon.
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
$query =
'SELECT ad_group.id, '
. 'ad_group_criterion.type, '
. 'ad_group_criterion.criterion_id, '
. 'ad_group_criterion.keyword.text, '
. 'ad_group_criterion.keyword.match_type '
. 'FROM ad_group_criterion '
. 'WHERE ad_group_criterion.type = KEYWORD';
// Get the stream
$stream = $googleAdsServiceClient->search($customerId, $query, ['pageSize' => 1000]);
// Get the first page
$page = $stream->getPage();
foreach ($page->getIterator() as $googleAdsRow) {
// Iterating over the first page of 1000 keywords.
}
// Get the next page token
$nextPageToken = $page->getNextPageToken();
// Get the second page
$page = $stream->getPage();
$stream = $googleAdsServiceClient->search($customerId, $query, ['pageSize' => 1000, 'pageToken' => $nextPageToken]);
foreach ($page->getIterator() as $googleAdsRow) {
// Iterating over the second page of 1000 keywords.
}
Note that you have to use search() and not searchStream() and iterator of the actual page instead of iterateAllElements()

codeigniter - Call to a member function query() on a non-object

I'm using xampp 1.77 version, codeigniter 1.7.2 with flexigrid.
I follow step by step this tutorial https://gembelzillonmendonk.wordpress.com/2010/06/28/flexigrid-and-codeigniter-with-advanced-searching-with-example/#comment-353 but I don't understand which code must have flexigrid.php in CI_Folder\system\application\controllers\flexigrid.php.
My flexigrid.php code is this:
<?php
class Flexigrid extends Controller {
function Flexigrid ()
{
parent::Controller();
$this->load->helper('flexigrid');
}
function index()
{
//ver lib
$this->load->model('ajax_model');
$records = $this->ajax_model->get_select_countries();
$options = '';
foreach( $records as $v ) {
$options .= $v['name'] . ';';
}
$options = substr($options, 0, -1);
/*
* 0 - display name
* 1 - width
* 2 - sortable
* 3 - align
* 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
*/
$colModel['id'] = array('ID',40,TRUE,'center',2);
$colModel['iso'] = array('ISO',40,TRUE,'center',0);
$colModel['name'] = array('Name',180,TRUE,'left',1);
$colModel['printable_name'] = array('Printable Name',120,TRUE,'left',1,'options' => array('type' => 'date'));
$colModel['iso3'] = array('ISO3',130, TRUE,'left',1, 'options' => array('type' => 'select', 'edit_options' => $options));
$colModel['numcode'] = array('Number Code',80, TRUE, 'right',1, 'options' => array('type' => 'select', 'edit_options' => ":All;AND:AND;KK:KK;RE:RE"));
$colModel['actions'] = array('Actions',80, FALSE, 'right',0);
/*
* Aditional Parameters
*/
$gridParams = array(
'width' => 'auto',
'height' => 400,
'rp' => 15,
'rpOptions' => '[10,15,20,25,40]',
'pagestat' => 'Displaying: {from} to {to} of {total} items.',
'blockOpacity' => 0.5,
'title' => 'Hello',
'showTableToggleBtn' => true
);
/*
* 0 - display name
* 1 - bclass
* 2 - onpress
*/
$buttons[] = array('Delete','delete','test');
$buttons[] = array('separator');
$buttons[] = array('Select All','add','test');
$buttons[] = array('DeSelect All','delete','test');
$buttons[] = array('separator');
//Build js
//View helpers/flexigrid_helper.php for more information about the params on this function
$grid_js = build_grid_js('flex1',site_url("/ajax"),$colModel,'id','asc',$gridParams,$buttons);
$data['js_grid'] = $grid_js;
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('flexigrid',$data);
}
function example ()
{
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('example',$data);
}
}
?>
When i type http://127.0.0.1/flexiadvanced/index.php/flexigrid browser give me a error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\flexiadvanced\system\application\models\ajax_model.php on line 34
this is the code of ajax_model.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Eye View Design CMS module Ajax Model
*
* PHP version 5
*
* #category CodeIgniter
* #package EVD CMS
* #author Frederico Carvalho
* #copyright 2008 Mentes 100Limites
* #version 0.1
*/
class Ajax_model extends Model
{
/**
* Instanciar o CI
*/
public function Ajax_model()
{
parent::Model();
$this->CI =& get_instance();
}
public function get_select_countries()
{
//Select table name
$table_name = "country";
//Build contents query
$separator = (string) ',';
//$this->db->select('concat(iso3, concat('. addcslashes($separator) .', iso3))')->from($table_name);
$query = $this->db->query("select concat(iso3, concat(':', iso3)) as name from country where iso3 is not null");
//Get contents
return $query->result_array();
}
public function get_countries()
{
//Select table name
$table_name = "country";
//Build contents query
$this->db->select('id,iso,name,printable_name,iso3,numcode')->from($table_name);
$this->CI->flexigrid->build_query();
//Get contents
$return['records'] = $this->db->get();
//echo $this->db->last_query();
//Build count query
$this->db->select('count(id) as record_count')->from($table_name);
$this->CI->flexigrid->build_query(FALSE);
$record_count = $this->db->get();
$row = $record_count->row();
//Get Record Count
$return['record_count'] = $row->record_count;
//Return all
return $return;
}
/**
* Remove country
* #param int country id
* #return boolean
*/
public function delete_country($country_id)
{
$delete_country = $this->db->query('DELETE FROM country WHERE id='.$country_id);
return TRUE;
}
}
?>
My database is called country and database table is called also country. This is information in CI_Folder\system\application\config
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "country";
$db['default']['dbdriver'] = "mysql";
Can you help me to write correct code inside flexigrid.php?
This is my code for CI_Folder\system\application\helpers\flexigrid_helper.php but is correct?
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Flexigrid CodeIgniter implementation
*
* PHP version 5
*
* #category CodeIgniter
* #package Flexigrid CI
* #author Frederico Carvalho (frederico#eyeviewdesign.com)
* #version 0.3
* Copyright (c) 2008 Frederico Carvalho (http://flexigrid.eyeviewdesign.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
if (! function_exists('build_grid_js'))
{
/**
* Build Javascript to display grid
*
* #param grid id, or the div id
* #param url to make the ajax call
* #param array with colModel info:
* * 0 - display name
* * 1 - width
* * 2 - sortable
* * 3 - align
* * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
* * 5 - hidden (TRUE or FALSE, default is FALSE. This index is optional.)
* #param array with button info:
* * 0 - display name
* * 1 - bclass
* * 2 - onpress
* #param default sort column name
* #param default sort order
* #param array with aditional parameters
* #return string
*/
function build_grid_js($grid_id,$url,$colModel,$sortname,$sortorder,$gridParams = NULL,$buttons = NULL)
{
//Basic propreties
$grid_js = '<script type="text/javascript">$(document).ready(function(){';
$grid_js .= '$("#'.$grid_id.'").flexigrid({';
$grid_js .= "url: '".$url."',";
$grid_js .= "dataType: 'json',";
$grid_js .= "sortname: '".$sortname."',";
$grid_js .= "sortorder: '".$sortorder."',";
$grid_js .= "usepager: true,";
$grid_js .= "useRp: true,";
//Other propreties
if (is_array($gridParams))
{
//String exceptions that dont have ' '. Must be lower case.
$string_exceptions = array("rpoptions");
//Print propreties
foreach ($gridParams as $index => $value) {
//Check and print with or without ' '
if (is_numeric($value)) {
$grid_js .= $index.": ".$value.",";
}
else
{
if (is_bool($value))
if ($value == true)
$grid_js .= $index.": true,";
else
$grid_js .= $index.": false,";
else
if (in_array(strtolower($index),$string_exceptions))
$grid_js .= $index.": ".$value.",";
else
$grid_js .= $index.": '".$value."',";
}
}
}
$grid_js .= "colModel : [";
//Get colModel
foreach ($colModel as $index => $value) {
$grid_js .= "{display: '".$value[0]."', ".($value[2] ? "name : '".$index."', sortable: true," : "")." width : ".$value[1].", align: '".$value[3]."'".(isset($value[5]) && $value[5] ? ", hide : true" : "")."},";
//If item is searchable
if ($value[4] != 0)
{
//Start searchitems var
if (!isset($searchitems))
$searchitems = "searchitems : [";
$options = '';
if (isset($value['options'])) {
if (isset($value['options']['type'])) {
$options = ", type : '".$value['options']['type']."'";
switch($value['options']['type']) {
case 'select' : $options .= ", editoptions : { value : '" . $value['options']['edit_options'] . "' }"; break;
case 'date' :
case 'radio' :
case 'checkbox' :
default :
}
}
}
if ($value[4] == 2)
$searchitems .= "{display: '".$value[0]."', name : '".$index."', isdefault: true " .$options. "},";
else if ($value[4] == 1)
$searchitems .= "{display: '".$value[0]."', name : '".$index."' " .$options. "},";
}
}
//Remove the last ","
$grid_js = substr($grid_js,0,-1).'],';
$searchitems = substr($searchitems,0,-1).']';
//Add searchitems to grid
$grid_js .= $searchitems;
//Get buttons
if (is_array($buttons))
{
$grid_js .= ",buttons : [";
foreach ($buttons as $index => $value) {
if ($value[0] == 'separator')
$grid_js .= "{separator: true},";
else
$grid_js .= "{name: '".$value[0]."', bclass : '".$value[1]."', onpress : ".$value[2]."},";
}
//Remove the last ","
$grid_js = substr($grid_js,0,-1).']';
}
//Finalize
$grid_js .= "}); })</script>";
return $grid_js;
}
}
?>
I solve looking here: https://github.com/sameersemna/ci-flexigrid
Just download codeigniter-flexigrid project, import database and set database credentials in database.php.
This is the live example from github project:
http://ci-flexigrid.sameershemna.com/countries
I like this solution because you do not need grocery-crud library but just simply codeigniter
cheers

how to remove error of undefined index in select n fetch query in php

i take the code of Bayesian from site http://www.ibm.com/developerworks/library/wa-bayes3/
i am not able to remove the error of undefined from the select query.
here is the code :
<?php
/**
* #package NaiveBayes
* #author Paul Meagher <paul#datavore.com>
* #license PHP License v3.0
* #version 0.2
*
* This class must be supplied with training example data, attribute names,
* and class names. Once this information is supplied, you can then invoke
* the learn and classify methods.
*/
class NaiveBayes {
/**
* Database table to use.
*/
var $table = null;
/**
* 1D array of attributes names. Attribute names should
* correspond to field names in the specified database
* table.
*/
var $attributes = array();
/**
* 1D array of attribute values to classify.
*/
var $attribute_values = null;
/**
* Specifies table column holding classification values.
*/
var $class = array();
/**
* Specifies allowable classification values.
*/
var $class_values = array();
/**
* 3D array containing joint frequency infomation about
* how class names and attribute names covary. Used to
* derive the likelihood array in the classify method.
*/
var $joint_frequency = array();
/**
* 1D array containing prior probability of each class name.
*/
var $priors = array();
/**
* 1D array containing likeliood of the data for each class.
*/
var $likelihoods = array();
/**
* 1D array containing the posterior probability of each class
* name given the supplied attribute values.
*/
var $posterior = array();
/**
* Denotes the number of training examples used for learning.
*/
var $n = 0;
/**
* When the classifier method is called, $predict is set to
* class name with the highest posterior probability.
*/
var $predict = null;
/**
* Set database table to use.
*/
function setTable($table)
{
$this->table = $table;
}
/**
* Set attribute columns to use. The attribute columns should
* correspond to fields in your database table.
*/
function setAttributes($columns)
{
foreach($columns as $column)
{
$this->attributes[] = $column;
}
}
/**
* Set classification column names to use.
*/
function setClass($column) {
$this->class = $column;
}
/**
* Set classification names to use.
*/
function setClassValues($values) {
foreach($values as $value) {
$this->class_values[] = $value;
}
}
function inimat($lr, $ur, $lc, $uc, &$a, $x){
for(; $lr<=$ur; $lr++)
for($j=$lc; $j<=$uc; $j++) $a[$lr][$j]=$x;
}
/**
* Learn the prior probability of each class and the
* joint frequency of each class and attribute.
*/
function learn()
{
// include connection file
include("connect.php");
// parse array
foreach ($this->attributes as $attribute)
// get field list
$field_list = substr($attribute, 0, -1);
// parse array
foreach ($this->class_values as $class) {
// make an sql query
$sql = "SELECT $field_list FROM " . $this->table . " WHERE " . $this->class . "='$class'";
// execute sql query
$result = mysql_query($sql);
$this->priors["$class"] = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
foreach ($this->attributes as $attribute) {
// if row attribute haven't any data then set default value
$attribute_value = isset($row[$attribute]) ? $row[$attribute] : 0;
$this->joint_frequency[$class][$attribute][$attribute_value]++;
}
}
}
}
/**
* Given a set of attribute values, this routine will
* predict the class they most likley belong to.
*/
function classify($attribute_values) {
$this->attribute_values = $attribute_values;
$this->n = array_sum($this->priors);
$this->max = 0;
foreach($this->class_values as $class) {
$counter = 0;
$this->likelihoods[$class] = 1;
foreach($this->attributes as $attribute) {
$attribute_value = $attribute_values[$counter];
$joint_freq = $this->joint_frequency[$class][$attribute][$attribute_value];
$likelihood = $joint_freq / $this->priors[$class];
if ($joint_freq > 0) {
$this->likelihoods[$class] = $this->likelihoods[$class] * $likelihood;
}
$counter++;
}
$prior = $this->priors[$class] / $this->n;
$this->posterior[$class] = $this->likelihoods[$class] * $prior;
if ($this->posterior[$class] > $this->max) {
$this->predict = $class;
$this->max = $this->posterior[$class];
}
}
}
/**
* Output the posterior probabilities that were computed by
* the classify method.
*/
function toHTML() {
foreach($this->class_values as $class) {
$equation = "P($this->class = ". $class ." | ";
$counter = 0;
foreach($this->attributes as $attribute) {
$attribute_value = $this->attribute_values[$counter];
$equation .= $attribute ."=". $attribute_value ." & ";
$counter++;
}
$equation = substr($equation, 0, -7);
$equation .= ") = ". $this->posterior[$class];
if ($class == $this->predict) {
$equation .= " <sup>*</sup>";
}
echo $equation ."<br />";
}
}
}
?>
it give error
Notice: Undefined index: q1 in C:\wamp\www\Bayes3\NaiveBayes.php on line 130 : $attribute_value = $row[$attribute];
Notice: Undefined index: 0 in C:\wamp\www\Bayes3\NaiveBayes.php on line 131 :
$this->joint_frequency[$class][$attribute][$attribute_value]++;
Notice: Undefined index: 1 in C:\wamp\www\Bayes3\NaiveBayes.php on line 150 :
$joint_freq = $this->joint_frequency[$class][$attribute][$attribute_value];
kindly help me in this
this can be done through isset function
You can use isset function:
<?php
/**
* Learn the prior probability of each class and the
* joint frequency of each class and attribute.
*/
function learn()
{
// include connection file
include("connect.php");
// parse array
foreach ($this->attributes as $attribute)
// get field list
$field_list = substr($attribute, 0, -1);
// parse array
foreach ($this->class_values as $class) {
// make an sql query
$sql = "SELECT $field_list FROM " . $this->table . " WHERE " . $this->class . "='$class'";
// execute sql query
$result = mysql_query($sql);
$this->priors["$class"] = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
foreach ($this->attributes as $attribute) {
// if row attribute haven't any data then set default value
$attribute_value = isset($row[$attribute]) ? $row[$attribute] : 0;
$this->joint_frequency[$class][$attribute][$attribute_value]++;
}
}
}
}
?>
To suppress the error you can add '#' symbol before the variable which is throwing the error.
Add # like
$attribute_value = #$row[$attribute];

PHP entity class generator

I am creating entity (of entity-view-controller)(in other words, model of MVC) classes which theoreticlly match the databse table I have. Is there a tool which reads mysql table and creates a model class code? (NOT on execution, a code output is required)
I expect an output like
class{
public $columnname1;
public $columnname2;
public $columnname3;
public $columnname4;
public $columnname5;
public $columnname6;
function __construct(&$columnname1, &$columnname2){...}
function insert(&$columnname1, &$columnname2){}
function delete(&$columnname1){}
...
}
A tool which would also create insert,update and delete by id functions would help me a lot.
The tool may be free or paid.
PDO can fetch results into an object.
Design a class which matches your database/query structure, and use PDO::FETCH_INTO to fetch the result set into an already instantiated object. Misread the question, my bad.
To generate the class itself from the database structure, there are several projects (I haven't tested, but this came up on a very simple search).
db2php
PHP MySQL class generator
The following code is what I've used for a long time to create PHP models for MySQL and DB2 tables. I've got stubs in place for MSSQL, PGSQL and SQLite but have never needed to complete them.
Here's the code generator class:
<?php
/**
* #license http://opensource.org/licenses/MIT The MIT License
* #version 1.0.0_20130220000000
*/
/**
* This class will generate PHP source code for a "model" that interfaces with
* a database table.
*
* #license http://opensource.org/licenses/MIT The MIT License
* #version 1.0.0_20130220000000
*/
class db_code_generator{
private $closing_tag;
private $columns;
private $database;
private $host;
private $password;
private $port;
private $table;
private $type;
private $username;
/**
* Constructor. By default we will try to connect to a MySQL database on
* localhost.
*
* #param string $database The name of the database the user wants to connect
* to.
*
* #param string $table The name of the table to generate code for.
*
* #param string $username The username we should use to connect to the
* database.
*
* #param string $password The password we need to connect to the database.
*
* #param string $host The host or server we will try to connect to. If the
* user doesn't give us a host we default to localhost.
*
* #param string $port The port we should try to connect to. Typically this
* will not be passed so we default to NULL.
*
* #param string $type The type of database we are connecting to. Valid
* values are: db2, mssql, mysql, pgsql, sqlite.
*/
public function __construct($database = NULL,
$table = NULL,
$username = NULL,
$password = NULL,
$host = 'localhost',
$type = 'mysql',
$port = NULL,
$closing_tag = TRUE){
$this->database = $database;
$this->table = $table;
$this->username = $username;
$this->password = $password;
$this->host = $host;
$this->port = $port;
$this->type = $type;
$this->closing_tag = $closing_tag;
}
/**
* Generate the code for a model that represents a record in a table.
*
* #return string The PHP code generated for this model.
*/
public function get_code(){
$this->get_data_definition();
$code = $this->get_file_head();
$code .= $this->get_properties();
$code .= $this->get_ctor();
$code .= $this->get_dtor();
$code .= $this->get_method_stubs();
$code .= $this->get_file_foot();
return $code;
}
/**
* Create the code needed for the __construct function.
*
* #return string The PHP code for the __construct function.
*/
private function get_ctor(){
$code = "\t/**\n";
$code .= "\t * Constructor.\n";
$code .= "\t *\n";
$code .= "\t * #param mixed \$id The unique id for a record in this table. Defaults to NULL\n";
if ('db2' === $this->type){
$code .= "\n\t * #param string \$library The library where the physical file resides. Defaults to LIBRARY\n";
}
$code .= "\t *\n";
$code .= "\t * #see base_$this->type::__construct\n";
$code .= "\t */\n";
if ('db2' === $this->type){
$code .= "\tpublic function __construct(\$id = NULL, \$library = 'LIBRARY'){\n";
$code .= "\t\tparent::__construct(\$id, \$library);\n";
}else{
$code .= "\tpublic function __construct(\$id = NULL){\n";
$code .= "\t\tparent::__construct(\$id);\n";
}
$code .= "\t}\n\n";
return $code;
}
/**
* Connect to the requested database and get the data definition for the
* requested table.
*/
private function get_data_definition(){
try{
switch ($this->type){
case 'db2':
$this->get_data_definition_db2();
break;
case 'mssql':
$this->get_data_definition_mssql();
break;
case 'mysql':
$this->get_data_definition_mysql();
break;
case 'pgsql':
$this->get_data_definition_pgsql();
break;
case 'sqlite':
$this->get_data_definition_sqlite();
break;
}
}catch(PDOException $e){
}
}
/**
* Get data definition information for a DB2 table.
*/
private function get_data_definition_db2(){
$con = new PDO("odbc:DRIVER={iSeries Access ODBC Driver};SYSTEM=$this->host;PROTOCOL=TCPIP", $this->username, $this->password);
$sql = "SELECT COLUMN_NAME, COLUMN_SIZE, COLUMN_TEXT, DECIMAL_DIGITS, ORDINAL_POSITION, TYPE_NAME FROM SYSIBM.SQLCOLUMNS WHERE TABLE_SCHEM = '". strtoupper($this->database) ."' AND TABLE_NAME = '". strtoupper($this->table) ."'";
$statement = $con->prepare($sql);
if ($statement->execute()){
while ($row = $statement->fetch()){
if (NULL !== $row['DECIMAL_DIGITS']){
$decimal = $row['DECIMAL_DIGITS'];
}else{
$decimal = NULL;
}
if ('DECIMAL' === $row['TYPE_NAME'] && NULL !== $row['DECIMAL_DIGITS'] && '0' !== $row['DECIMAL_DIGITS']){
$type = 'float';
}else if ('DECIMAL' === $row['TYPE_NAME']){
$type = 'integer';
}else{
$type = strtolower($row['TYPE_NAME']);
}
if ('1' === $row['ORDINAL_POSITION']){
$key = 'PRI';
}else{
$key = NULL;
}
$this->columns[$row['COLUMN_NAME']] = array('allow_null' => TRUE,
'decimal' => $decimal,
'default' => NULL,
'extra' => NULL,
'key' => $key,
'length' => $row['COLUMN_SIZE'],
'name' => $row['COLUMN_NAME'],
'text' => $row['COLUMN_TEXT'],
'type' => $type);
}
ksort($this->columns);
}
}
/**
* Get data definition information for a MS SQL table.
*/
private function get_data_definition_mssql(){
return "The code for generating MS SQL models is not yet implemented.\n";
}
/**
* Get data definition information for a MySQL table.
*/
private function get_data_definition_mysql(){
$dsn = "mysql:host=$this->host;";
if (NULL !== $this->port){
$dsn .= "port=$this->port;";
}
$dsn .= "dbname=$this->database";
$con = new PDO($dsn, $this->username, $this->password);
$sql = "SHOW COLUMNS FROM $this->table";
$statement = $con->prepare($sql);
if ($statement->execute()){
while ($row = $statement->fetch()){
$this->columns[$row['Field']] = array('allow_null' => $row['Null'],
'decimal' => NULL,
'default' => $row['Default'],
'extra' => $row['Extra'],
'key' => $row['Key'],
'length' => NULL,
'name' => $row['Field'],
'text' => NULL,
'type' => $row['Type']);
}
ksort($this->columns);
}
}
/**
* Get data definition information for a PostgreSQL table.
*/
private function get_data_definition_pgsql(){
return "The code for generating PostgreSQL models is not yet implemented.\n";
}
/**
* Get data definition information for a SQLite table.
*/
private function get_data_definition_sqlite(){
return "The code for generating SQLite models is not yet implemented.\n";
}
/**
* Create the code needed for the __destruct function.
*
* #return string The PHP code for the __destruct function.
*/
private function get_dtor(){
$code = "\t/**\n";
$code .= "\t * Destructor.\n";
$code .= "\t */\n";
$code .= "\tpublic function __destruct(){\n";
$code .= "\t\tparent::__destruct();\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code found at the end of the file - the closing brace, the
* ending PHP tag and a new line. Some PHP programmers prefer to not have a
* closing PHP tag while others want the closing tag and trailing newline -
* it probably just depends on their programming background. Regardless it's
* best to let everyone have things the way they want.
*/
private function get_file_foot(){
$code = '';
if ($this->closing_tag){
$code .= "}\n?>\n";
}else{
$code .= '}';
}
return $code;
}
/**
* Generate the code found at the beginning of the file - the PHPDocumentor
* doc block, the require_once for the correct base class and the class name.
*
* #return string The code generated for the beginning of the file.
*/
private function get_file_head(){
$code = "<?php\n";
$code .= "/**\n";
$code .= " * Please enter a description of this class.\n";
$code .= " *\n";
$code .= " * #author XXX <XXX#domain.com>\n";
$code .= " * #copyright Copyright (c) ". date('Y') ."\n";
$code .= " * #license http://www.gnu.org/licenses/gpl-3.0.html GPLv3\n";
$code .= " * #version ". date('Ymd') ."\n";
$code .= " */\n\n";
$code .= "require_once('base_$this->type.php');\n\n";
$code .= "class ". strtolower($this->table) ." extends base_$this->type{\n";
return $code;
}
/**
* Generate the code for a delete method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_delete(){
$code = "\t/**\n";
$code .= "\t * Override the delete method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param mixed \$id The unique record ID to be deleted.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully deleted from the table, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function delete(\$id){\n";
$code .= "\t\treturn parent::delete(\$id);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code for an insert method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_insert(){
$code = "\t/**\n";
$code .= "\t * Override the insert method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param array \$parms An array of data, probably the \$_POST array.\n";
$code .= "\t * #param bool \$get_insert_id A flag indicating if we should get the autoincrement value of the record just created.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully inserted into the table, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function insert(\$parms, \$get_insert_id = FALSE){\n";
$code .= "\t\treturn parent::insert(\$parms, \$get_insert_id);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code for an update method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_update(){
$code = "\t/**\n";
$code .= "\t * Override the update method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param array &\$parms An array of key=>value pairs - most likely the \$_POST array.\n";
$code .= "\t *\n";
$code .= "\t * #param integer \$limit The number of records to update. Defaults to NULL.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully updated, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function update(\$parms, \$limit = NULL){\n";
$code .= "\t\treturn parent::update(\$parms, \$limit);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Create method stubs for create, delete and update.
*
* #return string The PHP code for these stubs.
*/
private function get_method_stubs(){
$code = $this->get_method_stub_delete();
$code .= $this->get_method_stub_insert();
$code .= $this->get_method_stub_update();
return $code;
}
private function get_properties(){
$code = '';
if (count($this->columns)){
foreach ($this->columns AS $index => $col){
$code .= "\t/**\n";
if (NULL !== $col['text']){
$code .= "\t * $col[text]\n";
}else{
$code .= "\t * Description\n";
}
$code .= "\t * #var ". $col['type'];
if (NULL !== $col['length']){
$code .= " ($col[length]";
if (NULL !== $col['decimal']){
$code .= ",$col[decimal]";
}
$code .= ")";
}
$code .= "\n\t */\n";
$temp_name = str_replace('#', '_', $col['name']);
$code .= "\tpublic \$$temp_name;\n\n";
}
}
return $code;
}
}
?>
and here's a simple page to use it:
<?php
/**
* #license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
* #version 1.0.0_20130220000000
*/
require_once('db_code_generator.php');
$table_type = array();
$table_type['db2'] = 'DB2/400 (db2)';
$table_type['mssql'] = 'Microsoft SQL Server (mssql)';
$table_type['mysql'] = 'MySQL (mysql)';
$table_type['pgsql'] = 'PostGRESQL (pgsql)';
$table_type['sqlite'] = 'SQLite (sqlite)';
$database = (isset($_POST['database'])) ? $_POST['database'] : 'my_database';
$host = (isset($_POST['host'])) ? $_POST['host'] : 'localhost';
$username = (isset($_POST['username'])) ? $_POST['username'] : 'root';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$table = (isset($_POST['table'])) ? $_POST['table'] : '';
$type = (isset($_POST['type'])) ? $_POST['type'] : 'mysql';
$library = (isset($_POST['library'])) ? $_POST['library'] : 'LIBRARY';
$file = (isset($_POST['file'])) ? $_POST['file'] : 'STATES';
//---------------------------------------------------------------------------
?>
<div class="data_input">
<form action="" method="post">
<fieldset class="top">
<legend>Code Generator</legend>
<label for="host">Hostname or IP:
<input id="host" maxlength="32" name="host" tabindex="<?php echo $tabindex++; ?>" title="Enter the database host name" type="text" value="<?php echo $host; ?>" />
</label>
<br />
<label for="username">Username:
<input id="username" maxlength="32" name="username" tabindex="<?php echo $tabindex++; ?>" title="Enter the database username" type="text" value="<?php echo $username; ?>" />
</label>
<br />
<label for="password">Password:
<input id="password" maxlength="32" name="password" tabindex="<?php echo $tabindex++; ?>" title="Enter the database password" type="password" value="<?php echo $password; ?>" />
</label>
<br />
<label for="type">Type:
<select id="type" name="type" tabindex="<?php echo $tabindex++; ?>">
<?php
foreach ($table_type AS $key=>$value){
echo('<option ');
if ($key == $type){
echo 'selected="selected" ';
}
echo 'value="'. $key .'">'. $value .'</option>';
}
?>
</select>
</label>
<br />
</fieldset>
<fieldset class="top">
<legend>PostGRESQL/MSSQL/MySQL Parameters</legend>
<label for="database">Database:
<input id="database" maxlength="100" name="database" tabindex="<?php echo $tabindex++; ?>" title="Enter the database name" type="text" value="<?php echo $database; ?>" />
</label>
<br />
<label for="table">Table:
<input id="table" maxlength="100" name="table" tabindex="<?php echo $tabindex++; ?>" title="Enter the table name" type="text" value="<?php echo $table; ?>" />
</label>
<br />
</fieldset>
<fieldset class="top">
<legend>DB2 Parameters</legend>
<label for="library">Library:
<input id="library" maxlength="10" name="library" tabindex="<?php echo $tabindex++; ?>" title="Enter the library name" type="text" value="<?php echo $library; ?>" />
</label>
<br />
<label for="file">Physical File:
<input id="file" maxlength="10" name="file" tabindex="<?php echo $tabindex++; ?>" title="Enter the file name" type="text" value="<?php echo $file; ?>" />
</label>
<br />
</fieldset>
<fieldset class="bottom">
<button tabindex="<?php echo $tabindex++; ?>" type="submit">Generate!</button>
</fieldset>
</form>
</div>
<?php
if (isset($_POST['host'])){
if ('db2' == $_POST['type']){
$_POST['database'] = strtoupper($_POST['library']); // Library
$_POST['table'] = strtoupper($_POST['file']); // Physical file
$_POST['host'] = 'db2_host';
$_POST['username'] = 'db2_username';
$_POST['password'] = 'db2_password';
}
$object = new db_code_generator($_POST['database'], $_POST['table'], $_POST['username'], $_POST['password'], $_POST['host'], $_POST['type']);
echo('<textarea rows="75" style="margin-left : 50px; width : 90%;" onfocus="select()">'. $object->get_code() .'</textarea>');
}
?>
I understand you're looking for a ORM kind of a thing.
hope this helps
http://www.doctrine-project.org/
http://propelorm.org/
What about symfony? It does exactly what you say and you get a beastly good framework to go with it.
symfony 'compiles' classes for you based on a data model that you supply. It will make sure that compiled classes and MySQL database structure are in sync.
This approach is favorable over a Reflection based approach as it's simply too slow.
For what it's worth, Rafael Rocha shares code here.
Still, I strongly propose to use an ORM. Transforming MySQL structure back to a database-abstraction layer is anything but good...
Try this
https://github.com/rcarvello/mysqlreflection
A useful utility I built for the Object Relation Mapping of MySQL databases.
The utility generates automatically PHP classes for any tables of a given database schema.
The package is extracted from my personal PHP Web MVC Framework.
Yes, Doctrine is what you need.
Run a command, and you get all your tables' metadata in XML or YML format(choice is yours)
$ php app/console doctrine:mapping:convert xml ./src/Bundle/Resources/config/doctrine/metadata/orm --from-database --force
Once you generate the Metadata, command Doctrine to import the schema to build related entity classes you need. You will find all GET and SET functionality(read SELECT, UPDATE and INSERT) inside.
1.$ php app/console doctrine:mapping:import Bundle annotation
2.$ php app/console doctrine:generate:entities Bundle
Read details with Example here
Fat free framework allows you to work with existing tables using code like:
$user=new DB\SQL\Mapper($db,'users');
// or $user=new DB\Mongo\Mapper($db,'users');
// or $user=new DB\Jig\Mapper($db,'users');
$user->userID='jane';
$user->password=md5('secret');
$user->visits=0;
$user->save();
The code above creates new record in users table
I have written a PHP code which will automatically detect all the databases in MYSQL database, on selecting any of the database all of its related tables are loaded. You can select all the tables or any respective table to generate the Modal Class.
The following is the link to my repository
https://github.com/channaveer/EntityGenerator
This will automatically create Entity folder and dump all the entity class into that folder.
NOTE - Currently only supported for MYSQL
Hope it helps. Happy Coding!
I think you should make itout on your on. Every project and requirement of Model Code is different in my opinion. Two mysql queries will keep you in ease.
SHOW TABLES FROM db_NAME //this gives the table listing, so its Master Looper
DESC tbl_name //detail query that fetches column information of given table
DESC tbl_name will give Field, Type, Null, Key, Default and Extra Columns.
e.g. values seperated in pipes (|):
Id | int(11) | NO | PRI | NULL | auto_increment |
I followed these to make Model, controller and Viewer files supporting CRUD operation in Codeigniter 2 way back. It worked just fine.

joomla 1.7 : overriding pagination.php not working

I installed joomla 1.7(window/xampp/php 5.3) and my current template is beez_20. I have to override the pagination.php and to do so I copied the pagination.php from
\libraries\joomla\html
to
\templates\beez_20\html. When I reload the home page, I am getting a broken template as in the following picture.
I get the normal page when I remove the pagination.php from the html folder. I believe this is the correct method to override the pagination.php
what is missing ? need to change any configuration ? please post your comments
Thanks in advance
I do belive this is the correct way to do it...
Here is a pagnation.php for you to try with (works for me):
<?php
// no direct access
defined('_JEXEC') or die('Restricted access');
/**
* This is a file to add template specific chrome to pagination rendering.
*
* pagination_list_footer
* Input variable $list is an array with offsets:
* $list[limit] : int
* $list[limitstart] : int
* $list[total] : int
* $list[limitfield] : string
* $list[pagescounter] : string
* $list[pageslinks] : string
*
* pagination_list_render
* Input variable $list is an array with offsets:
* $list[all]
* [data] : string
* [active] : boolean
* $list[start]
* [data] : string
* [active] : boolean
* $list[previous]
* [data] : string
* [active] : boolean
* $list[next]
* [data] : string
* [active] : boolean
* $list[end]
* [data] : string
* [active] : boolean
* $list[pages]
* [{PAGE}][data] : string
* [{PAGE}][active] : boolean
*
* pagination_item_active
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* pagination_item_inactive
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* This gives template designers ultimate control over how pagination is rendered.
*
* NOTE: If you override pagination_item_active OR pagination_item_inactive you MUST override them both
*/
function pagination_list_footer($list)
{
// Initialize variables
$lang =& JFactory::getLanguage();
$html = "<div class=\"list-footer\">\n";
if ($lang->isRTL())
{
$html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>";
$html .= $list['pageslinks'];
$html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>";
}
else
{
$html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>";
$html .= $list['pageslinks'];
$html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>";
}
$html .= "\n<input type=\"hidden\" name=\"limitstart\" value=\"".$list['limitstart']."\" />";
$html .= "\n</div>";
return $html;
}
function pagination_list_render($list)
{
// Initialize variables
$lang =& JFactory::getLanguage();
$html = "<div class=\"pagination\"><ul>";
// Reverse output rendering for right-to-left display
if($lang->isRTL())
{
$html .= "<li class=\"pagination-start\">".$list['start']['data']."</li>";
$html .= "<li class=\"pagination-prev\">".$list['previous']['data']."</li>";
$list['pages'] = array_reverse( $list['pages'] );
foreach( $list['pages'] as $page ) {
if($page['data']['active']) {
// $html .= '<strong>';
}
$html .= "<li>".$page['data']."</li>";
if($page['data']['active']) {
// $html .= '</strong>';
}
}
$html .= "<li class=\"pagination-next\">".$list['next']['data']."</li>";
$html .= "<li class=\"pagination-end\">".$list['end']['data']."</li>";
// $html .= '«';
}
else
{
foreach( $list['pages'] as $page )
{
if($page['data']['active']) {
// $html .= '<strong>';
}
$html .= "<li>".$page['data']."</li>";
if($page['data']['active']) {
// $html .= '</strong>';
}
}
}
$html .= "</ul></div>";
return $html;
}
?>
You should not override the entire pagination.php in the manner you tried. You can only override certain functions. The reason you are seeing this page is because if you copied the entire pagination.php file with out changing anything, so you are re-declaring the JPagination class and you can't do that.
When you are try to make changes to the pagination.php you should only re-write the functions you wish to override not copy the entire file.
Please check out this article it's a little dated but the information still applies even in J! 2.5
http://docs.joomla.org/Understanding_Output_Overrides

Categories