I have declared two databases in my database.php, how i can access the users list of db and db2 instances
//database initialisation
$CI =& get_instance();
$CI->db1 = $CI->load->database('default', TRUE);
$CI->db2 = $CI->load->database('stylior_db', TRUE);
//select query for db2
$this->$db2->from('users');
// $this->$CI->db2->where('id',1312);
$query = $this->$CI->db2->get();
print_r($query);
if ( $query->num_rows() > 0 )
{
$row = $query->row_array();
return $row;
}
Try this way
$db_result = $this->db->get("table_users"); // here default database connected
$this->db1 = $this->load->database('db1', TRUE);
$db1_result = $this->db1->get("table_users")
You can use $this keyword directly to get you result. You can use following code to get results:
//database initialisation
$CI =& get_instance();
$this->db1 = $this->load->database('default', TRUE);
$this->db2 = $this->load->database('stylior_db', TRUE);
//select query for db2
$this->$db2->from('users');
// $this->db2->where('id',1312);
$query = $this->db2->get();
print_r($query);
if ( $query->num_rows() > 0 )
{
$row = $query->row_array();
return $row;
}
Related
In mysql, we use
$userdata = mysql_fetch_assoc(mysql_query("select * tablename where id=".$_SESSION['user_id']."));
And then we can use $userdata anywhere on that page....
How can we do it with mysqli without using foreach or while statement ?
What I have tried is
<?
include ("db.php");
session_start();
if(isset($_SESSION['user_id']))
{
$userid = $_SESSION['user_id'];
$query = "SELECT * FROM mytable where id= '$userid'";
$userdataraw = $database->get_results($query);
$userdata = $userdataraw ->fetch_assoc();
}
?>
Class Used as :
public function get_results( $query, $object = false )
{
self::$counter++;
//Overwrite the $row var to null
$row = null;
$results = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
return false;
}
else
{
$row = array();
while( $r = ( !$object ) ? $results->fetch_assoc() : $results->fetch_object() )
{
$row[] = $r;
}
return $row;
}
}
When I tried This, I got error
Fatal error: Call to undefined function fetch_assoc()
I want set $userdata without foreach or while, is it possible in Mysqli??
The get_resultsfunction already returns an associative array if the second parameter is not set or false. Thus there is no need to call fetch_assoc() again.
Also if you only expect a single dataset and don't want to use a loop you would need to do something like this: $userdata = $userdataraw[0]to get the first and only dataset.
So do not have an idea why this function is not working? i am trying to select all the ids from the table but nothing is selected.
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows = ('value'=>$record, 'label'=>$record);
}
return $rows;
}
this function below works fine, I need the function above to do the same as teh function below.
public function toOptionArray()
{
return array(
array('value'=>1, 'label'=>'one'),
array('value'=>2, 'label'=>'Two'),
array('value'=>3, 'label'=>'Three'),
array('value'=>4, 'label'=>'Four')
);
}
There are a couple of issues with your code:
You're only selecting a single item (id, but later, I assume you're expecting an ID and a value).
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
record is an array from your SQL query, so you should be treating it as such. eg. $record['id']
$rows you want as an array, but you're overwriting it each time, so $rows[] = makes more sense
Something like:
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id, label FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows[] = array('value'=>$record['id'], 'label'=>$record['label']);
}
return $rows;
}
Try using the core read/write resource. Change
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
To
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
I have a function query:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
The function works just fine when I use it like this:
$g = "05%";
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $g);
print json_encode($result);
However I am getting no result when $g is a value retrieved from a method. For example lets say I have a method getMonth() from a class Date that returns the current month of May as 05% when echoed. I try the code below and get nothing from the database:
$time = new Date();
//$g = "05%"; this would definitely get results from the db
$h = $time->getMonth();
echo $h; //this displays 05% on the screen
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $h);
print json_encode($result);
I am pretty sure that I am making a simple mistake, but I can't seem to figure it out. How can I fix this? Any help would be greatly appreciated.
Do something that your method return only 05 part from 05%. and append % after that for example
$h = $time->getMonth();
$h = "$h%";
and then it should work
How can I make this function
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$new_db = $this->load->database('budget_db', TRUE);
$q = "select * from budget where sy=$current_year
AND sy_dummy=$year_dummy";
$query = $new_db->query($q);
return $query->result();}
to somewhat like this.
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$new_db = $this->load->database('budget_db', TRUE);
$this->db->select('*');
$this->db->from('budget');
$this->db->where("sy",$current_year);
$this->db->where("sy_dummy",$year_dummy);
$query = $this->db->get();
return $query->result();}
The top function is correct but the bottom function is obviously wrong(I don't know how to select table from other db). I'm also connecting to other database and I'm selecting table from the other database(budget_db).
Hope you understand my problem.
I think you just need to use $new_db which is instance of budget_db.
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$new_db = $this->load->database('budget_db', TRUE);
$new_db->select('*');
$new_db->from('budget');
$new_db->where("sy",$current_year);
$new_db->where("sy_dummy",$year_dummy);
$query = $new_db->get();
return $query->result();
}
Hope this might be useful for you.
Supposedly, 'budget_db' is the other database you are trying to connect to, make sure it has its own group defined in the database config. Otherwise, you can connect to it using
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$config['hostname'] = "hostname";
$config['username'] = "db_user";
$config['password'] = "db_pass";
$config['database'] = "budget_db";
$config['dbdriver'] = "mysql";
$new_db = $this->load->database($config, TRUE);
$new_db->select('*');
$new_db->from('budget');
$new_db->where("sy", $current_year);
$new_db->where("sy_dummy", $year_dummy);
$query = $new_db->get();
return $query->result();
}
By adding the parameter TRUE to the load database method, $new_db becomes the database object of budget_db.
I have 3 files:
DB.class.php - which handles all the databases.
Site.class.php - contains a function to return the latest entries in a database.
index.php - trying to print the array passed.
I am trying to pass an array into index.php from Site.class.php which is using a function from DB.class.php to put the mysql results into an associative array.
index.php:
<?php
// index.php
include 'classes/Site.class.php';
$site = new Site();
print_r($site->latestBookmarks());
?>
Site.class.php:
<?php
// Site.class.php
require_once 'DB.class.php';
class Site {
function latestBookmarks() {
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
$db = new DB();
return $db->processRowSet($result);
}
}
?>
DB.class.php:
<?php
// DB.class.php
class DB {
protected $db_name = "project";
protected $db_user = "root";
protected $db_pass = "root";
protected $db_host = "localhost";
// Open up a connection to the database.
public function connect() {
$connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
mysql_select_db($this->db_name);
return true;
}
// Takes a MySQL row and returns an associative array where the keys in the array are the column names in the row set.
public function processRowSet($rowSet, $singleRow=false) {
$resultArray = array();
while ($row = mysql_fetch_assoc($rowSet)) {
array_push($resultArray, $row);
}
if ($singleRow === true)
return $resultArray[0];
return $resultArray;
}
// Select rows from the database.
public function select($table, $where) {
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
return $this->processRowSet($result, true);
return $this->processRowSet($result);
}
// Update a current row in the database.
public function update($data, $table, $where) {
foreach ($data as $column => $value) {
$sql = "UPDATE $table SET $column = $value WHERE $where";
mysql_query($sql) or die(mysql_error());
}
return true;
}
// Insert a new row into the database.
public function insert($data, $table) {
$columns = "";
$values = "";
foreach ($data as $column => $value) {
$columns .= ($columns == "") ? "" : ", ";
$columns .= $column;
$values .= ($values == "") ? "" : ", ";
$values .= $value;
}
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
mysql_query($sql) or die(mysql_error());
return mysql_insert_id();
}
}
?>
A few problems I noticed:
You run a query in function latestBookmarks before you connect to the db;
In your function connect you connect to a database, but the result is discarded immediately, $connection is lost as soon as the function finishes.
You have no connection to the database when you run this line:
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
You will need to adjust your code to send the query string to the DB instance for processing. You can add a method to DB to execute mysql_query, and pass the query in like from Site:: latestBookmarks() like this:
$db = new DB();
$db->executeQuery("SELECT url, title FROM site ORDER BY id DESC");
return $db->processRowSet();