I am new to joomla. I am using RSDirectory Component. In this i have to customize validation. i have a file named rsdirectory.php which is located at: administrator>components>com_resdirectory>helpers>rsdirectory.php.
I have a table, table1. In which a unique code is stored. Now i want to fill a form using that code if exist then query will execute otherwise my validation code will be execute. i have done this successfully. Now i have an another table, table2 in which my data is storing when i am filling a form with unique code. i just want to check my unique code whether it is exist in table2 or not. if exist validation will execute.i want to use same function for both.
Here is my code. Thanks in advance.
public static function uniquestacksfield($value, $column,$column1,$id1=null, $id = null){
// Get DBO.
$column = 'uni_code';
$db = JFactory::getDBO();
$query = $db->getQuery(true)
->select($db->qn('id'))
->from($db->qn('#_table1', 'e'))
->where($db->qn($column) . ' = ' . $db->q($value));
$db->setQuery($query);
$entry = $db->loadObject();
if ($id) {
$query->where($db->qn('e.id') . ' = ' . $db->q($id));
}
$db->setQuery($query, 0, 1);
return $db->loadResult();
/------------------another query-----------------------/
$column1 = 'uni_code2';
$db1 = JFactory::getDBO();
$query1 = $db1->getQuery(true)
->select($db1->qn('entry_id'))
->from($db1->qn('#_table2', 'c'))
->where($db1->qn($column1) . ' = ' . $db1->q($value));
$db1->setQuery($query1);
$entry1 = $db1->loadObject();
if ($id1) {
$query1->where($db1->qn('c_entry_id') . ' = ' . $db1->q($id1));
}
$db1->setQuery($query1, 0, 1);
return $db1->loadResult();
}`
I think below code is may be use.you can try it now. it is not good explain more to your criteria
public static function uniquestacksfield($value, $column,$column1,$id1=null, $id = null){
// Get DBO.
$db = JFactory::getDBO();
$column = 'uni_code';
$column1 = 'uni_code2';
if($column == 'uni_code') {
$query = $db->getQuery(true)
->select($db->qn('id'))
->from($db->qn('#_table1', 'e'))
->where($db->qn($column) . ' = ' . $db->q($value));
$db->setQuery($query);
$entry = $db->loadObject();
if ($id) {
$query->where($db->qn('e.id') . ' = ' . $db->q($id));
}
} else {
$query = $db->getQuery(true)
->select($db->qn('entry_id'))
->from($db->qn('#_table2', 'c'))
->where($db->qn($column1) . ' = ' . $db->q($value));
$db->setQuery($query);
$entry = $db1->loadObject();
if ($id) {
$query->where($db->qn('c_entry_id') . ' = ' . $db->q($id1));
}
}
$db->setQuery($query, 0, 1);
$item = $db->loadResult();
return $item;
}
Related
I would like to use a query on a function dynamically. I would like to use the same function multiple times. How do I call this function based on the $type variable?
This what I attempted. I know it is not complete, but I don't know what I have to do to get it to work.
function GeneralQuery($connMysqli){
// Query mounting according condition of $type
if(empty($type)){
if($type = "")
{
if($type == "school")
{
$type = 'GROUP BY school
ORDER BY school';
}
else if($type == "class")
{
$type = 'GROUP BY class
ORDER BY class';
}
else
{
$type == "student";
$type = 'GROUP BY class, student
ORDER BY class, avg DESC';
}
}
}
$sql = "SELECT avg(finalgrade) as avg, u.lastname as school, u.department as class, u.id as student from fhrw_grade_grades gg
inner join fhrw_user u on u.id=gg.userid
where gg.rawgrade is not null " . $type . "";
$res = mysqli_query($connMysqli,$sql)or die(mysqli_error($connMysqli));
$list = array();
while($item = mysqli_fetch_assoc($res)){
$list[] = $item;
}
return $list;
}
// I don't know what to do here to call query result for School -
$data = GeneralQuery($connMysqli);
foreach($data as $item){
echo $item['avg'] . ' - ' . $item['School'] . '<br>';
}
// I don't know what to do here to call query result for Class
$data = GeneralQuery($connMysqli);
foreach($data as $item){
echo $item['avg'] . ' - ' . $item['class'] . '<br>';
}
// I don't know what to do here to call query result for Student
$data = GeneralQuery($connMysqli);
foreach($data as $item){
echo $item['avg'] . ' - ' . $item['Student'] . '<br>';
}
// close connection
mysqli_close($connMysqli);
Now, when your intention is clear, here is your function refactored
function GeneralQuery($connMysqli)
{
$sql = "SELECT avg(finalgrade) as avg, u.lastname as school,
u.department as class, u.id as student
FROM fhrw_grade_grades gg
INNDER JOIN fhrw_user u on u.id=gg.userid
WHERE gg.rawgrade is not null ";
// Query mounting according condition of $type
if($type == "school")
{
$sql .= 'GROUP BY school ORDER BY school';
}
else if($type == "class")
{
$sql .= 'GROUP BY class ORDER BY class';
}
else if($type == "student")
{
$sql .= 'GROUP BY class, student ORDER BY class, avg DESC';
}
else
{
trigger_error("Wrong query type");
}
$res = mysqli_query($connMysqli,$sql);
return mysqli_fetch_all($res);
}
All you had to do it to add $type as a function parameter and then append the query with different endings.
Then you can call your function with different types
$data = GeneralQuery($connMysqli, 'student');
How about using switch structure?
<?php
function GeneralQuery($connMysqli, string $type = null)
{
switch($type) {
case "school":
$sqlQuery = 'GROUP BY school
ORDER BY school';
break;
case "class":
$sqlQuery = 'GROUP BY school, class
ORDER BY class';
break;
case "student":
$sqlQuery = 'GROUP BY school, class, student
ORDER BY class, avg DESC';
break;
default:
//your default case when
//none of above mathes
//for exampe no $type was passed
//to the function
$sqlQuery = 'GROUP BY class, u.id
ORDER BY class, avg DESC';
break;
}
$sql = "SELECT avg(finalgrade) as avg, u.lastname as school, u.department as class, u.id as student from fhrw_grade_grades gg
inner join fhrw_user u on u.id=gg.userid
where gg.rawgrade is not null " . $sqlQuery . "";
$res = mysqli_query($connMysqli,$sql)or die(mysqli_error($connMysqli));
$list = array();
while($item = mysqli_fetch_assoc($res)){
$list[] = $item;
}
return $list;
}
$type = 'school';
$data = GeneralQuery($connMysqli, $type);
?><h4>AVG by School</h4><?
foreach($data as $item){
echo round($item['avg'],2) . ' - ' . $item['school'] . '<br>';
}
$type = 'class';
$data = GeneralQuery($connMysqli, $type);
?><h4>AVG by Class</h4><?
foreach($data as $item){
echo round($item['avg'],2) . ' - ' . $item['class'] . '<br>';
}
$type = 'student';
$data = GeneralQuery($connMysqli, $type);
?><h4>AVG by Student</h4><?
foreach($data as $item){
echo round($item['avg'],2) . ' - ' . $item['student'] . '<br>';
}
// close connection
mysqli_close($connMysqli);
Note a must read about SQL Injection
Note there is no FROM in the SELECT query, the syntax for SELECT statemet or here
I'm calling AJAX through below code on single table query and everything works fine and the results are printed:
public function getUnitsHTML() {
$jinput = JFactory::getApplication()->input;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$sdate = date_create($jinput->get ('dsvalue'));
$mystartdate = date_format($sdate, "Y-m-d");
$edate = date_create($jinput->get ('devalue'));
$myenddate = date_format($edate, "Y-m-d");
$query->select($db->quoteName(array('id', 'unit', 'start_date', 'end_date', 'state')));
$query->from($db->quoteName('#__p_reservations'));
$query->where($db->quoteName('state')." = ".$db->quote('1'),'AND')
->where($db->quoteName('start_date')." >= ".$db->quote($mystartdate),'AND')
->where($db->quoteName('end_date')." <= ".$db->quote($myenddate));
$query->order('ordering ASC');
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $result)
{
echo '<option value="' . $result->id . '" > ' . $result->unit.'</option>';
}
exit;
}
But when trying to make it more complex by joining with other tables I'm getting 500 Error:
public function getUnitsHTML() {
$jinput = JFactory::getApplication()->input;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$sdate = date_create($jinput->get ('dsvalue'));
$mystartdate = date_format($sdate, "Y-m-d");
$edate = date_create($jinput->get ('devalue'));
$myenddate = date_format($edate, "Y-m-d");
$query
->select(array('a.unit','a.start_date','a.end_date','a.state','b.id','b.unit_number'))
->from($db->quoteName('#__p_reservations','a'))
->join('INNER',$db->quoteName('#__p_units','b') . ' ON (' . $db->quoteName('a.unit') . ' = ' . $db->quoteName('b.id') . ')')
->where($db->quoteName('a.state')." = ".$db->quote('1'),'AND')
->where($db->quoteName('a.start_date')." >= ".$db->quote($mystartdate),'AND')
->where($db->quoteName('a.end_date')." <= ".$db->quote($myenddate))
->order('ordering ASC');
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $result)
{
echo '<option value="' . $result->id . '" > ' . $result->unit_number.'</option>';
}
exit;
}
your error is connected to mysql. It looks like your sql query is correct, but check back through the MYSQL command line. If the error goes on, this may be due to joomla JDbase.
I had an error with entering data in the database, but it had nothing to do with my code but with JDbase.
To make sure that the error is from joomla, put the joomla error console to work. It will tell you which file and line the error encounters.
Sorry for my bad English but it's not my mother tongue.
i did mistake on method of using order
->order('ordering ASC');
should change to:
->order($db->quoteName('a.unit'). 'ASC');
I have csv file with following structure. I want to update product category path from this file. How I can do this.
sku,category_ids
0001,"1,2,3"
0002,"1,2,4"
I using flowing script to update prices
$mageFilename = '../app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
set_time_limit(0);
ini_set('memory_limit','1024M');
/***************** UTILITY FUNCTIONS ********************/
function _getConnection($type = 'core_read'){
return Mage::getSingleton('core/resource')->getConnection($type);
}
function _getTableName($tableName){
return Mage::getSingleton('core/resource')->getTableName($tableName);
}
function _getAttributeId($attribute_code = 'category_ids'){
$connection = _getConnection('core_read');
$sql = "SELECT attribute_id
FROM " . _getTableName('eav_attribute') . "
WHERE
entity_type_id = ?
AND attribute_code = ?";
$entity_type_id = _getEntityTypeId();
return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getEntityTypeId($entity_type_code = 'catalog_product'){
$connection = _getConnection('core_read');
$sql = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
return $connection->fetchOne($sql, array($entity_type_code));
}
function _getIdFromSku($sku){
$connection = _getConnection('core_read');
$sql = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
return $connection->fetchOne($sql, array($sku));
}
function _checkIfSkuExists($sku){
$connection = _getConnection('core_read');
$sql = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
$count = $connection->fetchOne($sql, array($sku));
if($count > 0){
return true;
}else{
return false;
}
}
function _updatePrices($data){
$connection = _getConnection('core_write');
$sku = $data[0];
$newPrice = $data[1];
$productId = _getIdFromSku($sku);
$attributeId = _getAttributeId();
$sql = "UPDATE " . _getTableName('catalog_product_entity_decimal') . " cped
SET cped.value = ?
WHERE cped.attribute_id = ?
AND cped.entity_id = ?";
$connection->query($sql, array($newPrice, $attributeId, $productId));
}
/***************** UTILITY FUNCTIONS ********************/
$csv = new Varien_File_Csv();
$data = $csv->getData('prices.csv'); //path to csv
array_shift($data);
$message = '';
$count = 1;
foreach($data as $_data){
if(_checkIfSkuExists($_data[0])){
try{
_updatePrices($_data);
$message .= $count . '> Success:: While Updating Price (' . $_data[1] . ') of Sku (' . $_data[0] . '). <br />';
}catch(Exception $e){
$message .= $count .'> Error:: While Upating Price (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
}
}else{
$message .= $count .'> Error:: Product with Sku (' . $_data[0] . ') does\'t exist.<br />';
}
$count++;
}
echo $message;
I don't know which table to be updated. What needs to change in this code to work update category_ids.
Unless you have a specific reason for using a custom script, you can always use the normal System -> Import/Export -> Dataflow: Profiles -> Import All Products using the file you described.
If you are truly looking for a script I can amend my answer for you.
I have the following code snippet that builds chained select boxes based on data pulled from MySQL.
The first select uses a DISTINCT on a column called PartTypeDescription. This code works awesome if the values in the column are numerical in nature (example: 11). You choose the first select and then the second select is populated as it should.
The problem occurs when the data is text (example: Plumbing). You choose Plumbing for example and the second select box is empty. I'm assuming the second query that builds the second select box is not working correctly. Is there something in the code below that does not allow text values?
/* Configure the select boxes */
if (isset($_GET['key'])) {
$key = $_GET['key'];
switch ($key) {
case 'callTypeSelect':
$select = new SelectBox('What vehicle are you working from?','Choose a vehicle');
$res = mysql_query('SELECT DISTINCT PartTypeDescription FROM ' . DB_TABLE2);
$callTypes = array();
for ($i = 0; list($callType) = mysql_fetch_row($res); $i++) {
$callTypes[] = $callType;
$select->addItem($callType, 'brandSelect-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
break;
default:
if (strpos($key, 'brandSelect-') === 0) {
$callType = str_replace('brandSelect-', '', $key);
$resBrands = mysql_query('SELECT Invm_InventoryNumber FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = ' . mysql_real_escape_string($callType) . " ORDER BY Invm_InventoryNumber");
$select = new SelectBox('What part number are you looking for?', 'Pick a part');
for ($i = 0; list($brand) = mysql_fetch_row($resBrands); $i++) {
$select->addItem($brand, 'result-' . $brand . '-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
} elseif (strpos($key, 'result-') === 0) {
list($null, $brand, $callType) = explode('-', $key);
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
$markup = '';
for ($i = 0; $row = mysql_fetch_assoc($res); $i++) {
//$row = array_map('htmlspecialchars', $row); it looks like the items is already encoded
$markup .= <<<HTML
You can't escape characters inside of single quotes. For example:
$x = 'I don\'t like tomatoes';
That won't escape the quote like you think it would and will cause problems. In your code with this line:
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
You need to wrap strings with escape sequences with double quotes.
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. " WHERE PartTypeDescription = \'" . mysql_real_escape_string($callType) . "\'
AND Invm_InventoryNumber = \'" . mysql_real_escape_string($brand) . "'");
I looked through the stack questions and answers, but didn't see anything I could directly apply here. Maybe I'm just missing something.
The code below works fine, except when I include my where statement which refers to the value of the $wp_user_id variable.
I've checked that the variable IS actually being populated with a $user_id when the script is loaded. It appears that the value of this variable is lost right after the call to the conManager function, but I don't understand why. There doesn't appear to be anything within the ConnectionManager.php file (which defines the conManager function) which would touch this variable, so I'm at a loss.
I'm a PHP hack, so go easy on me, but what is causing me to lose the value of my variable, and how do I address it? Here's the code:
<?php
include_once("/home/evaluate/public_html/admin/php/ConnectionManager.php");
header('Content-type:text/javascript;charset=UTF-8');
$wp_user_id = $_GET["user"];
$json1=json_decode(stripslashes($_POST["_gt_json"]));
$pageNo = $json1->{'pageInfo'}->{'pageNum'};
$pageSize = $json1->{'pageInfo'}->{'pageSize'};
if(isset($json1->{'sortInfo'}[0]->{'columnId'})){
$sortField = $json1->{'sortInfo'}[0]->{'columnId'};
}
else{
$sortField = "miles_on_oil";
}
if(isset($json1->{'sortInfo'}[0]->{'sortOrder'})){
$sortOrder = $json1->{'sortInfo'}[0]->{'sortOrder'};
}
else{
$sortOrder = "ASC";
}
if($json1->{'sortInfo'}[0]->{'sortOrder'} == "defaultsort"){
$sortField = "miles_on_oil";
$sortOrder = "ASC";
}
if($json1->{'filterInfo'}[0]->{'value'} != "") {
for ($i = 0; $i < count($json1->{'filterInfo'}); $i++) {
if($json1->{'filterInfo'}[$i]->{'logic'} == "equal"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "notEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "!='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "less"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "lessEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "great"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "greatEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "like"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "startWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "endWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == ""){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}
$filter .= " AND ";
}
}
else {
$filter = '';
}
//print_r ($json1);
//die;
// Temp TEsting Values
// End Temp Testing Values
$conManager = new ConManager();
$conManager->getConnection();
if($json1->{'action'} == 'load'){
//to get how many records totally.
$sql = "select count(*) as cnt from oil_analysis_data where $filter user_id = '".$wp_user_id."'";
$handle = mysql_query($sql);
$row = mysql_fetch_object($handle);
$totalRec = $row->cnt;
$sql2 = "select * from oil_analysis_data where $filter user_id = '".$wp_user_id."' ORDER BY " . $sortField . " " . $sortOrder . " limit " . ($pageNo - 1)*$pageSize . ", " . $pageSize;
$handle2 = mysql_query($sql2);
$retArray2 = array();
while($row2 = mysql_fetch_assoc($handle2)) {
// Grab Vehicle Make, Model & Year "Names" from their respective tables & insert into the array
$year = "select Name from vehicle_data_years where ID = {$row2['list1']}";
$year1 = mysql_query($year);
$year2 = mysql_fetch_assoc($year1);
$year3 = $year2['Name'];
$make = "select Name from vehicle_data_makes where ID = {$row2['list2']}";
$make1 = mysql_query($make);
$make2 = mysql_fetch_assoc($make1);
$make3 = $make2['Name'];
$model = "select Name from vehicle_data_all where ID = {$row2['list3']}";
$model1 = mysql_query($model);
$model2 = mysql_fetch_assoc($model1);
$model3 = $model2['Name'];
$row2['list1'] = $year3;
$row2['list2'] = $make3;
$row2['list3'] = $model3;
// Grab Motor oil Viscosity, Brand & Product "Names" from their respective tables & insert into the array
$visc = "select name from viscosity where id = {$row2['viscosity']}";
$visc1 = mysql_query($visc);
$visc2 = mysql_fetch_assoc($visc1);
$visc3 = $visc2['name'];
$brand = "select brandname from oil_brand where brandid = {$row2['brand']}";
$brand1 = mysql_query($brand);
$brand2 = mysql_fetch_assoc($brand1);
$brand3 = $brand2['brandname'];
$product = "select product_name from oil_data where id = {$row2['product']}";
$product1 = mysql_query($product);
$product2 = mysql_fetch_assoc($product1);
$product3 = $product2['product_name'];
$row2['viscosity'] = $visc3;
$row2['brand'] = $brand3;
$row2['product'] = $product3;
if($row2['bypass_filtration'] == 1) {
$row2['bypass_filtration'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['bypass_filtration'] = "";
}
if($row2['oil_change'] == 1) {
$row2['oil_change'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['oil_change'] = "";
}
$retArray[] = $row2;
}
$analysis_data = json_encode($retArray);
$ret = "{data:" . $analysis_data .",\n";
$ret .= "pageInfo:{totalRowNum:" . $totalRec . "},\n";
$ret .= "recordType : 'object'}";
echo $ret;
}
?>
I'm curious, why do you add a semi colon after the $wp_user_id; ? I've noticed you doing this in more than one place. This may be the culprit.
$filter user_id = '".$wp_user_id;."'";
Nevermind. It would appear that my problem actually resulted from a change in my code that I had forgotten about. I changed $_REQUEST['user'] to $_GET['user'], thinking that, in this case, since the value was being passed as a URL query string, that wouldn't be a problem.
To be honest, I'm still not entirely sure why that made a difference - although I can research that on my own. But, at any rate, changing that back corrected my problem entirely.
Thanks to those who responded, though. Even if not solutions to my actual problem, the information from both turned out to be very useful.
Any hacker can severely screw up or delete your database because of the way you use direct user provided data to build up your SQL query. Please instead read up on SQL Injection, and the use of PHP prepared statements.
Relevant