OK, I am new to AMFPHP. I can do simple sql statements with no problem.
Here are my classes of Schools and Locations:
class Schools {
public $id;
public $district_id;
public $school_name;
// explicit actionscript class
var $_explicitType = "components.Schools";
}
class Locations {
public $id;
public $school_id;
public $school_address;
public $icon_id;
// explicit actionscript class
var $_explicitType = "components.Locations";
}
This simple sql statement works with no issues:
/**
* Retrieves schools data
* #returns id, district_id, school_name
*/
public function getSchools() {
//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
//retrieve all rows
$query = "SELECT * FROM schools ORDER BY school_name";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new Schools();
$tmp->id = $row->id;
$tmp->district_id = $row->district_id;
$tmp->school_name = $row->school_name;
$ret[] = $tmp;
}
mysql_free_result($result);
return $ret;
}
However, I am having a hard time making a "somewhat" complex sql statement work properly.
/**
* Retrieves schools with locations data
* #returns school_name, school_address
*/
public function getSchoolsLocations() {
//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
//retrieve all schools with their locations
$query = "SELECT schools.school_name AS SNAME, school_address AS SLOC FROM schools, locations WHERE schools.id = locations.school_id";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new Schools();
$tmp->id = $row->id;
$tmp->school_name = $row->SNAME;
$ret[] = $tmp;
$tmp2 = new Locations();
$tmp2->school_id = $row->school_id;
$tmp2->school_address = $row->SLOC;
$ret2[] = $tmp2;
array_splice($ret, count($ret), 0, $ret2);
}
mysql_free_result($result);
return $ret;
}
BTW, SELECT schools.school_name AS SNAME, school_address AS SLOC FROM schools, locations WHERE schools.id = locations.school_id works perfectly in mysql.
It doesn't look like you are declaring $ret2.
FWIW: you might get better performance with your query if you format it as a join. Just a thought.
Related
Basically, this is what I wanted to do, how does it work?
public function get_product_category(){
$id = $this->uri->segment(3);
$query = $this->db->query('SELECT * FROM products where category_id = $id ');
return $query->row();
}
You could use Query Builder Class
public function get_product_category(){
$this->db->where('category_id', $this->uri->segment(3));
$query = $this->db->get('products');
return $query->row();
// return $query->row_array();
}
Or
public function get_product_category(){
$this->db->select('*');
$this->db->from('products');
$this->db->where('category_id', $this->uri->segment(3));
$query = $this->db->get();
return $query->row();
// return $query->row_array();
}
I would autoload the database library.
How to query below in zend 2
select * from states st where TRIM(LOWER(st.state_name))='noida'
Any help is appreciated.
Thanks
/* DB Adapter get and SQL object create */
$adapter = GlobalAdapterFeature::getStaticAdapter();
$sql = new \Zend\Db\Sql\Sql($adapter);
/* Select object create */
$select = new \Zend\Db\Sql\Select();
$select->from('states');
$select->where->addPredicate(
new \Zend\Db\Sql\Predicate\Expression(
'TRIM(LOWER(state_name)) = ?',
'noida'
)
);
/* Select object convert to string and execute */
$queryString = $sql->getSqlStringForSqlObject($select);
$result = $adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
Use following:
$resultStates=$this->states->select()->where('TRIM(LOWER(st.state_name))=?','noida')
->query()
->fetchAll();
For details refer Here and Here.
In you model file just use below code here I am using module profile.
Profile/Model/Common.php
namespace Profile\Model;
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
class Common
{
protected $dbConfig;
protected $adapter;
public function __construct($dbConfig)
{
$this->adapter = new Adapter($dbConfig);
}
public function getStateList()
{
$sql = "select * from states st where TRIM(LOWER(st.state_name))='noida'";
$statement = $this->adapter->query($sql);
$results = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($results);
$list = $resultSet->toArray();
return $list; // This will return a list of array
}
}
Profile/Controller/IndexController
namespace Profile\Controller;
use Profile\Model\Common;
class IndexController extends AbstractActionController
{
protected $dbConfig = array(
'driver' => DRIVER,
'database' => DB,
'username' => DBUSER,
'password' => DBPASS
);
public function init(){
$ssOrder = new Container(__CLASS__);
//SET OPTIONS
}
public function indexAction()
{
$plist = new Common($this->dbConfig);
$resultList = $plist->getStateList(); // This will give you state list
}
}
Good Luck
I am using this file to delete record from server
<?php
$dbhandle = mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ;
$selected = mysql_select_db("dbname" ,$dbhandle) or die(mysql_error()) ;
$id=$_POST['id'];
foreach($id as $value)
{
$query = mysql_query("DELETE FROM `record` WHERE `id`=$value");
}
mysql_close($dbhandle);
?>
but i am unable to delete record from the database. query is executing without any error but it cannot delete records from table
$query = mysql_query('DELETE FROM `record` WHERE `id` IN (' . implode(',', array_map('intval', $id)) . ')');
This will work even if $id array doesn't contain integers.
class db {
private static $instance = NULL;
private function __construct() {} //Make private
private function __clone(){} //Make private
public static function db() //Get instance of DB
{
if (!self::$instance)
{
self::$instance = new PDO("mysql:host=localhost;dbname=myDB;charset=utf8",'myUsername','myPassword',array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC));
}
return self::$instance;
}
}
if(count($ids)) { //Make sure you don't have an empty data set.
$qMarks = str_repeat('?,', count($ids)-1) . '?';
$sql ="DELETE FROM `record` WHERE `id` IN ({$qMarks})";
$stmt = $db::db->prepare($sql);
$stmt->execute($id);
}
I am using Yii MCV with multiple dbs.
Why does it take 15 seconds to run this code?
How to improve?
I switch the db connection using a server_id integer value.
This is the class that switches the db connection.
class VillageSlaveM extends VillageM {
const UNVERIFIED = 0;
const VERIFIED = 1;
public static function model($className = __CLASS__) {
return parent::model($className);
}
public static $server_id;
public static $slave_db;
public function getDbConnection() {
self::$slave_db = Yii::app()->dbx;
if (self::$slave_db instanceof CDbConnection) {
self::$slave_db->active = false;
$config = require(Yii::app()->getBasePath() . '/config/main.php');
$connectionString = $config['components']['dbx']['connectionString'];
self::$slave_db->connectionString = sprintf($connectionString, self::$server_id);
self::$slave_db->setActive(true);
return self::$slave_db;
}
else
throw new CDbException(Yii::t('yii', 'Active Record requires a "db" CDbConnection application component.'));
}
}
This is the code that needs 15 seconds to execute, dont know why so much.
It selects the one village that has the oldest last_update_resource timestamp value.
I have set indexes for all the db table fields involved.
$criteria = new CDbCriteria();
$criteria->condition = 'last_update_resource <= ' . ($time_start - 60 * 60 * 8);
$criteria->order = 'last_update_resource asc';
$criteria->limit = 1;
VillageSlaveM::$server_id = $world_id;
$start_x = time();
$model_village = VillageSlaveM::model()->findByAttributes(array('map_type_id' => VillageM::$map_type_id['village'], 'status' => VillageM::ACTIVE), $criteria);
$stop_x = time();
$msg[] = 'start_x: ' . ($stop_x - $start_x);
ps: after this code runs, i have much more complex queries and they run instantly;
i am new to PHP how to group functions inside a class and use it in other pages to reduce typing this is for single page what if i use multiple pages with pageination
this is my coding
<?php
include ('conn.php');
class sel
{
function sell()
{
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and
password ="'.$password.'"');
$x = $rdata['id'];
echo $x;
$_SESSION['username'] =$id;
echo $_SESSION['username'];
if(! $rdata)
{
echo "Enter your username and password correctly";
}
else
{
echo '<script type="text/javascript">
document.location="list.php";
</script>';
}
}
}
}
$myDBObject = new sel();
$myDBObject->sell();
?>
and my connection.php code is
<?php
class DBConnect
{
private $host = 'localhost';
private $user = 'root';
private $pass = '';
private $db = 'enquiry';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
}
$myDBObject = new DBConnect();
$myDBObject->__construct();
$myDBObject->select($select, $table, $where);
?>
if i did like this i get this error what did i do wrong in code
Fatal error: Call to private method DBConnect::select() from context '' in C:\xampp\htdocs
\Raj\cform\conn.php on line 23
You can use database class as mentioned below
class DBConnect
{
private $host = 'localhost';
private $user = 'user';
private $pass = 'pass';
private $db = 'mydb';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
// select query
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
// update query
private function update($update, $table, $where){
// code here
}
}
When required, create object of the class and call functions as below
require 'dbConnect.php'; // assuming, you have included the database class in this file
$myDBObject = new DBConnect();
$username = mysql_real_escape_string($_POST['username']); // mysql escaping
$password = mysql_real_escape_string($_POST['password']); // mysql escaping
// select required data
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and password = "'.$password.'"');
The function described in the class above are for demonstration purpose. You can include other functions in the class along with data escaping functionality.
FYI: mysql is deprecrated. Use mysqli or PDO instead. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
// Hi,
class ClassName {
static function funcName1(){
funcBody1;
}
static function funcName2(){
funcBody2;
}
}
// to use functions juste do :
ClasseName::funcName1();
ClasseName::funcName2();