Ajax not calling on php query when joining multiple table - php

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');

Related

How to remove 5 characters from the end of every column in a table MySQLi

I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))

Check for validation from different tables - joomla

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;
}

Joomla mysql query isnt working correctly

I have the following code:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "UPDATE #__cspartners_partners SET estado = '".TpoEstadoDocumentacion::Revisar."' WHERE id='" .$id. "'";
$db->setQuery($query);
$resultado = $db->query();
if(!$resultado) return 0;
$query returns this:
string(60) "UPDATE #__cspartners_partners SET estado = '3' WHERE id='1'"
And $resultado returns this:
bool(true)
If I execute this query directly in phpMyAdmin it works fine but its not working in my code. What am I missing?
Please refer to the Documentation for writing database queries so that you are aware of the latest coding standards.
For the query use this:
$value = TpoEstadoDocumentacion::Revisar;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$fields = array(
$db->quoteName('estado') . ' = ' . $db->quote($value)
);
$conditions = array(
$db->quoteName('id') . ' = ' . (int)$id
);
$query->update($db->quoteName('#__cspartners_partners'))->set($fields)->where($conditions);
$db->setQuery($query);
$result = $db->execute();

Display COLUMN NAMES from database through PHP

I am trying to pull all the column names from my database 'settings' and list them in PHP.
A bit of research has come up with the following:
SHOW COLUMNS FROM settings
but I don't know how to go about listing these off through PHP.
it would be helpful if any code posted was a prepared statement format, but not required.
Here is my PHP, it's giving me this error:
Notice: Undefined index: sThumbWidth in /home/demomycm/public_html/subdomains/mercury/eshop/library/classes/class.settings.php on line 204
for every field in my database.
$loadColumns = array();
$query = "SHOW COLUMNS FROM settings";
$result = $this->glob->dbConn->query($query);
if($this->glob->dbConn->errno) {
trigger_error('An error occurred whilst loading counties from the database.' . PHP_EOL . 'Query: ' . $query . PHP_EOL . 'Error[' . $this->glob->dbConn->errno . ']: ' . $this->glob->dbConn->error, E_USER_WARNING);
} elseif($result->num_rows) {
while($row = $result->fetch_assoc()) {
$loadColumns[$row['Field']];
}
return $loadColumns;
}
$loadColumnsHtml = '';
$loadColumns = $this->Settings->LoadColumns();
foreach($loadColumns as $i => $field) {
$loadColumnsHtml .= '<div class="home-stat-small-link">' . ($i + 1) . '. <strong>' . $field['Field'] . '</strong>.</div>';
}
use describe
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
In your code you have $loadColumns as an array.
This line does nothing: $loadColumns[$row['Field']];
Basically your getting the value in $loadColumns with the key associated with $row['Field'] and not assigning anything.
You want something like this perhaps for that line:
array_push($loadColumns,$row['Field']);
Full code below
$loadColumns = array();
$query = "SHOW COLUMNS FROM settings";
$result = $this->glob->dbConn->query($query);
if($this->glob->dbConn->errno) {
trigger_error('An error occurred whilst loading counties from the database.' . PHP_EOL . 'Query: ' . $query . PHP_EOL . 'Error[' . $this->glob->dbConn->errno . ']: ' . $this->glob->dbConn->error, E_USER_WARNING);
} elseif($result->num_rows) {
while($row = $result->fetch_assoc()) {
array_push($loadColumns,$row['Field']); //<-- this line has been changed
}
return $loadColumns;
}
$loadColumnsHtml = '';
$loadColumns = $this->Settings->LoadColumns();
foreach($loadColumns as $i => $field) {
$loadColumnsHtml .= '<div class="home-stat-small-link">' . ($i + 1) . '. <strong>' . $field['Field'] . '</strong>.</div>';
}
On MySQL connection (deprecated) you can use:
mysql_list_fields
On PDO (recommend) use:
$query = $dbh->prepare("DESCRIBE tablename");
$query->execute();
$tableFields = $query->fetchAll(PDO::FETCH_COLUMN);
On PDO you can also use PDOStatement::getColumnMeta(). But it has the status: EXPERIMENTAL

PHP MySQL result issue when using a variable in the WHERE Clause

I am having a pretty weird problem with my PHP MySQL Query, I am trying to return rows that have the correct rname, rcity, and rstate values.
$sql = "SELECT * FROM `images` WHERE rname = '" . $rname . "' AND rcity = '" . $rcity . "' AND rstate = '" . $rstate . "'";
When I run that query, it only returns 0 results. However after some playing around with it, If I only use rname and rstate in the WHERE Clause it returns results.
$sql = "SELECT * FROM `images` WHERE rname = '" . $rname . "' AND rstate = '" . $rstate . "';
That works perfect. So when i tried just useing rcity in the WHERE Clause.
$sql = "SELECT * FROM `images` WHERE rcity = '" . $rcity . "'";
0 results return. So something is wrong with the rcity portion of the query. If I hard write the value into the query instead of the $rcity variable, it pulls up results. I doubled checked to make sure $rcity was declared, it has the correct value, etc.
I also created another test table in the database to check to see if it was a problem on the db side. Which the problem still existed.
Here is the full code of the getQuery() Function
private function getQuery($data){
// Takes raw data and creats image(s) query to search for listing resort...
$listing = $data['listing'];
$rname = $data['rname'];
$rcity = $data['rcity'];
$rstate = $data['rstate'];
$query = "SELECT * FROM `test` WHERE rname = '" . $rname . "' AND rcity = '" . $rcity . "' AND rstate = '" . $rstate ."'";
return $query;
}
And Here is my database class
class db {
public function __construct(){
$this->server = DB_SERVER;
$this->user = DB_USER;
$this->Pass = DB_PASS;
$this->Database = DB_Database;
}
protected function connect(){
return mysqli_connect($this->server, $this->user, $this->Pass, $this->Database);
}
public function query($sql){
$conn = $this->connect();
$query = $conn->query($sql);
if($query == false) {
throw new Exception("Query failed:".PHP_EOL.$conn->error.PHP_EOL.$sql);
}
if($query->num_rows == 0) {
// need E_NOTICE errors enabled to see this,
// on screen if display_errors is on, else in PHP error log
trigger_error("Query returned 0 rows:".PHP_EOL.$sql);
}
$result = array();
while ($row = $query->fetch_assoc()){
$result[] = $row;
}
return $result;
}
}
I call the query in a class __construct function like so
$con = new db;
$sql = $this->getQuery($data);
$result = $con->query($sql);
I think problem can be with syntax or mysql screening. Try to use PDO with bindParam method
$sql = "SELECT * FROM `images` WHERE rname = '$rname' AND rcity = '$rcity' AND rstate = '$rstate'";
Try to implement this i.e. using variable directly between ' (apostrophe), It should work perfect

Categories