Joomla Jdatabase query code with join does not work - mysql

I run the php code below within the 'Eval' section of a Fabrik form element. The code is supposed to return/put a number in a form field, but nothing appears in the form field.
When I used another query (refer to '$query-> ' lines) the code does work, so I get the impression that the query contains errors; however, when executing the related webpage with the form fields no sql error appears.
I have no idea what is wrong with the query(?)
Code:
$form_productname = 'testproduct';
$form_username = 'myname';
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
//$query->select($db->quoteName(array('a.id', 'b.productid')));
$query->select($db->quoteName('b.productid'));
$query->from($db->quoteName('#__products', 'b'));
$query->join('INNER', $db->quoteName('#__extendedreg_users', 'a') . ' ON (' . $db->quoteName('a.user_id') . ' = ' . $db->quoteName('b.owner') . ')
AND (' . $db->quoteName('a.cf_collectivename') . ' = ' . $db->quote($form_username) . ')
AND (' . $db->quoteName('b.productname') . ' = ' . $db->quote($form_productname)).')'.;
//echo $query;exit;
$db->setQuery($query);
$db->execute();
$results = $db->loadObjectList();
return count($results);
UPDATE: cause was syntax php error in where statement:
. $db->quote($form_productname)).
must be:
. $db->quote($form_productname).

You are not getting any errors because you are not catching any errors. Have a look at How to do SQL exception / error handling.
Do at least a $query->dump() and run your query in a console if you can't figure out what is wrong.
I don't understand why are you quoting the value you are comparing $form_username and $form_productname. But maybe it's late and I am tired.

Related

mysql select - CONCAT no longer working with MariaDB upgrade

This code is part of a database search autocomplete function. It was coded a while ago but the database has since been upgraded from mysql to MariaDB.
This is the part of the code giving an error.
$sql = 'SELECT tree_id, tree_common_name, tree_botanical_name FROM all_trees';
for($i = 0; $i < $p; $i++) {
$sql .= 'WHERE CONCAT(tree_common_name,tree_botanical_name) LIKE ? ';
}
$stmt = $conn->prepare($sql);
if($stmt === false) {
$user_error = 'Wrong SQL: ' . $sql . '<br>' . 'Error: ' . $conn->errno . ' ' . $conn->error;
trigger_error($user_error, E_USER_ERROR);
}'
The error message
PHP Fatal error: Wrong SQL: SELECT tree_id, tree_common_name, tree_botanical_name FROM all_treesWHERE CONCAT(tree_common_name,tree_botanical_name) LIKE ? <br>Error: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(tree_common_name,tree_botanical_name) LIKE ?' at line 1 in /home/wiwi1740/public_html/includes/autocomplete.php on line 73
I've looked at using
$sql .= 'WHERE CONCAT_WS(' ',tree_common_name,tree_botanical_name) LIKE ? ';
but still throws an error.
Any tips would be appreciated. This code originally came from someone else that I adapted for my client.

Is it possible to know what UPDATE "WHERE" statement caused not to update without doing a second query?

I hava a Joomla DB Query (mysql) that updates something in the DB if all 3 WHERE clauses are met. I want to know if there is way to extract from the update mysql query which "WHERE" statement failed in updating?
I ask this because if COUNT = 1 (which means the DB is already updated and nothing should happen) I want to relay an error like "already updated before" instead of just "not updated".
I of course could do a select query if the update query fails but that means a second query and i was just wondering if there is a more elegant solution to this problem. Maybe a sql function i haven't heard of or something else. So i could do with just one database query.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->update($db->quoteName('#__table'));
$query->set($db->quoteName('field1') . ' = ' . $db->quote($value1))
->set($db->quoteName('field2') . ' = ' . $db->quote($value2));
if ($value3 !="") {
$query->set($db->quoteName('field3') . ' = ' . $db->quote($value3));
}
$query->where($db->quoteName('id') . ' = ' . $db->quote($rowid))
->where($db->quoteName('talentuid') . ' = ' . $db->quote($tid))
->where($db->quoteName('count') . ' = ' . $db->quote(0));
$db->setQuery($query);
$result = $db->execute();
// Check for affected rows.
if ($db->getAffectedRows() > 0) {
return '{"success": "true"}';
} else {
return '{"success": "false"}';
}

Minimize database in order to export all products from Magento

I have a Magento 1.4.0.1 site and I want to export all the products in a CSV format. I tried running an Import/Export profile, but the max_timeout limit in php.ini is too low for the time it needs to run the operation. Since my provider doesn't allow me to set a higher max_timeout I have to copy the site into my local machine and run the profile from there.
My local machine runs on Windows 7 and WAMP 2.2
I copied all the files, but I'm having real trouble importing the database as it has 300MB. I configured my php.ini to have:
max_execution_time=3600
post_max_size=999M
memory_limit=999M
upload_max_filesize=999M
max_input_time=5000
I restarted the WAMP server and Imported the dump through PhpMyAdmin, but I still get errors. So my plan is to reduce the size of the database in order to have a functional backend and all the products, and empty all unimportant tables. The problem is I don't know which ones are vital and which ones aren't. Can you suggest a list of tables that I have to keep or the ones that I have to empty?
Please note that since I'm running WAMP on windows I don't have the possibility use any SSH command line stuff.
I will share a simple php script, that I usually use to get a Magento DB dump with smaller footprint.
For example you can create a file with name: tiny-dump.php in Magento root directory and to paste the script inside this file. Later you can just run the script if you hit the url: http://mydomain.com/tiny-dump.php
... if everything works well you will find a sql file with the DB dump in var/ directory. The file name will contain {DB name}-{current date}.sql
For your information I used some ideas from this article: http://www.crucialwebhost.com/kb/article/log-cache-maintenance-script/
The script will work, if your hosting provide have installed "mysqldump"
Here is a link to the script: https://gist.github.com/4495889
Here is the script:
<?php
$xml = simplexml_load_file('./app/etc/local.xml', NULL, LIBXML_NOCDATA);
$db['host'] = $xml->global->resources->default_setup->connection->host;
$db['name'] = $xml->global->resources->default_setup->connection->dbname;
$db['user'] = $xml->global->resources->default_setup->connection->username;
$db['pass'] = $xml->global->resources->default_setup->connection->password;
$db['pref'] = $xml->global->resources->db->table_prefix;
function export_tiny() {
global $db;
$sqlFileName = 'var/' . $db['name'] . '-' . date('j-m-y-h-i-s') . '.sql';
$tables = array(
'dataflow_batch_export',
'dataflow_batch_import',
'log_customer',
'log_quote',
'log_summary',
'log_summary_type',
'log_url',
'log_url_info',
'log_visitor',
'log_visitor_info',
'log_visitor_online',
'index_event',
'report_event',
'report_compared_product_index',
'report_viewed_product_index',
'catalog_compare_item',
'catalogindex_aggregation',
'catalogindex_aggregation_tag',
'catalogindex_aggregation_to_tag'
);
$ignoreTables = ' ';
foreach($tables as $table) {
$ignoreTables .= '--ignore-table=' . $db['name'] . '.' . $db['pref'] . $table . ' ';
}
$dumpSchema = 'mysqldump' . ' ';
$dumpSchema .= '--no-data' . ' ';
$dumpSchema .= '-u ' . $db['user'] . ' ';
$dumpSchema .= '-p' . $db['pass'] . ' ';
$dumpSchema .= $db['name'] .' > ' . $sqlFileName;
exec($dumpSchema);
$dumpData = 'mysqldump' . ' ';
$dumpData .= $ignoreTables;
$dumpData .= '-u ' . $db['user'] . ' ';
$dumpData .= '-p' . $db['pass'] . ' ';
$dumpData .= $db['name'] .' >> ' . $sqlFileName;
exec($dumpData);
}
export_tiny();
Known issues: Sometimes the script fails to create the DB dump if the the DB password contains special characters.
Hope, that it's helpful!

Zend DB Expr getting values from previous join

I have the following code in a zend db query
->join(array('z' => new Zend_Db_Expr('(' . $this->_dbhInstance->select()->from('zipcode', array('lat', 'lon', 'zip'))
->group('zip') . ')')), 'zip = f.zipcode')
->join(array('distance' => new Zend_Db_Expr('(SELECT GetDistance(' . $lat . ',' . $lon . ',z.lat,z.lon) as distance)')))
The issue is that z.lat,z.lon is not getting the values from the previous join (>join(array('z'), it just uses the actual text.
How can I format z.lat,z.lon) to grab the values from >join(array('z' ?
This is not working because Join has tree parameter
->join(tableName,joinCondition,fetchParameters)
but you have wrote only two...

Searching MySQL DB using PHP

I use CodeIgniter + MySQL.
I am succeeding in running this query and parsing the result.
$var1 = $this->db->query("select title from stores where title like \"" . $str . "%\" union select title from coupons where title like \"" . $str . "%\"");
return $var1;
And in the controller, I parse the result() of this query to a JSON file using json_encode
But when I run the same query on another table, and follow the same step in parsing, I am facing parsing problems.
$var1 = $this->db->query("select tagword from tags where tagword like \"" . $str ."%\"");
Am I doing something wrong here?
Try echo-ing your SQL Statement
echo $this->db->last_query();
Then try Run SQL query/queries on your database for your debugging purpose