Codeigniter DB or URI problem with unicode - mysql

I'm having a weird problem.
I have this code
$topic contains "海賊_(ONE_PIECE)" from URI /trends/about/海賊_(ONE_PIECE)
I checked to echo $topic and it prints out 海賊_(ONE_PIECE)
$sql="SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = ? LIMIT 1";
$query = $this->db->query($sql,array($topic));
if ($row = $query->result_array())
{
The problem is that this code returns $row to be an empty array
Array
(
[0] => Array
(
[redirect_title] =>
)
)
However, if I use this code (replacing ? with the actual value of $topic, it works perfectly
$sql="SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = '海賊_(ONE_PIECE)' LIMIT 1";
$query = $this->db->query($sql,array($topic));
if ($row = $query->result_array())
{
Replacing ? with {$topic} will not make it working too.
This problem only occurs when $topic contains ( ) if it doesn't have () it works fine
I wonder what is the problem.
I suppose there is a problem with URI encoding, but I'm not sure how to fix it.
Please help me.
Thank you

I'm pretty sure your problem is that query binding escapes your input values (im guessing it doesn't like brackets).
try building your sql string with concatenation, like:
$sql = "SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = '".$topic."' LIMIT 1";
$query = $this->db->query($sql);
and see if that helps. Or try the active record class, I use it for japanese characters all the time and it seems to work ok.
// EDIT:
To allow brackets in the URI, try and change application/config.config.php and set
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-()';
also try urldecode($topic); to get the kanji out.

Related

joomla select list from api

How do I generate a dropdown list with custom item in joomla 3.1. I took a look on couple of examples but I don not get the thing to work. I have been trying the following but the list is not genarated the html works.
public function getInput() {
$jinput = JFactory::getApplication()->input;
$sub_id = $jinput->get('sub_id');
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('*')
->from('#__unis_faculties')
->order('faculty_name');
$db->setQuery($query);
$rows = $db->loadObjectList();
//array_unshift($rows, JHtml::_('select.option', '', JText::_('COM_UNIS_FACULTIES'), 'value', 'text'));
return JHTML::_('select.genericlist',$rows,'faculties',array('class'=>'nourritures','option.attr'=>'data'));
}
Your code actually does not look to have problems.
As long as the query returns something you are on the right track.
Change select('*') to select('COL_A as value, COL_B as text').
Make sure you echo the result of the method getInput (not a great name btw, how about getFacultiesDropdown()

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

"No result was found for query although at least one row was expected." Query should display records though in Symfony

I'm trying to retrieve content using two items in the URL. Here is the php/symfony code that should do it:
$em = $this->getDoctrine()->getEntityManager();
$repository = $this->getDoctrine()
->getRepository('ShoutMainBundle:Content');
$query = $repository->createQueryBuilder('p')
->where('p.slug > :slug')
->andWhere('p.subtocontentid > :parent')
->setParameters(array(
'slug' => $slug,
'parent' => $page
))
->getQuery();
$content = $query->getSingleResult();
However, when this code is executed it returns the following error:
No result was found for query although at least one row was expected.
I have done some tests, and the data held in the $slug and $page variables hold the correct information. I have also tested the MySQL query and the query brings up the desired result, which confuses me further.
Have I missed something?
As it was answered here
You are getting this error because you are using the
getSingleResult() method. it generates an Exception if it can't find
even a single result. you can use the getOneOrNullResult() instead
to get a NULL if there isn't any result from the query.
Query#getSingleResult(): Retrieves a single object. If the result
contains more than one object, an NonUniqueResultException is thrown.
If the result contains no objects, an NoResultException is thrown. The
pure/mixed distinction does not apply.
No result was found for query although at least one row was expected.
Another reason could be:
You did this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
return $query->getSingleResult();
Instead of this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
$query->setMaxResults(1);
return $query->getResult();
Don't you want to use "=" instead of ">" ?
If you've got this message because used
$content = $query->getSingleResult();
you can just replace it with the row below
$content = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ?? 0;

JSON encode comma delimited row

I'm trying to add an autocomplete tokenizer script to some form fields and one issue I'm having is if a person saves multiple values for the field the autocomplete suggestions come back with all of his values as one long value instead of them being single values delimited by the comma. I first tried to simply explode the value but it doesn't format it correctly in the JSON encode.
Here is my PHP file:
//connection information
$host = "localhost";
$user = "myuser";
$password = "mypass";
$database = "mydb";
$param = ($_GET["term"]);
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT cb_activities FROM jos_comprofiler WHERE cb_activities REGEXP '^$param'");
//build array of results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$activities[$x] = array(cb_activitiesterm => $row[cb_activities]);
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($activities) . ")";
echo $response;
mysql_close($server);
This gives the output like this:
[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,hockey,"}]
but I need it to output like this:
[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,"},"cb_activities":"hockey,"}]
I also need to find a way to prevent duplicate entries from populating. For instance, the way it is now, say 10 people all have kicking cats selected as a value, it will display 10 times in the autocomplete suggestions.
How do I set this up to correctly delimit at the commas and then weed out duplicate values?
NM the duplicate issue, I just added select distinct instead of just select, this json thing has me overcomplicating things now lol. Now if I can just figure out how to delimit properly at the comma all will be good.