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

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.

Related

Prestashop 1.7 , sending email in proaccount module

We are using proaccount , this module allow users to register as professionnal. This module send and email to staff when an you customer is register. I tried to edit the code but nothing happen , send mail method is not the same in prestashop doc
{
$context = Context::getContext();
$id_lang = (int)$context->language->id;
$iso = Language::getIsoById($id_lang);
$id_shop = (int)$context->shop->id;
$address_text = '';
if ((int)Configuration::get('PROACCOUNT_REGISTER_WITH_ADDRESS')
&& (int)Configuration::get('PROACCOUNT_REGISTER_ADDRESS_PRO')) {
$addresses = $customer->getAddresses($id_lang);
$address = new Address($addresses[0]['id_address']);
$address_text = AddressFormat::generateAddress($address);
}
if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/pro_account.txt')
&& file_exists(dirname(__FILE__).'/mails/'.$iso.'/pro_account.html')) {
$file_attachment = !empty($this->file_attachment['name']) ?
$this->file_attachment : null;
Mail::Send(
$id_lang,
'pro_account',
$this->l('Professional account register'),
array(
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{company}' => $customer->company,
'{siret}' => $customer->siret,
'{address}' => $address_text,
),
Configuration::get('PS_SHOP_EMAIL'),
null,
(string)Configuration::get('PS_SHOP_EMAIL'),
(string)Configuration::get('PS_SHOP_NAME'),
$file_attachment,
null,
dirname(__FILE__).'/mails/',
null,
(int)$id_shop
);
}
}```
Any help please ?

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?
}
?>

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found YII

Relations of review below:
return array(
'product' => array(self::BELONGS_TO, 'Product', 'product_id'),
'profile' => array(self::BELONGS_TO, 'Profile', 'profile_id'),
'rating' => array(self::BELONGS_TO, 'Rating', 'rating_id'),
'reviewcomments' => array(self::HAS_MANY, 'Reviewcomment', 'review_id'),
'reviewhelpfuls' => array(self::HAS_MANY, 'Reviewhelpful', 'review_id'),
'commentCounts' => array(self::STAT, 'Reviewcomment', 'review_id'),
);
Controller code below:
$criteria = new CDbCriteria();
$criteria->addCondition("t.seoUrl = :seoUrl");
$criteria->addCondition("t.published = 1");
$criteria->params = array("seoUrl"=>$seoUrl);
$data['product'] = Product::model()->find($criteria);
if($data['product']){
$data['product']->hits = $data['product']->hits+1;
$data['product']->save();
} else{
throw new CHttpException(404, "Invalid Request for product");
}
$product_id = $data['product']->id;
$criteria = new CDbCriteria();
$criteria->addCondition("t.product_id = '$product_id'");
if(isset($_GET['rating']))
{
$rating_id = $_GET['rating'];
$criteria->addCondition("t.rating_id = '$rating_id'");
}
$criteria->addCondition('t.status = "approved"');
if(isset($_GET['sort']))
{
$sorting = $_GET['sort'];
if($sorting=='newest')
$criteria->order = "t.postDate DESC";
elseif($sorting=='oldest')
$criteria->order = "t.postDate ASC";
elseif($sorting=='rating_high')
$criteria->order = "t.rating_id DESC";
elseif($sorting=='rating_low')
$criteria->order = "t.rating_id ASC";
}
$data['reviews'] = new CActiveDataProvider('Review', array(
'criteria'=>$criteria,
'pagination'=>array('pagesize'=>4)
));
Now when I am running this code, I am getting CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 't.rating_id' in 'where clause'
Thanks for your help
Intstead of using 't' as alias for your tables, start using getTableAlias(false, false)
In your case it would be:
$criteria->addCondition(Review::model()->getTableAlias(false, false).".rating_id = '$rating_id'");
More importantly this code screams SQL injection
$rating_id = $_GET['rating'];
$criteria->addCondition("t.rating_id = '$rating_id'");
Never use user input without processing it. Yii allows you to bind values which would be escaped for you - no threat of SQL injection(atleast as far as i know). You should be creating your criteria like so:
$criteria->addCondition(Review::model()->getTableAlias(false, false).".rating_id = :rating_id");
$criteria->params = array(
':rating_id' => $rating_id,
);

Zend Framework using regular mysql select call

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...