How to return a JSON array from sql table with PhalconPHP - phalcon

I have several tables that have JSON arrays stored within fields.
Using PHP PDO I am able to retrieve this data without issue using:
$query1 = $database->prepare("SELECT * FROM module_settings
WHERE project_token = ? AND module_id = ? ORDER BY id DESC LIMIT 1");
$query1->execute(array($page["project_token"], 2));
$idx = $query1->fetch(PDO::FETCH_ASSOC);
$idx["settings"] = json_decode($idx["settings"]);
This returns a string like:
{"mid":"","module_id":"1","force_reg_enable":"1","force_reg_page_delay":"2"}
Attempting to gather the same data via PhalconPHP
$result = Modulesettings::findFirst( array(
'conditions' => 'project_token = "' . $token . '"' ,
'columns' => 'settings'
) );
var_dump($result);
Provides a result of
object(Phalcon\Mvc\Model\Row)#61 (1) { ["settings"]=> string(167) "{"text":"<\/a>
<\/a>
","class":""}" }
What do I need to do different in Phalcon to return the string as it is stored in the table?
Thank you.

You have 2 approach
First :
Get the settings with this structure :
$settings = $result->settings;
var_dump($settings);
Second :
First get array from resultset, then using the array element :
$res = $result->toArray();
var_dump($res['settings']);
Try it.

You can decode json right in your Modulesettings model declaration:
// handling result
function afterFetch() {
$this->settings = json_decode($this->settings);
}
// saving. Can use beforeCreate+beforeSave+beforeUpdate
// or write a Json filter.
function beforeValidation() {
$this->settings = json_encode($this->settings);
}

Related

Can Laravel automatically switch between column = ? and column IS NULL depending on value?

When building a complex SQL query for Laravel, using ? as placeholders for parameters is great. However when the value is null, the SQL syntax needs to be changed from = ? to IS NULL. Plus, since the number of parameters is one less, I need to pass a different array.
To get it to work, I have written it like this, but there must be a better way:
if ($cohortId === null) {
// sql should be: column IS NULL
$sqlCohortString = "IS NULL";
$params = [
Carbon::today()->subDays(90),
// no cohort id here
];
} else {
// sql should be: column = ?
$sqlCohortString = "= ?";
$params = [
Carbon::today()->subDays(90),
$cohortId
];
}
$query = "SELECT items.`name`,
snapshots.`value`,
snapshots.`taken_at`,
FROM snapshots
INNER JOIN (
SELECT MAX(id) AS id, item_id
FROM snapshots
WHERE `taken_at` > ?
AND snapshots.`cohort_id` $sqlCohortString
GROUP BY item_id
) latest
ON latest.`id` = snapshots.`id`
INNER JOIN items
ON items.`id` = snapshots.`item_id`
ORDER by media_items.`slug` ASC
";
$chartData = DB::select($query, $params);
My question is: does Laravel have a way to detect null values and replace ? more intelligently?
PS: The SQL is for a chart, so I need the single highest snapshot value for each item.
You can use ->when to create a conditional where clause:
$data = DB::table('table')
->when($cohortId === null, function ($query) {
return $query->whereNull('cohort_id');
}, function ($query) use ($cohortId) {
// the "use" keyword provides access to "outer" variables
return $query->where('cohort_id', '=', $cohortId);
})
->where('taken_at', '>', $someDate)
->toSql();

How to create constraints that use expr() dynamically?

A user can enter a letter range like "A-D", by which a query must find all records that start with any of those letters. What I eventually need is a constraints block that looks like this:
$constraints = [
$query->expr()->eq(
'composition.sys_language_uid',
$query->createNamedParameter($language, \PDO::PARAM_INT)
),
$query->expr()->orX(
$query->expr()->like(
'composition.title',
$query->createNamedParameter('A%')
),
$query->expr()->like(
'composition.title',
$query->createNamedParameter('B%')
),
$query->expr()->like(
'composition.title',
$query->createNamedParameter('C%')
),
$query->expr()->like(
'composition.title',
$query->createNamedParameter('D%')
)
)
];
which is a structure, that works well, when I use it as a test. So I know I need to strive for a solution like this.
But, of course, since the letters given are not fixed, but variable, the block within ->orX() needs to be calculated programmatically. This is, where my problem lies.
I tried this:
// A custom helper function that splits a letter range string like "A-D"
// and returns an array like ['A','B','C','D']
$compareLetters = Helper::returnItemOrListAsArray($letter, true);
}
// Create the query
$query = $allDbConnections['composition']->createQueryBuilder();
// Collect constraints
$addConstraints = [];
// Compare first letter against given compareLetters
foreach($compareLetters as $l) {
$addConstraints[] = $query->expr()->like(
'composition.title',
$query->createNamedParameter($l . '%')
);
}
Trying to insert the resulting array like this:
$constraints = [
$query->expr()->eq(
'composition.sys_language_uid',
$query->createNamedParameter($language, \PDO::PARAM_INT)
),
$query->expr()->orX(
implode(',', $addConstraints)
)
]
throws an exception:
Operand should contain 1 column(s)
Currently I have no idea, how to do this differently nor how to interpret the exception. Any hint would be most welcome!
Not sure whether it's a good approach, but I would try out range() function to generate the query, something like this:
<?php
$userInput = 'A-D';
list($start, $end) = explode('-', $userInput);
$selection = [];
foreach (range($start, $end) as $letter) {
$selection[] = $query->expr()->like(
'composition.title',
$query->createNamedParameter($letter . '%')
);
}
$constraints = [
$query->expr()->eq(
'composition.sys_language_uid',
$query->createNamedParameter($language, \PDO::PARAM_INT)
),
$query->expr()->orX(...$selection)
];
So more or less what you already did. Just you are not using the spread operator in your example when calling orX()

$data = $query->row(); returns only one row

Im trying to list the results of my sql query (picking up all the movies from a category), but I cannot figure out how to get all the rows instead of only one.
Here's the code :
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->row();
$this->response($data, 200);
I've tried :
while($row = mysql_fetch_assoc($query)){
$data = $query->row();
}
$this->response($data, 200);
And it doesn't work. Any suggestion ? Thank you !
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->result();
To traverse the $data array:
foreach($data AS $row)
{
//to retrieve the data from each row.
$col1 = $row->col1;
$col2 = $row->col2;
}
Use result() instead of row(). result() will return an array of objects that are your results. Alternatively, you can useresult_array() which will resturn an array of arrays keyed according to your columns. Please refer to here for a better outline of the result() and row() methods.
Do you have a database configuration file? the load->database() requires it. Where is $movies_category coming from? This will let you iterate over your results.
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
foreach ($query->result() as $row)
{
echo $row->column;
}
Where column corresponds with one of the values in the movies table.
I'm surprised nobody has mentioned the potential hazards of using variables (possibly user input) in your SQL. You should seriously consider using query bindings or the active record features of CodeIgniter to build safer queries.
Consider the following solution to your problem:
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = ?';
$query = $this->db->query($sql, array($movies_category));
// $data = $query->result(); // returns result as an array of objects
$data = $query->result_array(); // returns result as array
$this->response($data, 200);
I'm assuming this is for some sort of API? If so, consider using the result_array() method as it will probably be better suited for your needed output, and also really easy to convert into JSON:
$json_data = json_encode($data);
Hope that helps,
Cheers.
For your question row() return only one value its good for checking in ID and if you want get all the rows use result_array() or simple result()
You can try this code....
Model:
function get_movies($movies_category){
$this->db->where("category",$movies_category);
$query = $this->db->get("movies");
return $query->result_array();
}
Controller:
$this->data['movies'] = $this->'name of model'->get_movies('here is the movie categories');
View:
foreach($movies as $m){
print_r($m);
}
exit();
Note you can directly add the code in function in model to controller add this in your controller if you want directly...
$this->data['movies] = $this->db->get('movies')->result_array();

sql update codeigniter

I am using codeIgniter..
I want to update a table column is_close when id=$ticket_id of my table= tbl_tickets.
I am doing this :-
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
and I have also done this :-
$sql = "UPDATE tbl_tickets SET is_close={1} WHERE id='$title_id'";
$this->db->query($sql);
both are not working,i.e., my table is not updating the value to 1 and also no error is being shown in the broswer. :(
Edited: Included my model part :
function setClosePost($title_id){
$sql = "UPDATE tbl_tickets SET is_close=0 WHERE id='$title_id'";
$this->db->query($sql);
// $data=array(
// 'is_close'=>1
// );
// $this->db->where('id',$title_id);
// $this->db->update('tbl_tickets',$data);
}
My controller :-
function closePost(){
$this->load->model('helpdesk_model');
$this->helpdesk_model->setClosePost($this->input->post('title_id'));
}
first of all use a get method to check if ticket_id is exist or not.
another thing is always use return in your functions in models so you can check them by if(function_name){...}else{...}
then if your get method returned data correctly try
Model Method
public function set_closed($ticket_id){
$this->db->set(array(
'is_close'=>1
)); // pass fields in array
$this->db->where('id',$ticket_id);
$this->db->update('tbl_tickets'); // table name
return true;
}
then check that in your controller
if($this->Ticket_model->set_closed($ticket_id) == true){
echo 'ticket set to closed correctly';
}else{
echo 'there is some error on updating database'.$this->db->error(); // to checkout db error .
}
First, check $title_id before passing:
var_dump($title_id);
Then, try do "select a row with this id" before updating and after.
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
$data=array(
'is_close'=>1
);
$this->db->where('id',$title_id);
$this->db->update('tbl_tickets',$data);
$query = $this->db->get_where('tbl_tickets', array('id' => $id));
foreach ($query->result() as $row)
{
var_dump($row->is_close);
}
Then, give your table structure.
Just try like this
$sql = "UPDATE tbl_tickets SET is_close='1' WHERE id=".$title_id;
$this->db->query($sql);
just try like this
**function edit($close,$id) {
$sql = "UPDATE tbl_tickets SET is_close= ? WHERE id = ? ";
$this->db->query($sql, array($close,$id));
}**
To handle this type of errors, i mean if reflection is not happen in database, then use below steps to resolve this type of error.
1) use $this->db->last_query() function to print query, using this we can make sure our variable have correct value (should not null or undefined), using that we can make sure also SQL query is valid or not.
2) If SQL query is valid then open phpmyadmin & fire same query into phpmyadmin, it will return error if query columns or table names are invalid.
Use this way, its best way to cross check our SQL queries issues.
I hope it will work.
Thanks
You are trying to update integer(INT) type value, just cross check with your column datatype if that is varchar then you have to put value in a single or double quote.
Like this
$data=array('is_close'=> '1');

Trying to get property of non-object Yii

I dont get this error, there is a row in database.
$tip = StringHelper::trimmer($_GET['tip']);
$sql = 'SELECT id FROM contact_reasons WHERE alias = "' . $tip . '"';
$model = ContactReasons::model()->findAllBySql( $sql );
die($model->id);
if(!is_null($model)) {
$this->render('kontakt', array(
'model' => $model,
));
} else {
$this->renderText('Tražena stranica ne postoji.');
}
I used debug to see if there is a response, and even used query on database, and it returns a row with ID. I get this error on line with die();
Please note that, findAllBySql returns an array of CActiveRecords, while findBySql returns a single CActiveRecord. You may also use parameter binding for your SQL statements to prevent SQL injection.
see also http://www.yiiframework.com/doc/api/1.1/CActiveRecord