Joomla doesn't work with PDO connection - php

Hey guys I need your help I have this code in a localhost file :
$db = new PDO('mysql:host=localhost;dbname=db;charset=utf8', 'user', 'pass');
$data = array();
$results = $db->query("SELECT * from YOUR_TABLE_NAME");
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$data[$row['prov_name']][] = $row;
}
But when I try to integrate this file in Joomla it doesn't work! Do you know how can I "transform" this into Joomla connection?
I always use this one for some select
$db =& JFactory::getDBO();
$query = 'SELECT CA_id FROM compras_activos where STAT_name = "Solicitado"';
$db->setQuery($query);
$result = $db->loadObjectList();
$CA_id = $result[0];
But that is just for one specific value but now I need all(*) the table.
Thanks

You should really read the documentation that I provided. If you are able to write a query as shown in your question, then this should not be too taxing. You can use the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('*'))
->from($db->quoteName('#__compras_activos'))
->where($db->quoteName('STAT_name') . ' = '. $db->quote('Solicitado'));
$db->setQuery($query);
$result = $db->loadObjectList();
If your database table do not belong to an extension associated with Joomla, then remove the #__ prefix in the above code.
Hope this helps

Related

How do I set the order when querying from DB?

I'm trying to query from a DB to get joomla articles from a certain category (52), and that are published.
I want to return these as the newest created, but I don't know where to add in the ORDER BY for the query.
I did try to add ->orderby('created'); just above $db->setQuery($query); but that didn't seem to work, it still only seems to be displaying by ascending order of ID.
Can anyone help?
<?php
$i = 0;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')
->from('#__content')
->where('catid = 52 AND state = 1');
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ( $rows as $row ) {
if(++$i > 1) break;
echo "<li><a href='/why-us/news/".$row->id."-".$row->alias."'>".$row->title."</a></li>";
}
?>
You can simply use ->order('created DESC') to achieve your desired results.
Check the documentation page, here

Selecting row where field = value error

Can you explain me why my code isnt working? Ive been thinking about it for a while and I cant find it. obviously I want to print some columns from rows where column F1 is equal to user's username.
$db = JFactory::getDBO();
$user = JFactory::getUser();
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$user->username;
$db->setQuery($query);
$result = $db->query();
while($row = mysqli_fetch_object($result))
{
print $row->F1;
}
It works when I remove condition from select command and I cant figure out how to make it work with it
$query = "SELECT * FROM qwozh_visforms_1";
Now Im getting this error:
UNKNOWN COLUMN 'ADMIN' IN 'WHERE CLAUSE' SQL=SELECT * FROM
QWOZH_VISFORMS_1 WHERE F1 = ADMIN RETURN TO PREVIOUS PAGE
Thanks
All it takes if a quick read of the Joomla documentation. The following is the same as your query but making full use of Joomla's up to date database class:
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select(array('*'))
->from($db->quoteName('#__visforms_1'))
->where($db->quoteName('F1') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$results = $db->loadObjectList();
// Display the results
foreach($results as $result){
// echo what you want here
}
Note, I've used the prefix #__ rather than manually defining qwozh, assuming your table belong to a Joomla extension.
I know PHP and MySQL, but not Joomla. But the problem is that your username needs to be quoted because it is probably a string.
Try this:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '{$user->username}'";
or
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$db->quote($user->username);
You need to wrap the name in quotes:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '".$user->username . "'";
As pointed out in the comments my answer has a pretty bad quality, you may want to look at prepared statements, expecially using bindParam, which takes care of quotes for you and protects you agains SQL injection attacks.
Unfortunately I cannot suggest you Joomla based approach since I never used it, somebody else can suggest you a more appropriate solution.

getting RS Eevents category name from Joomla database

I'm trying to get the category details from the joomla database for RSEvents. Can anyone shed any light on why this isn't working:
function _getCategorySlug($value) {
// 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.
// Note by putting 'a' as a second parameter will generate `#__content` AS `a`
$query
->select($db->quoteName(array('a.*', 'b.id', 'b.ide')))
->from($db->quoteName('#__categories', 'a'))
->join('INNER', $db->quoteName('#__rseventspro_taxonomy', 'b')
. ' ON (' . $db->quoteName('a.id') . ' = ' . $db->quoteName('b.id') . ')')
->where($db->quoteName('b.ide') . ' = '.$db->quote($value));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
}
I think this may help you. Using the below function you can get the categories of a particular event.
public function getCategories($id) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->clear()
->select($db->qn('id'))
->from($db->qn('#__rseventspro_taxonomy'))
->where($db->qn('type').' = '.$db->q('category'))
->where($db->qn('ide').' = '.$id);
$db->setQuery($query);
return $db->loadColumn();
}
Thanks! That was a great help and got me to where I need (with a little tweaking):
function getCategories($id) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->clear()
->select($db->qn('id'))
->from($db->qn('#__rseventspro_taxonomy'))
->where($db->qn('type').' = '.$db->q('category'))
->where($db->qn('ide').' = '.$id);
$db->setQuery($query);
$categories = $db->loadColumn();
return implode("_", $categories);
}
Also, would be great to find out what was wrong with my original query to get category's alias from the #__categories table

Converting mysql into PDO format

I'm trying to convert some old php mysql code into PDO format but am stuck. I've looked at other posts on here but can't quite figure it out.
This is the old code:
<?php
if (isset($_POST['query'])) {
// Connect to database
mysql_connect("localhost", "xxxxx", "xxxxx");
mysql_select_db("xxxxx");
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = mysql_query("SELECT * FROM articles WHERE title LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql))
{
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
And this is what I've managed to do but think there's something wrong in the "while" part.
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
while ($row = $sql->fetchAll()) {
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
You are trying to call fetchAll on "sql" which is a string.
Now, you could use query but i suggest you to use prepare instead (for security reason, because you insert POST data).
$q = $conn->prepare("SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')");
$q->execute(array($query));
// result contains all returned data
$result = $q->fetchAll();
// or row by row
while($row = $q->fetch())
From PHP.net
foreach ($conn->query($sql) as $row) {
Try somehing like this:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
//Build Query - Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
$sth = $conn->query($sql);
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
=========Updated Answer========
//Better alternative
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')";
$sth = $con->prepare($sql);
$sth->bind_param("s", $query);
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
PS: Best practice is to stick with prepared statements and execute for increased security.
Try to run this:
$rows = $conn->prepare("SELECT * FROM articles WHERE title LIKE ?")->execute(array('%'.$query.'%'))->fetchAll();
while($row = $rows->fetch()) {
// TODO: Parse the rows
}
Also, try not to use * in your queries, that's not the best practice, it is better to use a column list instead separated by commas, as you do not necessary need to load the values of all columns. select * is less scalable and it might be the source of security vulnerabilities, like accidentally loading the inappropriate column and passing its value to the inappropriate place.

inner join query in joomla

I want to fire one complex query in my joomla site. I have written below code for it.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('`chr`.`characteristic_id`,`chr`.`characteristic_value`,`prc`.`price_value`');
$query->from('`#___hikashop_product` AS `pdt`');
$query->join('inner', '`#__hikashop_variant` AS `vari` ON `pdt`.`product_id` = `vari`.`variant_characteristic_id`');
$query->join('inner', '`#__hikashop_characteristic` AS `chr` ON `vari`.`variant_characteristic_id` = `chr`.`characteristic_id`');
$query->join('inner', '`#__hikashop_price` AS `prc` ON `pdt`.`product_id` = `prc`.`price_product_id`');
$query->where('`pdt`.`product_id` = 68');
$db->setQuery($query);
Query is executing in my local mysql.
any help will be appreciated
You can try this
$db->setQuery("Your query");
$result = $db->query();
//if you need the count
$rowcount = $db->getNumRows();
//if the result is multiple rows
$result_array = $db->loadAssocList() or $db->loadObjectList();
//if the result is single row you can use
$result = $db->loadAssoc() or $db->loadObject();
To fire the query, all you need to do is:
$rows = $db->loadAssocList(); // or loadObjectList()
The above will put all of the rows into $rows
You can also fire the query without grabbing the rows with:
$db->query();

Categories