Converting mysql_query to mysqli_query - mysqli

I just moved to xampp version 7.0.13, which now has PHP 7.x, and the following query no longer works. I was Hoping someone can help me convert the following to mysqli query. I don't write code, so any help you could give me would be great.
// Count the number of rows in the member table
$rows = "SELECT * FROM $db_name.$tbl_name";
$count_rows = mysql_query( $rows );

here is your example with PDO:
$pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
$sql = 'SELECT * FROM :table';
$statement = $pdo->prepare($sql);
$count = $statement->execute(array('table' => 'your-table-name'))->rowCount();

Related

Joomla: get all users in a usergroup

I am working on a component where I want to show all users of a specific usergroup. Right now I found two solutions for this but I'm not feeling comfortable with both of them.
Solution 1
$usersID = JAccess::getUsersByGroup(3);
$users = array();
foreach($usersID as $cUserID)
{
$users[] = JFactory::getUser($cUserID);
}
This one seems to produce two database queries every time JFactory::getUser($cUserID) is called. I really don't want this.
Solution 2
function inside model
function getUsers()
{
if(!isset($this->users))
{
$groupID = 3;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$select = array( 'users.id', 'users.name');
$where = $db->quoteName('map.group_id') . ' = ' . $groupID;
$query
->select($select)
->from( $db->quoteName('#__user_usergroup_map', 'map') )
->leftJoin( $db->quoteName('#__users', 'users') . ' ON (map.user_id = users.id)' )
->where($where);
$db->setQuery($query);
$this->users = $db->loadObjectList();
}
return $this->users;
}
This one works like a charm but I feel there should be a "more Joomla! way" of doing this. I don't like working on their tables.
Right now I'm going with solution 2 but i really wonder if there is some better way to do it.

How to write native query in Doctrine / Postgres equivalent to a normal PDO_PGSQL

I have the following query in php with (pdo_pgsql) adapter:
$dsn = "pgsql:host=$host;port=5432;dbname=$db;user=$username;password=$password";
$conn = new PDO($dsn);
$query = 'SET search_path TO xyz_de;';
$result = $conn->query($query);
$query = 'Select * FROM "Orders" WHERE vendor_id=189 ';
$statement = $conn->query($query);
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
var_dump($row); // --> working perfectly fine, I see results here
}
I want to reproduce it using doctrine so I'm doing the following:
// given: 1) $this->em = EntityManager
// 2) the conenction is established successfull (I debugged it and sure about it)
$rsm = new ResultSetMapping();
$query = $this->em->createNativeQuery("SET search_path TO xyz_de ", $rsm);
$query->execute();
$query = $this->em->createNativeQuery('SELECT * FROM "Orders" WHERE vendor_id=?', $rsm);
$query->setParameter(1, 189);
$orders = $query->getArrayResult();
var_dump($orders); // Gives empty array (no errors)
as per my comment in the last line, the problem is that I get no results and no errors when using doctrine for this
Many things:
You can use addScalarResult
A simple example:
$rsm->addScalarResult('my_real_column', 'my_alias_column');
$query = $this->em->createNativeQuery('SELECT my_real_column FROM "Orders"');
var_dump($query->getScalarResult());
But I think, the best you can do is to use the queryBuilder.

How do I do this sql query in Zend?

How do I do this sql query in Zend Framework, I need to some how do this in the PDO context I think? I tried ->query but not sure if I am getting this right. The three variables are user_id and to and from date.
SELECT
ss.subcategory_id,
ss.subcategory_name,
ss.subcategory_issaving,
IFNULL(SUM(m.mv_monthly_total),0) AS expendsum
FROM
(SELECT
s.subcategory_id,
s.subcategory_name,
s.subcategory_issaving
FROM
subcategory s
WHERE
s.subcategory_isexpend = 'Y'
AND
s.subcategory_issaving = 'Y') ss
LEFT JOIN
mv_monthly m
ON ss.subcategory_id = m.mv_monthly_subcategory_id
AND m.mv_monthly_user_id = 2
AND m.mv_monthly_month >= '2010-01-01'
AND m.mv_monthly_month <= '2020-01-01'
GROUP BY
ss.subcategory_id,
ss.subcategory_name,
ss.subcategory_issaving
ORDER BY
ss.subcategory_issaving DESC,
expendsum;
I have tried the following with no luck
$db = Zend_Db_Table::getDefaultAdapter();
$dbExpr1 = new Zend_Db_Expr("s.subcategory_id, s.subcategory_name, s.subcategory_issaving");
$dbExpr2 = new Zend_Db_Expr("ss.subcategory_id, ss.subcategory_name, ss.subcategory_issaving, IFNULL(SUM(m.mv_monthly_total),0) AS expendsum");
$select = $db->select()
->from(
array(
'ss' => new Zend_Db_Expr(
'('. $db->select()
->from(array("s" => "subcategory"), $dbExpr1)
->where("s.subcategory_isexpend = 'Y'")
->where("s.subcategory_issaving = 'Y'") .')'
)
),
$dbExpr2
)
->joinLeft(array("m" => "mv_monthly"), "ss.subcategory_id = m.mv_monthly_subcategory_id")
->where("m.mv_monthly_user_id = ?", $user_id)
->where("m.mv_monthly_month >= ?", $fromMonth)
->where("m.mv_monthly_month <= ?", $toMonth)
->group(array("ss.subcategory_id","ss.subcategory_name","ss.subcategory_issaving"))
->order(array("ss.subcategory_issaving DESC", "expendsum"));
$row = $db->fetchAll($select);
For such a complex query, you can just execute it directly rather than using the object oriented approach as it gets fairly complicated with a query like that.
Try something like this, replacing my query with yours, and binding your variables into the query:
$db = Zend_Db_Table::getDefaultAdapter();
$stmt = new Zend_Db_Statement_Pdo($db, 'SELECT a, b, c FROM a WHERE username = ? AND date = ?');
try {
$res = $stmt->execute(array($user_id, $fromMonth));
if ($res) {
$rows = $stmt->fetchAll();
}
} catch (Zend_Db_Statement_Exception $dbex) {
// log Query failed with exception $dbex->getMessage();
}
If you prefer to use the object oriented approach, or need to because some parts of the query will be conditional, I usually build by subqueries up first as their own select, and you can simply embed those in to the main query with the select object for the subquery.
Here is what I mean by that:
$subselect = $this->getDbTable()
->select()
->from('mytable', array('time' => 'max(time)', 'id'))
->where('id IN (?)', $serialNumbers)
->group('id');
$select = $this->getDbTable()
->select()
->setIntegrityCheck(false)
->from('mytable')
->join('other', 'mytable.id = other.id', array('label'))
->join(array('dt' => $subselect),
'(mytable.time, mytable.id) = (dt.time, dt.id)', '');

How can i find the sql query statement of insert() in Zend Framework?

How can i find the sql query statement in Zend Framework for insert(), like its done for db table select's. $select->__toString().
Try this which work for me:
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$db->getProfiler()->setEnabled(true);
$profiler = $db->getProfiler();
$lastID = ($this->insert($data));
$query = $profiler->getLastQueryProfile();
$params = $query->getQueryParams();
$sqlQuery= $query->getQuery();
foreach ($params as $par) {
$sqlQuery = preg_replace('/\\?/', "'" . $par . "'", $sqlQuery, 1);
}
echo $sqlQuery;
You can't extract it since it's executed right away, but the code exists in Zend_Db_Adapter_Abstract::insert() and possibly overwritten in some of the adapters.

Translating a query to use Zend_Db_Select

I'm having some problems translating this query to use ZF's Zend_Db_Select:
SELECT b.id, b.title, b.description
FROM memberships AS m
JOIN blogs AS b ON b.id = m.blog_id
WHERE m.user_id = ?
ORDER BY m.created
LIMIT 0, 30
(this query works and returns results)
Memberships is a link table between blogs and users. It's a simple | id | blog_id | user_id | affair.
Here's what I have so far:
// $table = Zend_Db_Table instance, $id = a user id
$select = $table->select()
->from(array('m' => 'memberships'), array('b.id', 'b.title', 'b.description'))
->join(array('b' => 'blogs'), 'b.id = m.blog_id')
->where('m.user_id = ?', (int) $id)
->order('m.created DESC')
->limit(0, 30);
This is the (strange (to me)) error I'm getting:
#0: Select query cannot join with another table
Occurred on line 211 of D:\...\library\Zend\Db\Table\Select.php.
Thanks for your help.
You could also still use the traditional $model->select() object by adding setIntegrityCheck(false), like so.
$select = $table->select()
->setIntegrityCheck(false)
->from(array('m' => 'memberships'), array('b.id', 'b.title', 'b.description'))
->join(array('b' => 'blogs'), 'b.id = m.blog_id')
->where('m.user_id = ?', (int) $id)
->order('m.created DESC')
->limit(0, 30);
This disables the check that is throwing the exception:
#0: Select query cannot join with another table
When retrieved from your table object, the statement will be limited to that table I think. The Zend_Db_Table::select() methods returns a Zend_Db_Table_Select object which is a subclass of Zend_Db_Select and imposes this restriction. Try this instead:
$db = Zend_Db::factory( ...options... );
$select = new Zend_Db_Select($adapter);
$select->from( 'my_table_name' )->join( ...
If you prefer, the following should be equivalent:
$db = Zend_Db::factory( ...options... );
$db->select()->from( 'my_table_name' )->join( ...