PDO temporary persistent connection - php

I have a function for a forum that I'm working on. One of the things it does is return a result back to the ajax call and redirect
function inv_post_create_topic() {
global $db;
if($_POST['postas']=='support') {
$author = '0';
}
else { $author = $_POST['poster']; }
$query = <<<SQL
INSERT INTO inv_forums(parent,subject,body,author,replies,views,enabled,posted,posttype)
VALUES(:parent,:subject,:body,:author,:replies,:views,:enabled,:posted,:posttype)
SQL;
$resource = $db->db->prepare( $query );
$resource->execute( array (
':parent' => $_POST['cat'],
':subject' => $_POST['title'],
':body' => $_POST['post'],
':author' => $author,
':replies' => '0',
':views' => '0',
':enabled' => '1',
':posted' => date('F j, Y | h:i A'),
':posttype' => $_POST['flag'],
));
echo "viewPage.php?id=".inv_get_post_redirect()."&forum=".$db->db->lastInsertId()."";
}
With this function it pulls the id with the view posts function and the last inserted ID (IE The forum just created) and then returns that data and redirects you to the newly created forum. What I was wondering is if it is at all possible to create a temporary persistent connection. It was working fine on my server,but always returned forum=0 on my live server.After some research it has to do with persistent connections being allowed. My webhost said that's something I can set up within my config.php file, but they also let me know that the server only allows 24 concurrent connections, so what I'm trying to find out is if I can take that connection, make it persistent to pull the last id submitted and then close up afterwards.

Related

QuickBase foreach insert

I'm having an issue using the Quickbase API to perform the following:
SELECT 1, 2, 3 FROM table AA that has column BB = 1
foreach record {
Insert 1, 2, 3 into table ZZ.
}
function add_children($opportunity_id) {
global $config;
$qbc = new QuickBase($_SESSION['qb_username'] ,
$_SESSION['qb_password'],
true,
$config['AA'],
$config['debug'],
$config['app_token']);
$xml = $qbc->do_query("{'" . $config['AA'] . "'.EX.''}", 0, 0, 'a', 0, '', '');
$records = array();
foreach($xml->record as $record) {
$r = array();
$r['record_id'] = $record->record_id_;
$r['account_number'] = $record->account_number;
$records[] = $r;
$xml = $qbc->add_record($records[]);
}
}
First, I'm assuming that you're using this PHP SDK by QuickbaseAdmirer https://github.com/QuickbaseAdmirer/QuickBase-PHP-SDK. There are a few potential problems with your code.
Double check that your constructor is correct. Unless you've modified it, the Quickbase constructor in the SDK (again that I'm assuming you're using) takes user name, password, xml, database id, and then token in that order. Whatever value is in $config['debug'] may be taken as the token and the value of $config['app_token'] may be taken as your realm. Also, $config['AA'] as used in the constructor should be a string of random seeming characters like "bbqn1y5qv". Here's the constructor in the SDK for reference:
public function __construct($un, $pw, $usexml = true, $db = '', $token
= '', $realm = '', $hours = '')
Your query $xml = $qbc->do_query("{'" . $config['AA'] . "'.EX.''}", 0, 0, 'a', 0, '', ''); is not returning any records because $config['AA'] is both being used as your DBID (in the constructor) and your field ID in the query. The DBID must be a string and the field ID must be an integer that corresponds to the field you're making the query for. For example, if you wanted to return records created today your query would be '{1.IR.today}' because 1 is always the field ID for date created. It's also not returning any records because the SDK requires queries be passed as an array of arrays. So, my records created today query needs to be rewritten as:
$query= array(
array(
'fid' => '1',
'ev' => 'IR'),
'cri' => 'today'),
);
You'll also need to pass a string of period separated values to the clist parameter of the method or leave it blank for the table defaults. For example, if I wanted to get the date created and record ID for all records in this table sorted by date ascending, I would use this:
$query= array(
array(
'fid' => '3',
'ev' => 'GT'),
'cri' => '0'),
);
$xml = $qbc->do_query($query, '', '', '1.3', '1', '', 'sortorder-A');
You can read up more on the Quickbase API, and do_query specifically, here http://www.quickbase.com/api-guide/index.html#do_query.html
The add record API call takes pairs of field IDs and values. The SDK handles that by taking an array of arrays with 'fid' and 'value' pairs. Assuming you want to put the value of $record->record_id_ in field #37 and $record->account_number in field #30 your code should look like this:
foreach($xml->record as $record) {
$records= array(
array(
'fid' => '37', //Whatever field you want to store the value to
'value' => $record->record_id_),
array(
'fid' => '30',
'value' => $record->account_number),
);
$xml = $qbc->add_record($records);
}
Throw in a print_r($xml); at the end and you can see any response from Quickbase for debugging. You should get something like this for a success:
SimpleXMLElement Object ( [action] => API_AddRecord [errcode] => 0 [errtext] => No error [rid] => 81 [update_id] => 1436476140453 )
The way your code is presented, you may not get the results you expect. Your do query and add record method calls are performed on the same table and that isn't normally what someone would want. Usually, the goal is to perform a do query on one table and then use that data to add records in a different table. If that's the case, you'll need to change the database ID in your $qbc object before you preform the add record call. This is easy enough to do with $qbc->set_database_table('DBID'); where DBID is the target table ID (which should be a string of random seeming characters like "bbqn1y5qv").
Best of luck!

how to use sql NOW( ) function in laravel

I have used sql's now() function several times in normal query in php db connectivity...
But in laravel it does not displays anything and also the data is not inserted
the code I am using is:
$exercise = Exercise::insert(
array( 'fk_users_id' => '1',
'fk_equipments_id' => $equipment,
'muscular_group' => $muscular,
'exercise_name' => $postedContent['exercise_name'],
'exercise_type' => $postedContent['type'],
'Status' => '1',
'DateCreated' => 'NOW( )',
'DateModified' => 'NOW( )')
);
it stores the data into the database but the time in not stored in any of the columns
at first my method was:
$exerciseDetails = Input::all();
$exercise = Exercise::create($exerciseDetails);
the above method updates date and time itself and worked fine for other controllers but now I am having a problem of having a check box checked array in my post so it throws error
is there any other method in laravel to do this ??
Laravel comes with created_at and updated_at timestamp fields by default, which it keeps updated by itself.
http://laravel.com/docs/4.2/eloquent#timestamps
$now = DB::raw('NOW()');
$now variable can use in insert like
$user = new User;
$user->name = $name;
$user->created_at = $now;
use this
Carbon::now() instead 'NOW( )'
or use DB::raw('NOW()') instead 'NOW()'
You could be looking to direct query to get MySQL DB current Time.
You can go like this;
$currentDBtime = DB::select( 'select NOW() as the_time' );
$currentDBtime[0]->the_time;

Inserting rows to a table depending on date

This is my function to insert new rows to a table, depending on the date. I want to avoid duplication of rows if one already exists. This function basically inserts November, 2014 as mwf_month, so mwf_student_id and mwf_month pairs are unique for the row. What modification should I do to avoid this kind of duplication?
public function month_wise_due($grade_due, $new_due, $id, $remaining) {
$now1 = time();
$now = date('F, Y', $now1);
$store = array(
'mwf_month' => $now,
'mwf_previous' => $remaining,
'mwf_due' => $grade_due,
'total_due' => $new_due,
'mwf_student_id' => $id,
'mwf_pay_day' => 'Not Yet Paid',
'mwf_payment' => 0,
'mwf_diff' => $new_due
);
$this->db->trans_start();
$this->db->insert('mwf', $store);
$this->db->trans_complete();
}
The right way is to update your database table by adding "unique key" on two fields "mwf_month+mwf_student_id". The SQL command to do it is:
ALTER TABLE `mwf` ADD UNIQUE `unique_month_student`(mwf_month,mwf_student_id);
Then, possible duplicity would end with SQL error you can catch. You can also suppress the exception with 'ignore' statement or use 'replace' method instead of 'insert'.
If you don't have needed privileges on the table, you would need to simply check whether the pair exist with separate sql call before inserting new record.
I have found a solution from some where else without altering the table, it seems good to me.
$now1 = time();
$now = date('F, Y', $now1);
$row_exists = "SELECT * FROM mwf WHERE mwf_month = '" . $now."' AND mwf_student_id = '" . $id."' LIMIT 1";
if ( ! $this->db->simple_query($row_exists)) {
$store = array(
'mwf_month' => $now,
'mwf_previous' => $remaining,
'mwf_due' => $grade_due,
'total_due' => $new_due,
'mwf_student_id' => $id,
'mwf_pay_day' => 'Not Yet Paid',
'mwf_payment' => 0,
'mwf_diff' => $new_due
);
$this->db->trans_start();
$this->db->insert('mwf', $store);
$this->db->trans_complete();
}

PDO statements not executing?

I'm trying to use PDO (php data object) to execute queries in a .php file like so:
global $db, $table;
$sth = $db->prepare('INSERT INTO $table(user, timerun, magexp, crimsons, blues, golds, greens) VALUES (:user,:timerun,:magexp,:crimsons,:blues,:golds,:greens) ON DUPLICATE KEY UPDATE timerun=timerun+:timerun, magexp=magexp+:magexp, crimsons=crimsons+:crimsons, blues=blues+:blues, golds=golds+:golds, greens=greens+green');
$sth->execute(array(':user' => $user, ':timerun' => $timerun, ':magexp' => $magexp, ':crimsons' => $cr, ':blues' => $bl, ':golds' => $go, ':greens' => $gr));
echo "success";
However, it doesn't actually update my table. I don't get an error or anything.
Am I doing something wrong or is PDO not supported? The PDO docs said "Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional database code using a table type that does not support transactions, MySQL will pretend that a transaction was initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions."
I'm fairly certain my MySQL tables do support transactions, because the regular 'mysql_query' does work.
Thanks.
I'm not sure about Your code, You have variable inside single quoted string it will not work, You should use double quotation like this:
global $db, $table;
$sth = $db->prepare("INSERT INTO $table(user, timerun, magexp, crimsons, blues, golds, greens) VALUES (:user,:timerun,:magexp,:crimsons,:blues,:golds,:greens) ON DUPLICATE KEY UPDATE timerun=timerun+:timerun, magexp=magexp+:magexp, crimsons=crimsons+:crimsons, blues=blues+:blues, golds=golds+:golds, greens=greens+green:");
$sth->execute(array(':user' => $user, ':timerun' => $timerun, ':magexp' => $magexp, ':crimsons' => $cr, ':blues' => $bl, ':golds' => $go, ':greens' => $gr)); echo "success";
For security:
First of all i would create some associative array with all possible tables from project as keys and then check if table from variable exists as array index using if(isset($validTables[$table])) and then continue the query. For example
<?php
$validTables = array('foo' => true, 'bar' => true, 'other' => true);
if(isset($validTables[$table]))
{
// query logic here
}
else throw new Exception(sprintf('Security error %s table not exists', $table));
Check this code because i wrote it without parsing with php

Zend Framework Database Insert Issue

I'm starting out using the Zend Framework and have created a suitable model which saves data back to a database table. The issue I am having is that the sql statement is trying to insert '?' as the value for each column in the database. I have created the following save function which passes an array of data to the DBtable adapter functions:
public function save() {
$data = $this->getData();
if ($data['pageId']==0) {
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('pageId = ?' => $data['pageId']));
}
}
This seems to go through the appropriate motions but the item is not added to the database and the sql statement within MySql logs looks something like:
insert into DB_Table ('pageId','title','body') values ('?', '?', '?');
Not quite sure where this is falling down, any pointers would be gratefully received.
Thanks
Data should be in next format:
$data = array(
'pageId' => 1,
'title' => 'title',
'body' => 'body'
);
Are you sure that $this->getDbTable() returns your db adapter?
Try to use:
$db = new Zend_Db_Table('table_name');
$db->insert($data);

Categories