Zend Framework using regular mysql select call - zend-db

Is there a way to use a regular mysql select statement with Zend Framework without having to use Zend_Db::factory
Code below is in my Model classes which extends Zend_Db_Table_Abstract
I can currently do this (which works):
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => 'localhost',
'username' => 'dbuser',
'password' => 'dbuserpass',
'dbname' => "somedbname"
));
$select = "SELECT iv.*
FROM image_variations AS iv
LEFT JOIN images AS i ON (i.image_id = iv.image_id)
LEFT JOIN product_images AS pi ON (pi.image_id = iv.image_id)
WHERE pi.pid = '$pid'
&& iv.image_type_id = '$image_type_id' ";
$stmt = $db->query($select);
$rows = $stmt->fetchAll();
return $rows;
I would like to do this:
$select = "SELECT iv.*
FROM image_variations AS iv
LEFT JOIN images AS i ON (i.image_id = iv.image_id)
LEFT JOIN product_images AS pi ON (pi.image_id = iv.image_id)
WHERE pi.pid = '$pid'
&& iv.image_type_id = '$image_type_id' ";
$stmt = $this->query($select);
$rows = $stmt->fetchAll();
return $rows;
So I dont always have to define db variables in each method and have mysql passwords all over the place. Is there a way to use $this instead of having to instantiate a new $db Zend_DB Factory??

Ok figured it out. The solution is not very elegant buts works and is portable.
My setup consists of multiple DBs, so in Bootstrap.php I have:
protected function _initDatabase() {
$resource = $this->getPluginResource('multidb');
$resource->init();
Zend_Registry::set('db', $resource->getDb('db'));
Zend_Registry::set('shopdb', $resource->getDb('shopdb'));
}
In Application.ini
resources.multidb.db.adapter = PDO_MYSQL
resources.multidb.db.host = 127.0.0.1
resources.multidb.db.username = user
resources.multidb.db.password = userpassword
resources.multidb.db.dbname = dbone
resources.multidb.db.isDefaultTableAdapter = true
resources.multidb.db.default = true
resources.multidb.shopdb.adapter = PDO_MYSQL
resources.multidb.shopdb.host = 127.0.0.1
resources.multidb.shopdb.username = user
resources.multidb.shopdb.password = userpassword
resources.multidb.shopdb.dbname = dbtwo
resources.multidb.shopdb.isDefaultTableAdapter = false
in index.php
$config = new Zend_Config_Ini(APPLICATION_PATH . "/configs/application.ini");
Zend_Registry::set('settings', $config);
Then (the not very elegant bit) in Models add an init() method
protected $db;
public function init() {
$settings = Zend_Registry::get('settings');
$adapter = $settings->production->resources->multidb->shopdb->adapter;
$params = array(
'host' => $settings->production->resources->multidb->shopdb->host,
'username' => $settings->production->resources->multidb->shopdb->username,
'password' => $settings->production->resources->multidb->shopdb->password,
'dbname' => $settings->production->resources->multidb->shopdb->dbname,
);
$this->db = Zend_Db::factory("$adapter", $params);
}
And then you can use $this->db in other methods in the Model class, eg:
public function getProductImages($pid, $image_type_id) {
$select = "SELECT iv.*
FROM image_variations AS iv
LEFT JOIN images AS i ON (i.image_id = iv.image_id)
LEFT JOIN product_images AS pi ON (pi.image_id = iv.image_id)
WHERE pi.pid = '$pid'
&& iv.image_type_id = '$image_type_id' ";
$stmt = $this->db->query($select);
$rows = $stmt->fetchAll();
return $rows;
}
It works but it still seems like there should be an easier way...

Related

Big headache with SQL syntax - need help - page doesn't send new row to server

I am currently learning sql but I cannot get some things done like send a new data to the localhost when I am submiting data
$short_title=$_POST['short_title'];
$title=$_POST['title'];
$statement=$connection->prepare(
'INSERT INTO post (title,short_name) VALUES (:title,:short_name)');
$statement->execute(array(':title'=>$title,':short_name'=>$short_title));
Where is the db_connect file please?
And is the ID of the table in Auto-Increment?
Something seems wrong with your last line. Are you using PDO or MYSQLI?
Here is an example of a query and a db_connect file in PHP using PDO method
The db connect :
<?php
$db_username = "root";
$db_password = "";
$db_host = "localhost";
$db_name = "veterinaires";
$db_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
try {
$db = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8", $db_username, $db_password, $db_options);
} catch(PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>
Model for insert in DB
<?php
/* Basic function */
$query = "INSERT INTO users (
ID,
password,
email,
role
) VALUES (
:ID,
:password,
:email,
:role)";
// Security measures
$query_params = array(
':ID' => NULL,
':password' => $password,
':email' => $email,
':role' => 'vet');
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$check = true;
}catch(PDOException $ex){
$errormsg = "Vous possédez déjà un compte!";
$check = false;
}
?>

send payments to faucetbox

I have try to do my self this code to implement the automatic send bitcoin payments to faucet box but is some errors there I need help with.
and it give me this error
The bitcoinrotator.publiadds.org.pt page is not working bitcoinrotator.publiadds.org.pt can not process this request for time. 500
<?php
//custom parameters
$api_key = "my_api_key";
$userAddy = $_SESSION['user'];
require_once("faucetbox.php");
$currency = "BTC"; # or LTC or any other supported by FaucetBOX
$faucetbox = new FaucetBOX($api_key, $currency);
$users = array(
'user_id' => clean($user_id),
'user_name' => clean($user_name),
'user_email' => clean($user_email),
'user_pass' => clean($user_pass),
'user_points' => clean($user_points),
'user_wallet' => clean($user_wallet)
);
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$selfNav = mysqli_query($conn, "SELECT user_wallet, user_points FROM users WHERE user_id=".$_SESSION['user']);
$rowNav = mysqli_num_rows($selfNav);
$rowAssoc = mysqli_fetch_assoc($selfNav);
$balance = $rowAssoc['user_points'];
$wallet = $rowAssoc['user_wallet'];
//auto cashout if bal over 0.00010000
if($balance > 0.00010000){
$amount = $rowAssoc['user_points'];
$currency = "BTC";
$faucetbox = new Faucetbox($api_key, $currency);
$result = $faucetbox->send($wallet, $amount);
if($result["success"] === true){
$_SESSION['cashout'] = $result["html"];
//reset balance to zero
mysqli_query($conn, "UPDATE `users` SET user_points = 0 WHERE user_id = " . $_SESSION['user')];
header('Location: ../home.php');
?>
well there it is its work but it stay with some bug there but now its work
the error is
Array ( [user_wallet] => 111111111111111111111111111111111111 [user_points] => 0.00000010 ) Error en balance
<?php
session_start();//Session start is ALWAYS the first thing to do.
if(!isset($_SESSION['user']))
{
header("Location: index.php"); //Sending headers its the next thing to do. Always.
}
include_once 'dbconnect.php';
//custom parameters
$api_key = "my_api_key";
$userAddy = $_SESSION['user'];
require_once("faucetbox.php");
$currency = "BTC"; # or LTC or any other supported by FaucetBOX
$faucetbox = new FaucetBOX($api_key, $currency);
//$users = array(
// 'user_id' => clean($user_id),
// 'user_name' => clean($user_name),
// 'user_email' => clean($user_email),
// 'user_pass' => clean($user_pass),
// 'user_points' => clean($user_points),
// 'user_wallet' => clean($user_wallet)
//);
//You are mixing mysql and mysqli, you need to choose one. Since you are on a shared hosting, mysqli is probably
//not installed/available, so we will keep using mysql. mysqli is safer!
$selfNav = mysql_query("SELECT user_wallet, user_points FROM users WHERE user_id=".$_SESSION['user']);
$rowNav = mysql_num_rows($selfNav);
$rowAssoc = mysql_fetch_assoc($selfNav);
print_r($rowAssoc);
$balance = $rowAssoc['user_points'];
$wallet = $rowAssoc['user_wallet'];
//auto cashout if bal over 0.00010000
if($balance > 0.00010000){
$amount = $rowAssoc['user_points'];
$currency = "BTC";
$result = $faucetbox->send($wallet,$amount); //$amount);
if($result["success"] === true){
$_SESSION['cashout'] = $result["html"];
//reset balance to zero
mysql_query("UPDATE `users` SET user_points = 0 WHERE user_id = " . $_SESSION['user']);
echo "result sucess and location go";
//header('Location: ../home.php');
}else{
echo "Error on faucet";
var_dump($result);
//What happens if there is an error?
}
}else{
echo "do not have enough credit to cash out";
//what happens if they dont have enough balance?
}
?>

How to use a foreign database in extbase/fluid

I have a simple extbase extension (typo3) with one controller and one model/view. Now i want to "select *" a MSSQL database and output the results in my view. I have not found any reference on how to realize this.
How can i connect to a foreign database from within my extbase/fluid extension and use the data from this database (MSSQL)? How do i execute a query on the "extDB" and how to i print out the result IN my fluid-view.
This is how i integrate the DB (dbal/adodb):
$TYPO3_CONF_VARS['EXTCONF']['dbal']['handlerCfg'] = array(
'extDB' => array(
'type' => 'adodb',
'config' => array(
'driver' => 'mssql',
'username' => 'DB_username',
'password' => 'DB_password',
'host' => 'DB_host',
'database' => 'DB_used',
)
)
);
$TYPO3_CONF_VARS['EXTCONF']['dbal']['table2handlerKeys'] = array (
'VIEW_TABLE1' => 'extDB',
'VIEW_TABLE2' => 'extDB',
);
Any help is appreciated.
You can try extension Database Abstraction Layer (dbal).
Example use global variable $GLOBALS. This is tested on Typo3 4.x, but with little updates(?) maybe working on Typo 6.2 (eg. remove deprecated t3lib_div, and use GeneralUtility...).
class Abstract {
/**
* Access to database
*
*/
private
$msdbHost = 'localhost',
$msdb = 'database-name',
$msdbUsername = 'xxx',
$msdbPassword = 'xxx';
/**
* Connect to MS database
*
*/
public function connectDatabaseMs() {
$GLOBALS['MS_DB'] = t3lib_div::makeInstance('t3lib_DB');
$GLOBALS['MS_DB']->sql_pconnect($this->msdbHost, $this->msdbUsername, $this->msdbPassword);
if($GLOBALS['MS_DB']->link) {
if($GLOBALS['MS_DB']->sql_select_db($this->msdb)) {
return $GLOBALS['MS_DB'];
} else {
t3lib_div::devLog('[tx_rtgms_lib::connectDatabaseUsers] Can not select database "'.$this->msdb.'".', $this->extKey, 3);
}
} else {
t3lib_div::devLog('[tx_rtgms_lib::connectDatabaseUsers] Can not connect to database "'.$this->msdb.'".', $this->extKey, 3);
}
$GLOBALS['MS_DB'] = FALSE;
return FALSE;
}
/**
* Example
*
*/
public function getData() {
$query = 'SELECT ...';
$res = $GLOBALS['HOSTAFF_DB']->sql_query($query);
...
}
}

Trouble passing SQL data to view in codeigniter

I have a form that I am using to allow people to input data and then upload a preset picture. I want to label that picture as the form_id. I am able to run a LAST_INSERT_ID() query and display it after I insert the form in my view but I can't seem to echo that information out anywhere else. I need the query to select_last_id to run after my $update query or the ID number will be off. Could anyone assist in helping me pass just the value of the row to my view? Here is the code from my controller.
function inspection() {
if($this->input->post('submit')) {
$array = array(
'trlr_num' => $this->input->post('trlr_num'),
'seal' => $this->input->post('seal'),
'damaged' => $this->input->post('damaged'),
'truck_num' => $this->input->post('truck_num'),
'driver_name' => $this->input->post('driver_name'),
'car_code' => $this->input->post('car_code'),
'origin' => $this->input->post('origin'),
'lic_plate' => $this->input->post('lic_plate'),
'del_note' => $this->input->post('del_note'),
'live_drop' => $this->input->post('live_drop'),
'temp' => $this->input->post('temp'),
'level' => $this->input->post('level'),
'ship_num' => $this->input->post('ship_num'),
'trlr_stat' => $this->input->post('trlr_stat'),
'comment' => $this->input->post('comment')
);
$update = $this->trailer_model->insert_form($array);
$query = $this->trailer_model->select_last_id();
$result =& $query->result_array();
$this->table->set_heading('ID');
$data['table'] = $this->table->generate_table($result);
unset($query,$result);
}
$level = $this->trailer_model->select_fuel_level();
$result = $level->result_array();
$data['options'] = array();
foreach($result as $key => $row) {
$data['options'][$row['level']] = $row['level'];
}
unset($query,$result,$key,$row);
$data['label_display'] = 'Fuel Level';
$data['field_name'] = 'level';
$status = $this->trailer_model->select_trailer_type();
$result = $status->result_array();
$data['options1'] = array();
foreach($result as $key => $row) {
$data['options1'][$row['trlr_stat']] = $row['trlr_stat'];
}
unset($query,$result,$key,$row);
$data['label_display1'] = 'Trailer Status';
$data['field_name1'] = 'trlr_stat';
$data['page_title'] = 'Trailer Inspection';
$data['main_content'] = 'dlx/inspection/trailer_inspection_view';
return $this->load->view('includes/template',$data);
}
}
Anything you want to display on a view, you must pass to it.
When you're setting $data, you missed adding $query to it.
Controller:
I understand that $query = $this->trailer_model->select_last_id(); is returning just an ID, so:
$data['last_id'] = $query;
But if $query = $this->trailer_model->select_last_id(); does not return just an ID, but an array or something else, you shall include to return the ID in your model method. Actually, it'd be crucial to know what $this->trailer_model->select_last_id(); is returning.
View:
echo $last_id; -> must echo the last ID, if select_last_id() method from your model returns what it has to return.

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'

I can't get the following PDO statement to work
<?php
// Update (Edit) user details in DB
// DB Connection include
include_once('connstring.inc.php');
//include_once('key.inc.php'); // Not necessary for update as UID is already generated
$User_ID = $_POST['user_id'];
$First_Name = ucfirst($_POST['first_name']);
$Last_Name = ucfirst($_POST['last_name']);
$Address = $_POST['address'];
$Phone = $_POST['phone'];
$District = ucfirst($_POST['district']);
$State = ucfirst($_POST['state']);
$Country = ucfirst($_POST['country']);
$Pin_Code = $_POST['pin_code'];
$Email = $_POST['email'];
$User_Name = $_POST['user_name'];
//$UID = $_POST['UID'];
$Admin_Group = $_POST['admin_group'];
$Admin_Status = $_POST['admin_status'];
// Update DB with new values
$sql = "UPDATE admin_user SET first_name = :firstname, last_name = :lastname, address= :address, phone = :phone, district = :district, state = :state, country = :country,pin_code = :pincode, email = :email, user_name = :username, admin_group = :admingroup, admin_status = :adminstatus WHERE user_id = :userid";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':firstname'=>$First_Name, ':lastname'=>$Last_Name, ':address'=>$Address, ':phone'=>$Phone, ':district'=>$District,':state'=>$State,':country'=>$Country,':pincode'=>$Pin_Code,':email' >$Email,':username'=>$User_Name,':admingroup'=>$Admin_Group,':admin_status'=>$Admin_Status, :userid'=>$User_ID));
$conn = null;
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
?>
My MySQL table structure is as follows:
======================================
(DB Name:admin_user)
user_id
first_name
last_name
address
phone
district
state
country
pin_code
email
user_name
password
UID
admin_group
admin_status
I am using the current version of the jQuery jtable plugin. Inserts are working fine in the same table. But on trying to update I get:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in /var/www/test.com/public_html/admin/adminedituser.php:28\nStack trace:\n#0 /var/www/test.com/public_html/admin/adminedituser.php(28): PDOStatement->execute(Array)\n#1 {main}\n thrown in /var/www/test.com/public_html/admin/adminedituser.php on line 28
How can I fix this problem?
<?php
/*
* Update (Edit) user details in DB
* DB Connection include
*/
include_once('connstring.inc.php');
$user_info_arr = [];
foreach($_POST as $key => $val)
{
$user_info_arr[$key] = $val;
}
//update DB with new values
$query = "UPDATE `admin_user` SET
`first_name` = :firstname,
`last_name` = :lastname,
`address` = :address,
`phone` = :phone,
`district` = :district,
`state` = :state,
`country` = :country,
`pin_code` = :pincode,
`email` = :email,
`user_name` = :username,
`admin_group` = :admingroup,
`admin_status` = :adminstatus
WHERE
`user_id` = :userid";
$stmt = $conn->prepare($query);
$stmt->execute(
array(
':firstname' => ucfirst($user_info_arr['first_name']),
':lastname' => ucfirst($user_info_arr['last_name']),
':address' => $user_info_arr['address'],
':phone' => $user_info_arr['phone'],
':district' => ucfirst($user_info_arr['district']),
':state' => ucfirst($user_info_arr['state']),
':country' => ucfirst($user_info_arr['country']),
':pincode' => $user_info_arr['pin_code'],
':email' => $user_info_arr['email'],
':username' => $user_info_arr['user_name'],
':admingroup' => $user_info_arr['admin_group'],
':adminstatus' => $user_info_arr['admin_status'],
':userid' => $user_info_arr['user_id']
)
);
$conn = null;
//Return result to jTable
$jTableResult = [];
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
?>
It also took me to cleanup your code. And really using $_POST and passing to an individual variable is pretty ugly; instead use an array...
Try to check if it works now.