How can I unserialize data from database after it was serialized - sql

try {
if (isset($_SESSION['list']) > 0) {
$test = serialize($_SESSION["list"]);
$sQuery = "INSERT INTO table (id, date) VALUES ('$test', NOW())";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
}
else {
echo 'No data';
}
}
In my database I see this:
1 a:1:{i:1;s:1:"5";} 2011-12-21
The $_SESSION['list'] stores ID and the QUANTITY.
The data a:1:{i:1;s:1:"5";} is as follow: i=id, s=id:"quantity", I read this as id=1 and the quantity of id=1 is 5, am I correct?
Now I want select the data and unserialize the array.
try {
$sQuery = "SELECT * FROM table";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetchALL(PDO::FETCH_ASSOC)) {
$id = unserialize($aRow['id']);
foreach($id as $id => $quantity) {
echo $id.', ';
}
}
}
catch(PDOException $e) {
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
What am I doing wrong or what can I do so I can select the ID and QUANTITY from database?

The serialization/deserialization part looks fine to me, but the $oStmt->fetchALL( I think should be $oStmt->fetch(, and in foreach($id as $id => $quantity) { use another variable to hold the key instead of id, like foreach($id as $key => $quantity) {.
Also, you don't echo the quantity anywhere. Change echo $id.', '; to echo $key.' '.$quantity; or something and tell us what the output is so we can help further.

Related

How can I bind correctly my variables to my tokens?

I can't figure out what causes this error, I'm burned out already. I can't figure out how to solve this.
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter
number: number of bound variables does not match number of tokens in C:\wamp64\www\myproject-dev\public\viajes\orden_mantenimiento\controller.php on line 77
This happens when I try to execute my create method so heres the whole method:
if ($type == 'create') {
$Records = $request->models;
foreach ($Records as $rec) {
if (isset($request->pky)) {
$fky = $request->fky;
$rec->$fky = $request->pky;
}
$aError = Validate($rec);
$statement = $conn->prepare('INSERT INTO order (id, idVehiculo, idTipo, fecha, kilometraje, horaIn, horaSal, proyecto, jefeProy, aprobadoPor, descripcion)
VALUES (:id, :idVehiculo, idTipo, :fecha, :kilometraje, :horaIn, :horaSal, :proyecto, :jefeProy, :aprobadoPor, descripcion)');
$statement->bindValue(':id', $rec->id);
$statement->bindValue(':idVehiculo', $rec->idVehiculo);
$statement->bindValue(':idTipo', $rec->idTipo);
$statement->bindValue(':fecha', $rec->fecha);
$statement->bindValue(':kilometraje', $rec->kilometraje);
$statement->bindvalue(':horaIn', $rec->horaIn);
$statement->bindvalue(':horaSal', $rec->horaSal);
$statement->bindValue(':proyecto', $rec->proyecto);
$statement->bindValue(':jefeProy', $rec->jefeProy);
$statement->bindValue(':aprobadoPor', $rec->aprobadoPor);
$statement->bindValue(':descripcion', $rec->descripcion);
if (!$statement->execute()) { // **========================== THIS IS LINE 77 ===================**
$aErrInfo = $statement->errorInfo();
$aError = array();
$aError[] = array('success' => false);
$aError[] = array('msg' => $aErrInfo[1]);
$aError[] = array('error' => $aErrInfo[2]);
$respuesta["errors"] = $aError;
echo "statement error".$respuesta;
} else {
$rec->id = $conn->lastInsertId();
$respuesta["data"] = $rec;
echo "Data bound.";
}
} else {
$respuesta["errors"] = $aError;
echo "ERROR";
}
}
}
Thanks a lot in advance.

ModX PDO SQL returns empty array

I pretty much copy/pasted this from the ModX RTFM:
$results = $modx->query("SELECT * FROM `saved_jobs` WHERE `job_id` = $job_id AND `user_id` = $user");
if (!is_object($results)) {
return 'No result!';
}
else {
$r = $results->fetchAll(PDO::FETCH_ASSOC);
echo $r;
echo "<br>count " . count($r);
print_r($r);
}
But even though there are no records in the database I still get the 'else' occurring. The line echo "count " . count($r); produces the output: count 0
Does anyone know whats going on and how to fix it?
If your query is successful, you still create an object with your first statement.
take a peek [also from the docs]:
$result = $modx->query("SELECT * FROM modx_users WHERE id='blah'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return 'No result!';
}
else {
$row = $result->fetch(PDO::FETCH_ASSOC);
return 'Result:' .print_r($row,true);
}
What you want to do is find out if the object actually contains a result set:
$result = $modx->query("SELECT * FROM modx_users WHERE id='1'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return FALSE;
}
if(sizeof($result) > 0){
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo'Result:' .print_r($row,true);
}
}
so you can either test the size of the $result variable or just run the while loop & test if it has any data as well.

MODx querying custom db table

See the code below. I'm trying to get some data from a database is modx. The data is there, meaning, when i query the database in phpmyadmin, i get results. I can't figure out why it doesnt work in modx.
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$stmt = $modx->prepare($sql);
$stmt->execute();
// Put data in array
$order_data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($order_data == '') {
return 'Resultset empty for user '. $user_id.'.<br />'.$sql;
} else {
return 'Data found!';
}
Perhaps try using xPDO:
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$c = new xPDOCriteria($modx,$sql);
if ($c->stmt && $c->stmt->execute()) {
$order_data = $c->stmt->fetch(PDO::FETCH_ASSOC);
var_dump($order_data);
}
You need to loop through your output, the result will be an array of arrays.
The below example will return the data and present it according to a chunk format
<?php
$sql = "SELECT * FROM `table_name`";
$query = $modx->query($sql);
$rows = array();
if ($query) {
// loop through the result set and inspect one row at a time
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
$output .= $modx->getChunk($tpl,$row);
}
}
$output = "<table border=\"1\" cellpadding=\"5\" >
<th>ID</th><th>row1_Head</th><th>row2_Head</th><th>row3_Head</th><th>row4_Head</th><th>row5_Head</th>
$output</table>";
return $output;
This is an example of the chunk:
<tr>
<td>[[+id]]</td> <td>[[+row1]]</td> <td>[[+row2]]</td> <td>[[+row3]]</td> <td>[[+row4]]</td> <td>[[+row5]]</td>
</tr>
Now in a resource call your snippet like
[[!Snippet_name? &tpl=`chunk_name`]]
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
Assume your schema is like
<?xml version="1.0" encoding="UTF-8"?>
<model package="your_package_name" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1">
<object class="Orders" table="orders" extends="xPDOSimpleObject">
<field key="order_no" dbtype="varchar" precision="255" phptype="string" null="false" />
<!-- and everything else below -->
</object>
<!-- and everything else below -->
</model>
What you need to do is as simple as this:
$modx->addPackage('your_package_name'); // Add your table schema to MODX object
$orders = $modx->getCollection('Orders'); // class's name, not table's name
$output = '';
if ($orders){
$outputArray = array();
foreach ($orders as $order) {
$orderArray = $order->toArray();
$outputArray[] = $modx->getChunk('your_row_chunk_name', $orderArray);
}
$wrapper = array(
'orders' => #implode("\n", $outputArray);
);
$output = $modx->getChunk('your_wrapper_chunk_name', $wrapper);
}
return $output;

Magento API, Return Orders with NULL values

Using the magento api version 1 and soap.
Need to return all orders with 'coupon_code'=> NULL
The call I'm attempting:
$order_listAR = $proxy->call($sessionId, 'sales_order.list', array(array('coupon_code'=>array('null'=>'null'))));
The ouput I want returned is this:
array(237) {
["state"]=>
string(8) "complete"
["status"]=>
string(8) "complete"
["coupon_code"]=> NULL
So far this seems to work properly, but I'm not sure if ('null'=>'null') is the proper way to find NULL values in the array. Can someone explain why this works, and, or if this is the correct syntax? I don't have any margin for error on this.
Yes, the syntax you use is correct to filter against null.
array(
'coupon_code' => array(
'null' => 'this_value_doesnt_matter'
)
)
Magento maps* the API method sales_order.list to Mage_Sales_Model_Order_Api::items().
public function items($filters = null)
{
:
$collection = Mage::getModel("sales/order")->getCollection()
:
if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
if (isset($this->_attributesMap['order'][$field])) {
$field = $this->_attributesMap['order'][$field];
}
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
}
:
}
The items() method uses a Mage_Sales_Model_Resource_Order_Collection to fetch the orders for the API call. That collection is based on Varien_Data_Collection_Db, so
$collection->addFieldToFilter($field, $value)
from above essentially does call
Varien_Data_Collection_Db::addFieldToFilter()
If you follow the latter, you'll hit Varien_Db_Adapter_Pdo_Mysql::prepareSqlCondition() in the end, params being
$fieldName = 'coupon_code'
$condition = array('null' => 'null')
Excerpt of that method:
public function prepareSqlCondition($fieldName, $condition)
{
$conditionKeyMap = array(
'eq' => "{{fieldName}} = ?",
:
'notnull' => "{{fieldName}} IS NOT NULL",
'null' => "{{fieldName}} IS NULL",
:
'sneq' => null
);
:
$query = '';
if (is_array($condition)) {
:
$key = key(array_intersect_key($condition, $conditionKeyMap));
if (isset($condition['from']) || isset($condition['to'])) {
:
} elseif (array_key_exists($key, $conditionKeyMap)) {
$value = $condition[$key];
if (($key == 'seq') || ($key == 'sneq')) {
:
}
$query = $this->_prepareQuotedSqlCondition($conditionKeyMap[$key], $value, $fieldName);
} else {
:
}
}
:
}
In your case _prepareQuotedSqlCondition() will be called with
$text = '{{fieldName}} IS NULL'
$value = 'null'
$fieldName = 'coupon_code'
which will result in $query = 'coupon_code IS NULL'.
If you take a closer look at the conversion method
protected function _prepareQuotedSqlCondition($text, $value, $fieldName)
{
$sql = $this->quoteInto($text, $value);
$sql = str_replace('{{fieldName}}', $fieldName, $sql);
return $sql;
}
you'll also see, why the value of the 'null' => 'null' key/value pair does not matter at all. That's because $text will be '{{fieldName}} IS NULL', i.e. not containing any binding ?.
Hence, there's nothing to replace for _quoteInto()^^
* see app/code/core/Mage/Sales/etc/api.xml

codeigniter pagination for a query

So far found plenty of help to get the pagination working for a get(table) command.
What I need is to pick only few of the entries from a couple of linked tables based on a sql where statement.
I guess the query command is the one to use but in this case how do I do the pagination since that command does not take extra parameters such $config['per_page']
Thanks for the help
Without any more info to go on I think that what you're looking for is something like the following.
public function pagination_example($account_id)
{
$params = $this->uri->ruri_to_assoc(3, array('page'));
$where = array(
'account_id' => $account_id,
'active' => 1
);
$limit = array(
'limit' => 10,
'offset' => (!empty($params['page'])) ? $params['page'] : 0
);
$this->load->model('pagination_model');
$data['my_data'] = $this->pagination_model->get_my_data($where, $limit);
foreach($this->uri->segment_array() as $key => $segment)
{
if($segment == 'page')
{
$segment_id = $key + 1;
}
}
if(isset($segment_id))
{
$config['uri_segment'] = $segment_id;
}
else
{
$config['uri_segment'] = 0;
}
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/controller_name/method_name/whatever_your_other_parameters_are/page/';
$config['total_rows'] = $this->pagination_model->get_num_total_rows();// Make a method that will figure out the total number
$config['per_page'] = '10';
$this->load->library('pagination');
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('pagination_example_view', $data);
}
// pagination_model
public function get_my_data($where = array(), $limit = array())
{
$this->db
->select('whatever')
->from('wherever')
->where($where)
->limit($limit['limit'], $limit['offset']);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$data = $query->result_array();
return $data;
}
return FALSE;
}
This should at least get you on the right track
If this isn't what you're asking I'd happy to help more if you can be a little more specific. How about some of your code.
The only other options that I can think of would be to either code a count in your select statement or not limit the query and use array_slice to select a portion of the returned array.