I'm trying to create a drop down list that populates a <select> with options pulled from a DISTINCT argument. Code looks like this:
function cityData() {
$db =& JFactory::getDBO();
$query = "SELECT DISTINCT MSTCITY FROM " . $db->nameQuote('#__mls') . " ORDER BY MSTCITY;";
$db->setQuery($query);
$tbl = $db->loadObjectList();
echo $tbl;
}
Now, I have two views: one is RAW for an AJAX call and the other is the default view. I figured the simplest way would be to just use the default view and do it in PHP, since the default view wasn't really being used for much anyway. So I added a function:
function dropList($tpl = null){
$model = &$this->getModel();
$array = $model->cityData();
$this->assignRef('array', $array );
parent::display($tpl);
}
And then a call in the page
<?php
$thing = $this->array;
echo $thing;
?>
Nothing is being displayed for the echo $thing;. In the past, when I used PHP to build content instead of AJAX, this worked fine. I don't know if it's using loadObjectList() that's not giving me anything or what. I know the mySQL query works, as it's be tested in the cmd and I get the result I expect.
In order to debug and see the array values you need to use print_r.
In your case edit the default.php file to
<?php
$thing = $this->array;
print_r($thing);
?>
You can also use var_dump
Related
I ve been at this for a few days now. I want to read the products from the database and return them in a JSON to the front page so I can use it. The problem is i dont even know how to read form db.
I ve tried making a plugin but i dont know how to do that either. I ve tried making a separate php script and using global $wpdb but no response. Any help appreciated.
I tried this in a php script.
<?php
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );
echo $results;
?>
Thank you in advance!
<?php
// gets the global $wpdb variable
global $wpdb;
// put the query in its on variable to be able to include your database prefix
$query = "SELECT * FROM ". $wpdb->prefix ."options WHERE option_id = 1";
// get database results from the query and stores it as a stdObject
$results = $wpdb->get_results($query);
// if something is found, convert the resulting stdObject into a json object
if ($results) {
$json = json_encode($results);
print_r($json);
}
?>
This should return your json string. I ran it myself on my wordpress installation and it worked without a hitch.
For me, this returned:
[{"option_id":"1","option_name":"siteurl","option_value":"https://your_url_here.com","autoload":"yes"}]
EDIT
This can be included in a plugin or in the loop.
Another note: if you'd turn on debugging you'd see that you can't echo arrays out as a string :) You'd need to do this:
<?php print_r($result); ?>
I am a beginner trying to make a webpage where a schedule of reservations is being retrieved from the database. In a php file I have a class that has a function that creates a query using a SELECT statement, here is the function
public function getDTodayScheduleDB(){
$session=Modulator::getSession();
$session->start();
$currentdrID=$_SESSION['userID'];
$todayDate = date("Y/m/d");
$getTSchedule = "SELECT time, user.name FROM reservation FULL JOIN user ON childID = user.ID AND doctorID = '$currentdrID' AND date = '$todayDate'";
$result = Modulator::getDb()->query($getTSchedule);
return $result;
}
I am not sure if this is the right way to do it or not but I read this when I tried googling it. the $result variable is returned in a php file and used like this
<?php
include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Models/DoctorModel.php');
$scheduleResult = DoctorModel::getDTodayScheduleDB();
while($row = mysqli_fetch_assoc($scheduleResult)){
$appTime = $row['time'];
$childName = $row['name'];
echo"<tr>";
echo"<td>".$appTime."</td>";
echo"<td>".$childName."</td>";
echo"</tr>";
}
?>
However I do not know why it is not working although I tested the query elsewhere and it works so he problem is with the variable passing from the function to the other page I guess.
Using the :: operator, you are calling a non static (i.e instance method) function as if it was a static function. Assuming that your getDTodayScheduleDB is inside a DoctorModel class, you have to define it this way:
public static function getDTodayScheduleDB(){
//your code here
}
This is the one thing that I am trying absolutely first time. I have made few websites in PHP and MySQL as DB but never used functions to get data from database.
But here is the thing that I am trying all new now as now I want to achieve reusability for a bog project. I wanted to get the order details from DB (i.e. MySQL) through PHP Function. I am bit confused that how to print values returned by a PHP function.
Function wrote by me is as below:
function _orderdetails(){
$sql = "Select * from orders WHERE 1";
$result = DB::instance()->prepare($sql)->execute()->fetchAll();
return $result;
}
Please let me know how i can print these values and value returned by above function is an array.
I tried by calling function directly through print_r(_orderdetails());
Please let me know:
Efficient way of iterating through this function to Print Values.
Is there any other approach that can be better worked upon?
You cannot chain fetchAll() to execute() like this.
Besides, for a query that takes no parameters, there is no point in using execute(). So change your function like this
function _orderdetails(){
$sql = "Select * from orders WHERE 1";
return DB::instance()->query($sql)->fetchAll();
}
and so you'll be able to iterate results the most natural way
foreach (_orderdetails() as $order) {
echo $order['id'] . '<br />';
}
You can also use ->fetch();
Instead of ->fetchAll();
There some other functions that also work as a worker to iterate through the next row in the table.
You can check PDO for more functions at:
http://php.net/manual/en/book.pdo.php
In your PHP code that will call this function use the following
print_r(_orderdetails());
//to get all the result set... I mean all the values coming from this function.
You can also use the function and use -> after the function call, then put the variable name as follows:
To iterate through the values of this function:
$value_arr = _orderdetails();
foreach ($valur_arr as $value) {
echo $value . '<br />';
}
This way you will echo 1 column from the database table you are using.
I am sure that this question has been asked before, but I am unable to come up with the proper keywords (especially in english).
I am using PHP and I am trying to for loop through a parameter of a function. So the function should be called, store the retrieved data in some variables and these variables should then be inserted into a database.
However, the loops only runs once! If I substitute $id with any number it works fine, but only once.
This is a simplified version of my code:
for ($i=0; $i<9; $i++) {
$id = $rows[$i][1];
$values = getDetails($id); // This function (from another file) returns an array
$title = $values["Title"];
$year = $values["Year"];
$query= " INSERT INTO database
VALUES ('','$title','$year')";
$result = $mysqli->query($query);
}
* EDIT This is part of the getDetails function:
function getDetails($id) {
$url = "http://www.something.de/". $id . "/";
$html = file_get_html ( $url );
$title = $html->find('span[itemprop=name]');
$title = explode('>',$title[0]);
$title = explode('</span',$title[1]);
... // This might look weird and is definatly not perfect, but it works :)
$details = array("Title" => $title[0], "Year" => $year[1]);
return $details;
}
* EDIT
WOW! I found the reason ... I had a function within my function which was never used. I just commented it out and my code works just fine. I assume it is not a good idea to so anyways.
I think your $query is wrong.
Change this:
$query= " INSERT INTO database
VALUES ('','$title','$year')";
To something like this:
$query= " INSERT INTO database (field1,field2,field3)
VALUES ('','$title','$year')";
Is your ID field autoincrementing? If so you do not need the "field1" entry at all.
Happy Coding!
I had this problem also.
I could print to a table without a problem the parameters I was feeding into a function in a loop. But the function calls in the loops would only call once.
SOLUTION: Remove the location redirects and the exit(); from the function.
Hope this helps someone else.
I was wondering if there was a way to echo out the full query with limit and limitstart etc. I can echo out the line $query, but i want to see why the limit isn't working and I can't seem to get it to display the actual query that it's sending to the database.. Here's the code:
$params =& JComponentHelper::getParams('com_news');
$limit = $params->get('x_items', 5);
$limitstart = JRequest::getVar('limitstart', 0);
$query = "SELECT * FROM #__news WHERE published = 1 AND catid = ".$Itemid." ORDER BY date DESC";
$db->setQuery($query, $limitstart, $limit);
$rows = $db->loadObjectList();
$db->getQuery($query, $limitstart, $limit); is only displaying "SELECT * FROM jos_news WHERE published = 1 AND catid = 8 ORDER BY date DESC" which doesnt have the LIMIT params on the end of the query..
Any help would be appreciated :)
The JDatabaseQuery object has a __toString() function that outputs the query so you can do:
echo $db->getQuery();
Or if you want to pass it to a function you can explicitly cast it to a string first:
var_dump((string)$db->getQuery());
var_dump($db);die;
Do that after the loadObjectList() call. Inside the $db variable there must be a _sql attribute that is the last query executed.
Agreed with the previous answers, but... In case you are developing your own components, since I often want to know for sure what exactly is executed too, here's a simple solution:
In your models put:
$db = JFactory::getDBO();
echo $db->getQuery();
Where you want to know the query... Don't put it in (for example) your view, since it might have loaded some other dropdown list by way of execution in the meantime...
For example:
For a list-view put it right before the foreach ($items... in the public function getItems() of the model.
In a form-/item-view put it right before the return $data / return $item in the protected function loadFormData() / public function getItem($pk = null)
Hope this helps...
On new joomla versions, you need to echo __toString() on query object.
echo $query->__toString();
I get this info on this joomla answer.
Hope this helps
Joomla provides $query->dump(). To add convenience, I like to wrap it in enqueueMessage() so that the presented string is at the top of the webpage.
JFactory::getApplication()->enqueueMessage(
$query->dump(),
'notice'
);
IMPORTANT: You should never show the raw SQL string or a raw query error string to the public.
See some of my implementations at Joomla Stack Exchange.