PHP framework that allows both getRow and getRows? - php

I downloaded AlegroCart from https://code.google.com/p/alegrocart/ and I am trying to figure out which database framework is being used.
One of the methods being used is getRow:
$result = $this->database->getRow("select order_reference, total from order_google where order_number = '" . $orderNumber . "'");
but there is also a call to getRows:
$result = $this->database->getRows("select * from zone_to_geo_zone where geo_zone_id = '" ...
Does any one know which framework allows these two calls? I see that Pear framework has getRow but not getRows.
thanks

It's not really a framework but it seems like it's just some piece of (easy) code directly written by alegrocart :
function getRow($sql) {
$this->query($sql);
$row = mysql_fetch_assoc($this->result);
mysql_free_result($this->result);
return $row;
}
function getRows($sql) {
if (func_num_args()) { $this->query(implode(func_get_args(), ', ')); }
else { $this->query($sql); }
$rows = array();
while (is_resource($this->result) && $row = mysql_fetch_assoc($this->result)) { $rows[] = $row; }
if(is_resource($this->result)){
mysql_free_result($this->result);
}
return $rows;
}
https://code.google.com/p/alegrocart/source/browse/trunk/AlegroCart/upload/library/database/database.php

Related

ext js store/model example .net -converting php/mysql to .netwebservier/sql

Afternoon all,
I am working through a tutorial from MASTERING EXT JS and am stuck on retrieving data from db.
The book has been using examples using PHP and MYSQL... which I do not know. I use a .net web server and SQL, so I'm trying to convert this example from the tutorial, to how I would do it on my .net webserver.
the result in JSON format should be something like this
{
"data"[
{
"id":1",
"text" : "menu1",
"items": [
{"id": 2",
"text: "submenu2
},
{
"id":"3",
"text":"submenu3"
}
the php code they give me is this
php file 1
$permissions = retrievePermissions($userName); $modules =
retrieveModules($permissions); $result = retrieveMenuOptions($modules,
$permissions);
php file 2
function retrievePermissions($userName){
require('../db/db.php');
$sqlQuery = "SELECT p.menu_id menuId FROM User u ";
$sqlQuery .= "INNER JOIN permissions p ON u.groups_id = p.groups_id ";
$sqlQuery .= "INNER JOIN menu m ON p.menu_id = m.id ";
$sqlQuery .= "WHERE u.username = '$userName' ";
$permissions = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($user = $resultDb->fetch_assoc()) {
$permissions[] = $user['menuId'];
}
}
$resultDb->free();
$mysqli->close();
return $permissions; }
function retrieveModules($permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$sqlQuery = "SELECT id, text, iconCls FROM menu WHERE menu_id IS NULL AND id in $inClause";
$modules = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($module = $resultDb->fetch_assoc()) {
$modules[] = $module;
}
}
$resultDb->free();
$mysqli->close();
return $modules; }
function retrieveMenuOptions($modules, $permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$result = [];
foreach ($modules as $module) {
$sqlQuery = "SELECT * FROM menu WHERE menu_id = '";
$sqlQuery .= $module['id'] ."' AND id in $inClause";
// check if have a child node
if ($resultDb = $mysqli->query($sqlQuery)) {
// determine number of rows result set
$count = $resultDb->num_rows;
if ($count > 0){
$module['items'] = array();
while ($item = $resultDb->fetch_assoc()) {
$module['items'][] = $item;
}
}
$result[] = $module;
}
}
$resultDb->close();
$mysqli->close();
return $result;
I'm trying to figure out how to return the same json format using my .net webservice/SQL instead of php/MySQL.
It seems like it does 3 separate functions. And the result array is used as a parameter for the next query.
The basics seem easy... like for retreivePermissions... it is a simple SELECT WHERE statement.
retrieveModules seems to be an INNER JOIN with the first results.
But the last one... retrieveMenuOptions, it pulls in both results as parameters, and It returns results.
That is what I don't understand... how can I pull the results from SQL in the same JSON result format.
Am I making sense?
I have an example that uses a .NET Web API controller. Not exactly a web service, but you'll get the idea. Check it out here: http://jorgeramon.me/2015/ext-js-grid-search-with-net-and-mysql-backend/

Unable to add Codeigniter where in clause and where clause in mysql query

I am new to codeigniter and working on a project where I need to add search filters on a page. The way its been setup under applications/core there is a MY_Model.php file and here it the get_result function it.
function get_result() {
$this->db->from($this->tableName . ' ' . $this->alias);
$this->db->select($this->selectFields, FALSE);
for($j=0;$j<count($this->arrJoins);$j++){
$this->db->join($this->arrJoins[$j][0], $this->arrJoins[$j][1], $this->arrJoins[$j][2]);
}
$this->db->like($this->arrLike);
$this->db->or_like($this->arrOrLike);
if(isset($this->custLikeStr) && count($this->custLikeStr) > 0){
$this->db->where($this->custLikeStr);
}
$this->db->where($this->arrWhere);
$this->db->order_by($this->sortBy, $this->sortOrder);
$query = $this->db->get()->result();
//echo '<br>'.$this->db->last_query();
return $query;
}
There is a get_where function to build all where clauses
function get_where() {
foreach($this->arrWhereInputs as $arrWhereInput) {
if(isset($this->$arrWhereInput) && $this->$arrWhereInput != ''){
$this->arrWhere[$this->fieldAlias[$arrWhereInput].'.'.$arrWhereInput] = trim($this->$arrWhereInput);
}
}
return $this->arrWhere;
}
And in the model file for the application so under application/models here is there is a select function we need to call to get results.
function select(){
/* for search list */
$this->arrLikeInputs = array('stock_title', 'stock_id', 'price_band', );
$this->arrWhereInputs = array();
$this->arrWhere = array();
if ($this->input->post('record_per_page') != '') {
$records_per_page = $this->input->post('record_per_page');
} else {
$records_per_page = ROWS_PER_PAGE;
}
if (!(isset($this->record_per_page) && $this->record_per_page != '')) {
$this->record_per_page = ROWS_PER_PAGE;
}
$this->arrLike = $this->get_like();
$this->arrWhere = $this->get_where();
$this->arrWhere['SC.isDeleted'] = 0;
/* for search list */
if ($this->countQuery == 1) {
$this->db->from($this->tableName . ' ' . $this->alias);
$this->countSelectFields = 'COUNT(SC.stock_id) as cnt';
$result['count'] = $this->get_count();
}
$result['resultarr'] = $this->get_result();
$result['record_per_page'] = $records_per_page;
return $result;
}
Now I want to add where in to my query and I have tried a few ways but it just does not work.
I am getting confused on to where I am going wrong on such a simple thing.
So I have added a get_wherein function.
function get_wherein() {
foreach($this->arrWhereInInputs as $arrWhereInInput) {
if(isset($this->$arrWhereInInput) && $this->$arrWhereInInput != ''){
$this->arrWhereIn[$this->fieldAlias[$arrWhereInInput].'.'.$arrWhereInInput] = trim($this->$arrWhereInInput);
}
}
return $this->arrWhereIn;
}
So I added $this->arrWhereIn['Field'] = $arr which does not work and also tried to to call $this->db->where_in('field',$array) in the select function directly that does not work either. In both the cases it gets ignored and the query is build without the "and where in".
Where am I going wrong and how to build this query?

stopping duplicate urls in a form submission

I have a community site, where people can put up pages, and the url generates from their name. e.g. My Business, becomes my-business. I want to create a way, that if there is another My Business, it will check and make the url my-business-2, my-business-3, etc.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$slugs = array();
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
if(in_array($url, $slugs)) {
$max = 1;
while(in_array(($url . '-' . ++$max ), $slugs)) $url .= '-' . $max;
}
}
return $url;
}
This is my function, but this still wont work, as if there is a business called My Bus, it will make it my-bus-2, when it would have been unique at my-bus. I have experimented with other functions too, but this one is the closest I got. Can anyone tell me one that works perfectly?
So form my understanding, you are trying to avoid inserting/generating duplicate URL. Output will be something like this -
www.example.com/my-business
www.example.com/my-business-1
www.example.com/my-business-2
www.example.com/my-business-3
...
Try using this function -
function check_url($base_url, $new_url='', $num=0) {
if($new_url == '') {
$new_url = $base_url;
}
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url = '$new_url'");
if(mysqli_num_rows($qry) > 0) {
while($row = mysqli_fetch_array($qry)) {
$num++;
check_url($base_url, $base_url . '-' . $num, $num);
}
}
return $url;
}
Basically, this function will check the database until it finds a valid URL. Each time it will increment the number and recursively call the same function to generate new/valid URL.
Simple and basic!
#SpritsDracula has working code, but his function will query your database each time it executes. That being said, the recursion is a nice concept. Here is a piece of code that will save your the multiple database calls.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$baseUrl = $url;
$slugs = [];
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
$max = 1;
while(in_array($url, $slugs)) {
$url = $baseUrl . "-" . $max++;
}
}
return $url;
}

Programming CRUD functions in PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm writing some CRUD functions in PHP (not object oriented), and I ran into a little trouble. The function works just fine as is. Please review and read ahead for the actual issue I'm having. Here's the function:
<?php
function db_s(
$table,
$condition = array(),
$limit = '',
$order = array(),
$group = array(),
$return_query_string = false
) {
$sql = '
SELECT
*
FROM
`'. $table .'`
';
if (is_array($condition)) {
if (count($condition) > 1) {
$sql .= '
WHERE
';
$sql .= implode(' AND ', $condition);
}
elseif (count($condition > 0)) { $sql .= ' WHERE '. $condition[0] .' '; }
}
elseif ($condition != '' && is_string($condition)) { $sql .= ' WHERE '. $condition .' '; }
if (!empty($group)) {
$sql .= '
GROUP BY
';
$sql .= implode(', ', $group);
}
if (!empty($order)) {
$sql .= '
ORDER BY
';
$sql .= implode(', ', $order);
}
if ($limit != '') {
$sql .= '
LIMIT
'. $limit .'
';
}
//print '<pre>'. $sql .'</pre>';
$query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
if ($return_query_string) { return $sql; }
else { return $query; }
} // end db_s() function
?>
And here are some examples of how you would use it:
<?php
$results = db_s('users', 'active = 1');
while($row = mysql_fetch_assoc($results)) {
// do cool stuff here
}
?>
<?php
$results = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10);
while($row = mysql_fetch_assoc($results)) {
// do cool stuff here
}
?>
<?php
$results = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10, 'date DESC');
while($row = mysql_fetch_assoc($results)) {
// do cool stuff here
}
?>
<?php
$results = db_s('posts', 'unread = 1', '', 'date ASC', 'user_id', true);
print '<pre>'; print_r($results); print '</pre>';
?>
All of this works just fine (pending any syntax errors above but the function works fine). The problem is in the way I want to use the function. As you can see above, I must first establish the $results variable. Then I have to put the whole thing into a while loop with $row = mysql_fetch_assoc($results). That seems like too much work for me. In order to really make this function useful to me, I'd really like to rewrite it so I can use it like this:
<?php
while ($row = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10, 'date DESC')) {
// do cool stuff here
}
?>
Or like this:
<?php
while ($row = db_s('users', 'active = 1')) {
// do cool stuff here
}
?>
In order to do that, I've tried rewriting the end of the function (the part that actually returns the query), but I can't seem to get it to work correctly. I've tried something like this
}
//print '<pre>'. $sql .'</pre>';
$query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
if ($return_query_string) { return $sql; }
else { return mysql_fetch_array($query); } //<--- this line is modified
} // end db_s() function
?>
But it just doesn't work like that. Unfortunately the results are... spotty... when used like this. Often it returns more results than it should, and it only spits out the first result several times... I did rewrite the while() loop so it would use the function db_s() correctly. Can anyone provided me any insight as to why it wouldn't work like this? Or perhaps, how to return the results so I can use the function as I intend to? Any help is greatly appreciated. Thanks in advance!
You need to get on PDO or MySQLI now. The solution would be similar or you could use the *_fetch_all() for those libraries.
For the function return:
$query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
if($return_query_string) {
return $sql;
} else {
while($result[] = mysql_fetch_array($query)) {}
return $result;
}
Then use it like this:
foreach(db_s('users', 'active = 1') as $row) {
//do cool stuff here
}
I'm not endorsing the function or the code concept, just answering the question.

Accessing a variable in the function declared in model from the controller in Zend framework

I am quite new to OOPS and Zend. I am converting a part of web app code to Zend framework, I can't post all the code in here coz its quite lengthy. I created a model as in the code below(I can post only two functions) and I want to access the variables inside the functions from the controller and then print them out in HTML tables(I guess I will have to use "views" for that", below is my model:
public function getVenueTypes()
{
$poiTypes = array();
if($this->_cache)
{
$key = $this->getCacheKey()."poiTypes_stats:{$this->language}";
}
if(!$poiTypes)
{
$sql = "SELECT poi_type_id, poi_type_name_".$this->language."
AS
poi_type_name
FROM
poi_types
ORDER BY
poi_type_name_".$this->language." ASC";
$result = mysql_query($sql);
if(!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= "Whole query: \n\n$sql\n";
die($message);
}
while($row = mysql_fetch_array($result))
{
$poiTypes[] = array('id' => $row['poi_type_id'] ,'name' => $row['poi_type_name']);
}
print_r($poiTypes);
if ($this->_cache)
{
$this->_cache->save($key, $poiTypes);
}
}
foreach($poiTypes as $poiType)
{
$count_type = null;
if($this->_cache)
{
$key = $this->getCacheKey()."poiTypeCount:{$poiType['id']}:{$this->metro_id}";
$count_type = $this->_cache->load($key);
}
if(!$count_type)
{
$sql = "SELECT COUNT(*) FROM
poi
WHERE
find_in_set('{$poiType['id']}', poi_type_id_array)
AND poi_status = 1 AND poi_address_prefecture_id = '$this->metro_id'";
$result = mysql_query($sql) or die(mysql_error());
}
if(!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= "Whole query: \n\n$sql\n";
die($message);
}
while($count = mysql_fetch_array($result))
{
$count_type[$poiType['id']][$this->metro_id] = $count['COUNT(*)'];
}
if($this->_cache)
{
$this->_cache->save($key, $count_type);
}
}
}
Any help is Highly appreciated, I hope I am being clear enough and thanks in advance.
I'm noy sure if this will help you, but you have several options to access those values.
Option 1: return an array with the variables you need
return array($myVar1, $myVar2, ..., $myVarN);
Option 2 (less modular): create the html string inside that function and then echo or return the string.
Im assuming that you have a basic knowledge of Zend
The basic idea of Zend framework is the link between controller ,models and view
Your model file,BlaBla.php
Class Namespace_models_BlaBla extends Zend_Db_Table_Abstract{
public function foo(){
return 'hello world';
}
}
Your controller say BarController and an action say test
class BarController extends extends Zend_Controller_Action{
public function testAction(){
$class = new Namespace_models_BlaBla();
$this->view->string = $class->foo();
}
}
Your html side // test.phtml
<?php echo $this->string; ?> /**this will output hello world **/

Categories