how to echo multiple DB results with one query - php

If I were to echo the result of this query:
//Find membertype from community builder
$db->setQuery('Select cb_membertype From #__comprofiler Where id='.$user->id);
$membertype = $db->loadResult(); //load the result from the query
I would use:
echo "Your member type is: $membertype";
I'd rather not use a new query for every variable thought since they are all in the same table.
I'd rather run a single query like this:
//Find all 3 from one query
$db->setQuery('Select cb_membertype, cb_2015vopac, cb_2015llf
From #__comprofiler Where id='.$user->id);
$result = $db->loadResult(); //load the result from the query
How do I echo the specific fields from that query when using the single $result variable?

First, let me just say that should should quote your values/columns/table names.
Secondly, if you want to get multiple values, you need to use loadObjectList instead of loadResult.
The following will do it for you:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('cb_membertype', 'cb_2015vopac', 'cb_2015llf')))
->from($db->quoteName('#__comprofiler'))
->where($db->quoteName('id') . ' = '. $db->quote($user->id));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $result)
{
echo $result->cb_membertype;
echo $result->cb_2015vopac;
echo $result->cb_2015llf;
}
So loadObjectList give you an object, then you can loop though it using foreach loop.
Hope this helps

Related

Selecting data from other columns

I've rather new at php and mysqli and I've had some success but am currently facing a wall. Mostly because I dont know the terms to express what i'm trying to do.
I can select a row all day long but I seem to be stuck on the same row. I need to be able to select data from further down the column. Here is the code i'm working with.
$qry = "select * from products";
$rs = mysqli_query($conn,$qry);
$getRow = mysqli_fetch_row($rs);
$getRowAssoc = mysqli_fetch_assoc($rs);
echo "<img src=\"".$getRow['1'] . "\">";
i have several links to images in the picture column on my database but can't seem to figure out a simple way to display the links from other rows in that column. I may be way off base here but I dont think I am.
this is a layout of the db db pic
any help would be much appreciated
For each mysqli_fetch_assoc you get the result of the next row. As the index starts in -1, the first time you call it, it goes to the first row. So whenever you call it again, it goes to the next row. Use it inside of a loop and you will be all set.
while($row = mysqli_fetch_assoc($result)){
// $row will have new content each iteration
}
mysqli_fetch_assoc Fetch a result row as an associative array, but just 1 row, if you want to get all the result, you have to go through a loop to get everything for the result, example :
<?php
$query = 'SELECT `products`.* FROM `products`';
$mysqli = new Mysqli('localhost','test','root','password');
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo '<img src="' . htmlentities($row['pic']) . '" /><hr />';
}
unset($row);
$result->free();
$mysqli->close();
if you want to get all the rows in 1 step for later usage, you would use mysqli::fetch_all(), example :
<?php
$query = 'SELECT `products`.* FROM `products`';
$mysqli = new Mysqli('localhost','test','root','password');
$result = $mysqli->query($query);
$products = $result->fetch_all();
$result->free();
$mysqli->close();
print_r($products);

Joomla Mysql query in foreach loop

I'm trying to build a simple select list in Joomla 2.5 with php and mysql, but I've got a problem: it doesen't load the options name... are there any error?
<?php
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('optValue');
$query->from('#__sobipro_field_option');
$query->where("fid='38'");
$db->setQuery((string)$query);
$results = $db->loadObjectList();
if ($results){
echo "<select>";
foreach($results as $result){
foreach($result as $value) {
$query->select('sValue');
$query->from('#__sobipro_language');
$query->where("fid='38' and language='it-IT' and sKey='".$value."'");
$db->setQuery((string)$query);
$name = $db->loadResult();
echo "<option value=\"$value\">".$name."</option>";
}
}
echo "</select>";
}
else {
echo 'Error';
}
?>
Whenever you're trying to debug Joomla! code turn on debug mode (Global Configuration->System->Debug Settings) and turn Error Reporting up to Development (Global Configuration->Server->Error Reporting), then you would have seen your problem straight away.
$query is a actually an object of type JDatabaseQuery and should be used as is in the $db->setQuery($query) call without casting to a (string).
When referencing a database, table or column name it's a good idea to use Joomla's mechanism for wrapping the name is the correct quotes e.g.
$query-select($db->quoteName('optValue'))
Amongst other things this will insure that SQL keywords aren't a problem.
Likewise for values, use the Joomla! provided $db->quote() method. e.g.
$query->where($db->quoteName('fid') . '=' . $db->quote('38'));
When building a WHERE query with multiple values ANDed together you can simply add each item as it's own ->where() clause.
So your where before I would tend to write as:
$query->where($db->quoteName('fid') . '=' . $db->quote('38'));
$query->where($db->quoteName('language') . '=' . $db->quote('it-IT'));
$query->where($db->quoteName('sKey') . '=' . $db->quote($value));
Finally, as you've said both of your $queries work by themselves, but when put together in your code as shown they don't.
The reason for this is that after you configure $query for your first statement (and run it), you continue to add to the second statement to the original $query object. So, that when you do the second, third etc setQuery($query) the SQL is getting longer and longer and unlikely to return any results.
As you don't test for success of each $db->loadResult() in the inner-most foreach loop you never see the error.
At the very least you need to add a new $db->getQuery(true) at the beginning of your inner loop, like this:
<?php
// Get default database object
$db = JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('optValue'));
$query->from($db->quoteName('#__sobipro_field_option'));
$query->where($db->quoteName('fid') .'=' . $db->quote('38'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if ($results){
echo "<select>";
foreach($results as $result)
{
foreach($result as $value)
{
// Get a new query object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('sValue'));
$query->from($db->quoteName('#__sobipro_language'));
$query->where($db->quoteName('fid') .'=' . $db->quote('38'));
$query->where($db->quoteName('language') .'=' . $db->quote('it-IT'));
$query->where($db->quoteName('sKey') .'=' . $db->quote($value));
$db->setQuery($query);
$name = $db->loadResult();
echo "<option value=\"$value\">$name</option>";
}
}
echo "</select>";
}
else
{
echo 'Error';
}
This is going to potentially create a lot of objects, so, you should consider if there's a way to restructure it all into one SQL query this will make it significantly faster and reduce the load on your server.

Foreach skipping, joomla framework in using

I have in using joomla, have a input field and must add on result page of com_search a additional query, if i run this query in a sql editor i get 2 results, but in joomla is my foreach every time skipping.
If i do $db->getPrefix(); i see table prefix, so i thing to $db and $query are true.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__k2_categories');
$query->where("`name` LIKE '%MY_SEARCH_WORD%'");
$db->setQuery($query);
$results = $db->loadObjectList();
foreach($results as $entry) :
echo $results->name . "<br />";
endforeach;

Read from database, single rows (Joomla framework)

I use this code to read from data base:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array('category_name', 'category_short_description'));
$query->from('#__redshop_category');
$query->where('category_id = 1');
$db->setQuery($query);
$results = $db->loadObjectList();
How can i read once element, for example extra *category_name* and extra *category_short_description*
Here is also offical joomla wiki, but without single output: http://docs.joomla.org/J2.5:Accessing_the_database_using_JDatabase
Here what i have doing, but that's not work:
echo $results; ->output:ARRAY
echo $results['category_name']; -> without output, empty (In database rows are not empty)
How can i do this?
You can use loadObject() instead of loadObjectList() to retrieve just the first row:
$results = $db->loadObject();
echo $results->category_name;
If you want an associative array instead of an object, there is loadAssoc():
$results = $db->loadAssoc();
echo $results['category_name'];
To fetch single row you can use
$result = $db->loadObject()
instead of
$results = $db->loadObjectList()
and then you can access data by
$result->category_name;
$result->category_short_description;

Iterating over results of PDO query

I want to run a query using PDO, based on data in the URL paramater (yes, I know that this is prone to attacks, but its internal code for a utility).
$user = 'USER';
$pass = 'PASSWORD';
$dsn = 'mysql:dbname=PRODUCTS;host=HOST';
try {
$productDB = new PDO($dsn, $user, $pass);
$productDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
$msg = 'PDO ERROR' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();
die($msg);
}
if(isset($_GET['cat']))
{
$cat = $_GET['cat'];
print "cat = $cat <br>";
$products = $productDB->prepare('SELECT * FROM products WHERE cat_id LIKE ?');
$products->execute(array($cat));
$rows = $products->rowCount();
print "$rows rows returned";
?>
<table border="1">
<tr>
<td>product_id</td>
<td>product_name</td>
</tr>
<?php
foreach ($products->fetchAll() as $row) {
$id = $row['product_id'];
$product_name = $row['product_name'];
print "<tr>";
print "<th scope=\"row\"><b>$id</b></th>";
print "<td> $product_name </td>";
print "<tr>";
}
print "</table>";
}
?>
When I run this code, it prints the correct number of rows depending on the query, but does not populate the table.
I have also tried replacing the prepare and execute lines with:
$products = $productDB->query("SELECT * FROM products WHERE cat_id LIKE $cat");
Which returns the correct row count, but doesn't otherwise help.
And finally, I've tried replacing the foreach line with something like:
$rows = $products->fetchAll();
foreach ($rows as $row) {
My attempts to do the same with a fixed query all work fine, but I am having trouble working out how to place a variable element in a query, and then iterate over the results.
You're not doing anything to store the result:
$products->execute(array($cat));
needs to go in a variable:
$result = $products->execute(array($cat));
Then, instead of calling $products->fetchAll(), use $results->fetchAll():
foreach ($result->fetchAll() as $row)
I find it easier to use a $query variable (for prepare, etc) and then get the result into something like $result or $product. Makes the code a bit easier to read.
Try this (If I understood correctly) :
$products = $productDB->prepare("SELECT * FROM products WHERE cat_id LIKE :cat");
// Now, you can either do this :
$products->bindParam('cat', '%'.$cat.'%');
$products->execute();
// or you can call execute with an associative array of your parameterized query.
$products->execute(array('cat' => '%'.$cat.'%'));
// Then, get all the results like this :
$rows = $products->fetchAll();
foreach ($rows as $row) {
// Do work here ..
}
// Or, like this :
while ($row = $products->fetch(PDO::FETCH_ASSOC)) {
// Do work here ..
}
I personaly prefer the while, because you don't fetch the whole query in one var, reducing the amount of memory needed.
I also recommend you to use the FETCH_* parameter, to get only the kind of array you want.
By the way, you need to know that rowCount should not be used to count the rows returned by a SELECT. As said by php.net :
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Categories