mysql max function does not work in joomla - mysql

someone can tell me what is wrong in this code? I just want to get the last date in Joomla 2.5. Thanks
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select($db->quoteName('MAX(created)'))
->from($db->quoteName('#__content'))
$db->setQuery($query);
$result = $db->loadResult();
return $result;

don't quote functions:
$query
->select('MAX('.$db->quoteName('created').')')
->from($db->quoteName('#__content'));

A ; is missing at the end of the line ->from($db->quoteName('#__content'))

Related

codeigniter 3 $query = $this->db->query($queri_str); return 0 result

Good morning,
I have a problem with mysql and coeigniter 3.
if I request data with
$ query = $ this-> db-> query ($ queri_str);
it does not give me results.
if I enter the query on phpmyadmin it shows me two results.
$ queri_str = 'SELECT * FROM `my_table` WHERE` id_mytable2` = "'. $ id_name. '"';
The database tables were created with mysql workbench and automatically the reference to the main table with a 1: n ratio was added
Try this query
$this->db->select('*');
$this->db->where('id', '58e5j0m5bqrs7hk8suokko28hj7ni0v6');
$result = $this->db->get('ci_sessions')->result_array();
print_r($result);
Try this solution, you want to do a normal select,I don't know the query your wrote but
public fucntion get_data($id){
$this->db->select('*');
$this->db->from('your_table');
$this->db->where('id','=' ,'$id');
$query = $this->db->get();
$data = $query->result_array();
return $data;
}
the problem is back.
I'll explain.
function myfunction($id_myname) {
$this->db->select('*');
$this->db->where('id_myname', $id_myname);
//$query = $this->db->get('my_table');
$query = $this->db->get('my_table');
//print_r($query);
//var_dump($query);
if ( !$query ){
$error = $this->db->error(); // Has keys 'code' and 'message'
}
return $query->result();
}
when I call this function an empty value comes back to me.
While if I enter the value of the query in phpmyadmin I find two values

Preparing SQL query

In my PHP document, I got a SQL query looking like this:
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = "SELECT * FROM `objekt_t` WHERE `id`='" . $id . "'";
$row = mysqli_query($con, $q) or die(mysqli_error($con));
while($r = mysqli_fetch_assoc($row))
{
$objekt = $r;
}
}
I realize this is very unsafe practice concerning SQL injections and such, so I've been looking into prepared SQL querys, using bound parameters. Looking at bobby-tables.com I see this example query:
$stmt = $db->prepare('update people set name = ? where id = ?');
$stmt->bind_param('si',$name,$id);
$stmt->execute();
I do not understand how I should modify my current query to match the safer one using bound parameters. Any help is appreciated.
Just the same way
$mysqli = new mysqli("localhost", "my_user", "my_password", "db");
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = "SELECT some_field FROM `objekt_t` WHERE `id`= ?";
if ($stmt = $mysqli->prepare($q)) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
}
}
Now $result variable contains the resuts of your query.
prepared statements transmit raw data to the query so that SQL injection is not possible. There is no need to escape for real_escape_String or any other formatting functions, as this does it for you.
Example:
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE Username=?");
$statement->bind_param('s',$_POST['Username']);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
I am basically binding my $_POST data directly to the query because the data is being sent as raw, so even if the query contained a form of injection, as the $_POST['username']; the query will run as normal.
IN terms of the procedure and OOP style, it's down to preference, I personlly prefer the OOP style over the other options as it's more readable.
Working with numbers:
$ID= 5;
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID=?");
$statement->bind_param('i',$ID);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
Or you can work with exact values directly within the statement:
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID='5'");
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
You can do it like this:
$stmt = $mysqli->prepare('SELECT * FROM objekt_t WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// $row is an associative array
}

How to display the values returned by count in SQL

i keep having this error "mysql_fetch_array() expects parameter 1 to be resource, null given in" when i try to display the returned value of count in sql. heres my code.
$query="SELECT med_rec_ID, COUNT(med_rec_ID)
FROM med_issue
WHERE MONTH(issue_date) = MONTH('2013-02-05')
GROUP BY med_rec_ID";
$result= mysql_query($query);
while($count = mysql_fetch_array($display3)){
echo $count[0];
}
i have tried to run the query in sql alone it displays 2 columns (the med_rec_ID, and the COUNT). guys how do i display the count and fix the error too?
First of all, don't use mysql_* functions since they're deprecated. Use mysqli or PDO.
Secondly, look at what you're passing into the fetch_array function.
You probably want to do something like:
$link = mysqli_connect("localhost", "admin", "pass", "db_name");
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$medIds[] = $row['med_rec_ID'];
...
}
Then fix the count by giving it an alias.
Please note that you should actually store how you access the DB in a more secure manner, but I use this only to illustrate the example. Here's a pretty good post: How to create global configuration file?
Is your query even executing? that error will happen if mysql_query doesnt return the resource, in case query fails
$query="SELECT med_rec_ID, COUNT(med_rec_ID) as C FROM med_issue where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID";
$result= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row["C"];
}
Note: Please do not use mysql_* functions anymore
Give it an alias:
SELECT
med_rec_ID,
COUNT(med_rec_ID) TheCount
FROM med_issue
where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID
then you can select that column TheCount inside the while loop with $row['TheCount'], also use lope through the $result:
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo $row['TheCount'];
}

Joomla Database - How to use LIMIT in getQuery?

I want to build the below query using joomla inbuilt database class.
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
This is the query I have built up to now.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->nameQuote('*'));
$query->from($db->nameQuote(TABLE_PREFIX.'table_name'));
$db->setQuery($query);
$rows = $db->loadObjectList();
I don't know how to add the limit(LIMIT 1) to the query. Can someone please tell me how to do it? Thanks
Older than Joomla 3.0
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from($db->nameQuote('#__table_name'))
->order($db->nameQuote('id').' desc');
$db->setQuery($query,0,1);
$rows = $db->loadObjectList();
$db->setQuery function takes 3 parameters. The first one being the query, then the start, then the limit. We can limit records as shown above.
Newer than Joomla 3.0
setLimit(integer $limit, integer $offset)
If you want just one row
$query->setLimit(1);
Read more
This should work as well:
$query->setLimit(1);
Documentation: http://api.joomla.org/cms-3/classes/JDatabaseQueryLimitable.html
SetLimit doesn't work for me in Joomla 3.4.x, so try:
Within the model:
protected function getListQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
$query->from('#__your_table');
$this->setState('list.limit', 0); // 0 = unlimited
return $query;
}
Davids answer: https://joomla.stackexchange.com/questions/4249/model-getlistquery-fetch-all-rows-with-using-jpagination
Run that before the model calls getItems and it will load all the
items for you.
A few caveats with this.
You can also do this outside the model, so if for instance you were in
your view. You could do the following:
$model = $this->getModel(); $model->setState('list.limit', 0);
Sometimes you can do this too early, before the model's state has been
populated, which will cause the model to get rebuilt from the user
state after you have set the limit, basically overriding the limit.
To fix this, you can force the model to populate its state first:
$model = $this->getModel(); $model->getState();
$model->setState('list.limit', 0); The actual populateState method is
protected, so outside the model you can't call it directly, but any
call to getState will make sure that the populateState is called
before returning the current settings in the state.
Update: Just had to revisit this answer, and I can confirm, both the methods
setLimit & order are working if used as below.
$query->order($db->qn($data->sort_column_name) . ' ' . $data->sort_column_order);
$query->setLimit($length,$start);
OLD ANSWER
As of 08/Sept/14 The solutions from #Dasun or #escopecz arent working for me on J3.x
but this old trick is working for me which is nice,
$query->order($db->qn('id') . ' DESC LIMIT 25');
And About your specific requirement of wishing to fetch only 1 row you could use :
$rows = $db->loadObject();

use a single return from a sql query

I'm using PHP to make a very specific sql query. For example sake, I have the user's ID number, but I need their name. So I do a sql query from that table with the ID number in order to return the name.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
Now I want to use that. What's the most succinct way to go about making that result into a variable ths I can use?
edit:
I'm hoping that this is not the answer:
$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $val){
$username = $val;
}
}
}
I have used something like this to keep it short in the past:
list($name) = mysql_fetch_row(mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db));
echo $name;
In my opinion, the best way to fetch any SQL result is through mysql_fetch_assoc(). To use it, you would do something like this:
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name']; // You get an array with each column returned from your query.
}
Still, MySQL extension has been replaced for MySQLi, which is acknowledged to be faster and more practical. It has both OOP and structural bindings, and takes more into account your server settings.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$name = mysql_fetch_row($result)[0];
You should use MySQLi as bellow:
$db = new MySQLi($host,$user,$pass,$db);
$query = $db->query('SELECT name FROM users WHERE userID='.$thisuserid);
$result = $query->fetch_object();
echo $result->name;
If you use SELECT * so you also can access via $result->{field_name}