Joomla: how to load JTable-element with LIKE-condition - sql

I am using the following code to load a categorys record:
$res = JTable::getInstance('category');
$res->load(array('id' => $catid));
Now I would like to load the record based on its title which whould be matched against a SQL LIKE-pattern - is it possible to do this in a simple way with JTable, or do I need $dbo?

Far as I know JTable is made to be simple and carry only one element at a time, and through the primary key. If you really want something more advanced, I recomend that you use JDatabaseQuery way.
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all articles for users who have a username which starts with 'a'.
// Order it by the created date.
$query
->select(array('a.*', 'b.username', 'b.name'))
->from('#__content AS a')
->join('INNER', '#__users AS b ON (a.created_by = b.id)')
->where('b.username LIKE \'a%\'')
->order('a.created DESC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects.
$results = $db->loadObjectList();
In your case, instead of "$db->loadObjectList();" you can use "$db->loadObject();" for load just one item.
Source:
http://docs.joomla.org/Accessing_the_database_using_JDatabase/3.1

Related

Select $id from ids field containg $id1,$id2,$id3

My model in Laravel has a linked_ids string field like this:
echo $model->linked_ids
1,2,3,4,5
I want to make a query that gets me all records with a given id in linked_ids.
Currently I have:
Model::where('linked_ids', 'LIKE', '%' . $model->id . '%');
but this selects me more than I want to (if ex: $model->id is 3 => selects: 1,32,67)\
How can I avoid this since I don't know what position the id will be nor will the ids be ordered? I would like to do this in eloquent but can also use something like DB::raw() to run sql queries.
Bad way to keep your ids but if you really can't change it, you could take advantage of LazyCollections and filter with php.
I'm sure there's a way to do it directly in MySQL (or whatever dbms you're using) but this is what I have.
$id = 3;
Model::cursor()
->filter(function ($model) use ($id) {
return in_array($id, explode(',', $model->linked_ids));
})
// then chain one of these methods
->first(); // returns the first match or null
->collect(); // returns an Illuminate\Support\Collection of the results after the filtering
->all(); // returns an array of Models after the filtering
->toArray(); // returns an array and transforms the models to arrays as well.
->toJson(); // returns a json string
Take notice that this will still do a SELECT * FROM table without any filtering (unless you chain some where methods before cursor() but it won't load any model into memory (which is usually the bottleneck for big queries in Laravel)

passing msqli to a function - can't suss out why it's not working

I've searched high and low for an answer on this, but I'm either missing something, or I just can't find anything in this context.
Background - trying to avoid spaghetti frenzy with a little casual project I'm starting; part of this will involve mainly just calls to a mysql database, displaying table content and so on. Simply put, like a CRM I guess.
I may be way off base here, but I want to be able to create my sql calls as functions, which will help if/when I tweak and tune, as well as creating a cleaner code for what I'm looking to do.
So, without further ado, I have this as a demomstration:
echo "<table>";
selectall('actions','content',$mysqli);
echo "</table><br><br>";
What this does is show all rows from my table of 'actions. "content" is just an example field name I'm passing through that I want to display, as it is the main human-relevant field name in that table. I'm also passing $mysqli through here for my function db call.
My function looks like this:
function selectall($s_table,$s_content,$mysqli){
$query = "SELECT * FROM " . $s_table;
$resource = $mysqli->query($query);
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
$id = $row['id'];
echo "<tr><td>{$row[$s_content]}</td></tr>";
}
$resource->free();
$mysqli->close();
}
However.... it doesn't work, and it seems to throw a wobbly saying:
Warning: mysqli::query(): Couldn't fetch mysqli
This points to the action within the line $resource = $mysqli->query($query);
I know the function and everything is ok, as if I restate and declare $mysqli within the first line of the function, like so...
$mysqli = new mysqli(username password and so on in here);
... it works spot on.
$mysqli exists and works within the same code that is passing the variable within the function too.
This is early stages, so by shuffling the code around trying to poke the $mysqli pass into life I have perhaps made the code a little messier that intended, so try not to worry too much about that.
Anyone any ideas why it doesn't like this?
D'oh...
I had a
$mysqli->close();
in the lines above. Solved myself.
For reference, this is my function:
function selectall($s_table,$s_field,$mysqli){
if ($mysqli->connect_error) {die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);}
$s_table = preg_replace('/[^0-9a-zA-Z_]/', '', $s_table); // Cleans up the table name variable
$s_field = preg_replace('/[^0-9a-zA-Z_]/', '', $s_field); // Cleans up the field name variable
$query = "SELECT * FROM " . $s_table; // Adds passed table name to the select all
$resource = $mysqli->query($query);
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "<tr><td>{$row[$s_field]}</td></tr>"; // Content for each row of the select all
}
$resource->free();
$mysqli->close();
}
As you can see, I've also tried to protect the variables that enter the function.
This can be called via:
selectall('actions','content',$mysqli);
In this context, I want to view all the entries in the 'actions' table by the field name 'content'. This function, with some code above and below for a table, will create a new row for each entry.
I'll probably evolve a few, already created on that includes a delete button at the end of the line which is 'selectalldel'.
Open to comments on whether this actually is worthwhile, but thought I'd post up my corrected stupidity in case anyone finds this useful.

Avoiding SQL Injection in PDO and using the like clause

I am using prepared statements for a search functionality using PDO and I am using the like clause. Mysql is 5.5.32
function dblink(){
# hidden #
$conn = new PDO("mysql:host=localhost;dbname=$database",
$username, $password, array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ
));
return $conn;
}
$conn = dblink();
$query = "select * from tablename where attrib like ? ;";
$stmt = $conn->prepare($query);
$stmt->execute(array($_POST['field']."%"));
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
This dumps all the table contents when user enters % for field in the html form. I thought prepared statement would handle it and there is % in execute so that it matches the substring entered.
How do I use the POST field as normal text only so that it doesn't cause such problem?
This dumps all the table contents when user enters % for field in the html form.
Yes. That's the exact purpose of LIKE operator.
No, it has nothing to do with prepared statement. The latter is used to format your data, not to interfere with query logic.
If you don't like the way your code works - change it. But at the moment it works exactly the way you coded, with no flaws.

PDO fetchColumn() and fetchObject() which is better and proper usage

It's been bugging me, I have a query which returns a single row and I need to get their corresponding column value.
//Retrieve Ticket Information to Database
$r = db_query("SELECT title, description, terms_cond, image, social_status, sched_stat FROM giveaway_table WHERE ticket_id = :ticket_id",
array(
':ticket_id' => $ticket_id
));
There are two ways that I can get data which is, by using fetchColumn() and fetchObject()
fetchObject()
$object = $r->fetchObject();
$ticket_info[] = $object->title;
$ticket_info[] = $object->description;
$ticket_info[] = $object->terms_cond;
$ticket_info[] = $object->image;
$ticket_info[] = $object->social_status;
$ticket_info[] = $object->sched_stat;
fetchColumn()
$title = $r->fetchColumn() //Returns title column value
$description = $r->fetchColumn(1) //Returns description column value
Was wondering, which one is better, or are there any pros and cons about this stuff?
if possible, can you guys also suggest the best way (if there's any) on how to retrieve all columns that's been selected in a query and store it into an array with less line of code.
There are two ways that I can get data which is, by using fetchColumn() and fetchObject()
really? what about fetch()?
There is a PDO tag wiki where you can find everything you need
I don't know pros and cons of using it. In my project I often used fetching as array rather than object. It was more comfortable. But if you make ORM projects then maybe it would be better to use fetchObject and make it your object not a std_class. You could make a contructor that has one parametr which is stdClass and make your object from this class
Answering your other question you can fetch all columns using fetchAll();
Follow this link to learn more about this function http://www.php.net/manual/en/pdostatement.fetchall.php
More about abstract database layer you can find here -> http://www.doctrine-project.org/

Does CDbcommand method queryAll() in yii return indexed entries only?

I am trying to retrieve data from a simple mySql table tbl_u_type which has just two columns, 'tid' and 'type'.
I want to use a direct SQL query instead of the Model logic. I used:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('type')->from('tbl_u_type')->queryAll();
return $userArray;
But in the dropdown list it automatically shows an index number along with the required entry. Is there any way I can avoid the index number?
To make an array of data usable in a dropdown, use the CHtml::listData() method. If I understand the question right, this should get you going. Something like this:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('tid, type')->from('tbl_u_type')->queryAll();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($userArray,'tid','type'));
You can also do this with the Model if you have one set up for the tbl_u_type table:
$users = UType::model()->findall();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($users ,'tid','type'));
I hope that gets you on the right track. I didn't test my code here, as usual, so watch out for that. ;) Good luck!