Active Record in CodeIgniter 2 - mysql

I have this code:
$places = $this->db
->select('*')
->from('places')
->where('postal_code',$search)
->limit($limit, $start)
->get()->result();
I want to know if is there something wrong, and which is the way to get a query with a simple where inside the query.

Like this..
$places = $this->db->get_where('places',array('postal_code'=>$search),$limit,$start)->result();//outputs result in object format
$places = $this->db->get_where('places',array('postal_code'=>$search),$limit,$start)->result_array();//outputs result in array format
See more docs https://www.codeigniter.com/userguide3/database/query_builder.html

At the end I do it in other way, as I can see is there some issues to do a where and limit sentence in CodeIgniter in the same query.
So I do it directly in SQL
$query = "SELECT * FROM places WHERE locality = '".$search."' LIMIT ".$start.",".$limit."";
$places = $this->db->query($query)->result();
Not nice, but it works.

Related

How can i send one query result (via variable) into an other query

What I want is to include the result of sub variable into another query.
$sub = DB::table('chef_food_ethics')->
select(DB::raw('count(id) as fCount'))
->where('chef_food_ethics.food_ethic_id',
'=','food_ethic_managers.food_ethic_id')
->toSql();
Is it possible to include it like that?
$r = DB::table('food_ethic_managers')where
('food_ethic_managers.manager_id','=',$id)
->leftJoin('staff','food_ethic_managers.food_ethic_id'
,'=','staff.id')
->leftJoin('regions','staff.region_id','=','regions.id')
->with($sub)
->get();

Symfony Query in controller

$query = $em->query("
SELECT c.id AS id
FROM collectif c, zone z
WHERE
c.zone_id = z.id
AND z.label = '$zone'
ANDc.collectif = '$collectif'
");
$c = $query->fetchAll();
$idc = $c['id'];
I have this query that returns a single line, Symfony shows me an error as what variable id undefined
NB: I know that's don't respect the concept of Symfony [MVC] but it's for a particular reason so if someone can tell me how I can resolve this problem
Thank you
$query->fetchAll() should return numeric array of elements so key id does not exists. You should try $c[0]['id'] to get value.
If you'd rather use the results in the assocative way, you can use fetchAssoc() instead:
$c = $query->fetchAssoc();
$idc = $c['id'];
Here is the documentation for reference:
http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#fetchassoc
I'm just giving an alternate way to do this.

Find text with like

I want to find text in a MySql database
$result = mysqli_query($con,"SELECT * FROM blog
WHERE text_post LIKE = 't%';
")
or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
echo $row['titol_post'] . "<br>";
}
It gives me the error:
mysqli_error() expects exactly 1 parameter, 0 given...
If I substitute
WHERE text_post LIKE = 't%';
by
WHERE text_post = 'test';
It works well. I do not undestand. Why the LIKE does not work?
Here like after = is probelm please replace
with
WHERE text_post LIKE = 't%';
to
WHERE text_post LIKE 't%';
mysqli_error(), like all other mysqli_xx() functions, requires that you pass the connection variable to it, so that it knows which DB connection you want to know the last error for.
...
or die(mysqli_error($con));
...
Once you've done this, you will get a more useful error message that will help you diagnose the problem with your SQL code.
When you do get the real SQL error message, you will find that the problem is with the = sign.
The reason for this is that LIKE is an operator in the same way as =. You can only use one operator here, so if you're using LIKE, then you don't need = as well.
Your SQL code would therefore change to look like this:
SELECT * FROM blog
WHERE text_post LIKE 't%
I just changed like = to like and it works
SELECT * FROM blog WHERE text_post LIKE 't%'"
Try to pass conn in the error function:
or die(mysqli_error($con));
The MySQL syntax says:
string mysqli_error(mysqli link);
Returns the last error message for the most recent MySQLi function
call that can succeed or fail.
Also you need to remove the = sign after the LIKE keyword
$result = mysqli_query($con,"SELECT * FROM blog
WHERE text_post LIKE 't%';
")
or die(mysqli_error($con));
This is the right way to write sql query in mysql. Please replace your query with this.
$result = mysqli_query($con,"SELECT * FROM blog
WHERE text_post LIKE 't%';
")

Ruby: How can i extract just one MYSQL record in Ruby instead all with each_hash do

I know how to get all Mysql Results from a table and output it with each_hash.do in Ruby like this
results = con.query "SELECT * FROM table"
#results.each_hash do |row|
$url = row["Url"]
$name = row["linkname"]
$id = row["ID"]
#end
But how can i get only one record extracted from results?
You can use fetch_hash on the result.
e.g.
results = con.query "SELECT * FROM table"
record = results.fetch_hash
url = record["Url"]
# etc
There is also fetch_row which returns an array of the field values instead of a hash.
add a "limit 1" to your query? Or break out of the each_hash loop after the first :)

Symfony Propel criteria

Is there any possible way to convert the MySQL object into criteria object? I tried this query:
select
p.disrepid,
p.subject, p.body,
c.disrepid as disrepid1,
c.subject as subject1,
c.body as body1
from discusreply as p, discusreply as c
where p.distopid=' . $this->id . '
and (c.disrepid = p.parentid or c.parentid = p.distopid)
order by p.disrepid ASC
I tried a lot for converting this query into a Criteria, But nothing happened. I want this criteria object for passing this into Pager class for completing the pagination.
$pager->setCriteria($c);.
You can use your own SQL do perform a query, but there is no automated way to turn sql into a Criteria object.
$con = Propel::getConnection(DATABASE_NAME);
$sql = "SELECT books.* FROM books
WHERE NOT EXISTS (SELECT id FROM review WHERE book_id = book.id)";
$stmt = $con->createStatement();
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM);
$books = BookPeer::populateObjects($rs);
This bypasses Criterion objects all together. You mentioned wanting a criteria object so you could feed this into a pager. You can instead set a custom select method into your pager, which will then perform your custom query. If you need to pass a parameter into this, I would recommend extending sfPropel with your own pager class that can optionally pass parameters to your peer select methods so you don't have to use Criteria objects at all. As a quick alternative, you can do something like this, using your Criteria as a container for your select parameters:
$c = new Criteria();
$c->add(DiscussreplyPeer::ID, $myId);
$pager = new sfPropelPager();
$pager->setCriteria($c);
$pager->setPeerMethod('getReplies');
And then in your peer class:
public static function getReplies(Criteria $c) {
$map = $c->getMap();
$replyId = $map[DiscussreplyPeer::ID]->getValue();
$con = Propel::getConnection(DATABASE_NAME);
$sql = "select p.disrepid, p.subject, p.body, c.disrepid as disrepid1, c.subject as subject1, c.body as body1 from discusreply as p, discusreply as c where p.distopid=? and (c.disrepid = p.parentid or c.parentid = p.distopid) order by p.disrepid ASC";
$stmt = $con->prepareStatement($sql);
$stmt->setString(1, $replyId);
$rs = $stmt->executeQuery();
$results = array();
while ($rs->next()) {
// for example
$results['disrepid'] = $rs->getInt('disrepid');
}
return $results;
}
More tips on propel and symfony can be found at:
http://stereointeractive.com/blog/2007/06/12/propel-queries-using-custom-sql-peer-classes-and-criterion-objects/
This site will help a lot for learning to write criteria - you can use it to generate criteria code from pseudo SQL. I would also recommend grabbing the Symfony/Propel cheat sheets.
For your query in particular you will want something like this:
$c = new Criteria();
$c->addJoin(discusreply::DISREPID, discusreply::PARENTID, Criteria::INNER_JOIN);
$c->clearSelectColumns();
$c->addSelectColumn(discusreplyPeer::Disrepid);
...
$c->add(discusreplyPeer::DISTOPID, $this->id, Criteria::EQUAL);
...
$c->addAscendingOrderByColumn(discusreply::DISREPID);
I'm not sure that the Criteria system supports multiple clauses for an inner join so you may have to revert back to ad-hoc SQL for this query (if it does I would love to know how). The following code will create a ResultSet object similar to what you would get from simple database abstraction layers.
$sql = "SELECT ...";
$dbh = Propel::getConnection([DB]);
$sth = $dbh->createStatement();
$res = $sth->executeQuery($sql, ResultSet::FETCHMODE_NUM);
I don't think there is much of a disadvantage to using the ad-hoc method on a query like this since you will have to deal with ResultSet objects rather than table-specific objects when you are returning only specific columns.
You can try auto-generating the criteria from sql using this site.