exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number - php

This look a lot simple but for some reasons i can not get it to work... I need all the help i can get
function register_user($email, $password, $gender, $phone_number){
$this->sql = "insert into user
(
email_addr, phone_number, password,
gender, activation_code, isMobileVerified,
last_login_date, unix_sign_up_time, sign_up_date
) VALUES
(
:email, :phone_number, :password,
:gender, :activation_code, :isMoobileVerified,
:last_login, :time_unix, NOW()
)";
$this->prepare($this->sql);
$this->bind(':email', $email);
$this->bind(':phone_number', $phone_number);
$this->bind(':password', $password);
$this->bind(':gender', $gender);
$this->bind(':activation_code', sha1($password));
$this->bind(':isMobileVerified', 0);
$this->bind(':last_login', time());
$this->bind(':time_unix', time());
$this->execute();
return $this->lastInsertedId();
}
when i run this function like this
try{
echo "<br>" . $i->register_user('myMail#register.com', 'password', 'male', '2348020000007');
}catch (PDOException $e) {
//todo: logging function or mail to dev goes here
echo $e ."<br>". $e->getMessage();
}
i get this error
exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in C:\wamp\www\ecommerce\system\model\class.ecommerce.php:215 Stack trace: #0 C:\wamp\www\ecommerce\system\model\class.ecommerce.php(215): PDOStatement->bindValue(':isMobileVerifi...', true, 5) #1 C:\wamp\www\ecommerce\system\model\class.ecommerce.php(281): ukorJidechi\db_handler->bind(':isMobileVerifi...', true) #2 C:\wamp\www\ecommerce\namespace_test.php(51): ukorJidechi\ecommerce_user->register_user('myMail#register...', 'password', 'male', '2348020000007') #3 {main}
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
here is my custom bind method
function bind($placeholder, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = \PDO::PARAM_INT;
break;
case is_bool($value):
$type = \PDO::PARAM_BOOL;
break;
case is_null($value):
$type = \PDO::PARAM_NULL;
break;
default:
$type = \PDO::PARAM_STR;
}
}
$this->stmt->bindValue($placeholder, $value, $type);
}
Can someone show me what I am doing wrong? Please.

See this statement here,
$this->bind(':unix_sign_up_time', time());
And compare the above statement with $this->sql
$this->sql = "insert into user
(
...
:last_login, :time_unix, NOW()
^^^^^^^^^
)";
So your bind() statement should be,
$this->bind(':time_unix', time());
Edited:
See this line here in $this->sql,
$this->sql = "insert into user
(
...
:gender, :activation_code, :isMoobileVerified,
^^^^^^^^^^^^^^^^^^
...
)";
It should be :isMobileVerified

Related

Query doesn't insert into table

I using a register form and i would like to see if i have missing columns/tables. I'm using var_dump $stmt; and echo $e->getMessage();
Every time I get successfully message but the code doesn't insert anything into the database .
If I'm using echo $e->getMessage(); I get this:
object(PDOStatement)#11 (1) { ["queryString"]=> string(153) "INSERT INTO bg_user(user_id, passwd, email, account_status) VALUES(:login, :password, :email, :status)" }
Notice: Undefined variable: e in include\classes\user.php on line 89
Fatal error: Uncaught Error: Call to a member function getMessage() on null in include\classes\user.php:89 Stack trace:
#0 include\functions\register.php(57): USER->register('test123', 'a3876fafbc8b9b9...', 'test#tex.com', NULL)
#1 pages\register.php(11): include('D:\Working Stat...')
#2 index.php(199): include('D:\Working Stat...')
#3 {main} thrown in include\classes\user.php on line 89
This is my code:
public function register($username,$password,$email,$ref)
{
global $safebox_size;
try
{
$password = md5($password);
$social_id = rand(1000000, 9999999);
$status = "OK";
$stmt = $this->account->prepare("INSERT INTO bg_user(user_id, passwd, email, account_status)
VALUES(:login, :password, :email, :status)");
$stmt->bindparam(":login", $username);
$stmt->bindparam(":password", $password);
$stmt->bindparam(":email", $email);
$stmt->bindparam(":status", $status);
$stmt->execute();
$lastId = $this->account->lastInsertId();
$safebox_password = "000000";
$stmt = $this->player->prepare("INSERT INTO safebox(account_id, size, password)
VALUES(:account_id, :size, :password)");
$stmt->bindparam(":account_id", $lastId);
$stmt->bindparam(":size", $safebox_size);
$stmt->bindparam(":password", $safebox_password);
$stmt->execute();
if($ref && count(getAccountInfo($ref)))
addReferral($lastId, $ref);
return $stmt;
}
catch(PDOException $e)
{
//echo $e->getMessage();
print 'ERROR';
}
}
My question is: what command do I have to use for var_dump, echo, print etc. to report errors (missing columns or tables)?

Problems entering information in MySQL database

I'm trying to introduce some data info in the DB on production mode but is not working I'm using PDO for the connection to the DB, in my localhost works correctly but in the GoDaddy server isn't.
I'm using MVC, when I submit I send the data by POST and in the controller is like this
when i make a submit i execute this
$Registro = new ControladorUsuarios();
$Registro -> ctrRegistroUsuario();
static public function ctrRegistroUsuario(){
if (isset($_POST["regUsuario"])) {
if (preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ.]+$/', $_POST["regUsuario"]) &&
preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $_POST["regEmail"]) &&
preg_match('/^[a-z0-9][a-z0-9.]+$/', $_POST["regPassword"])) {
$encriptar = crypt($_POST["regPassword"], '//hash');
$encriptarEmail = md5($_POST["regEmail"]);
$datos = array(
"usuario" => strtolower($_POST["regUsuario"]),
"email" => strtolower($_POST["regEmail"]),
"password" => $encriptar,
"nombre" => strtolower($_POST["regNombre"]),
"apellidos" => strtolower($_POST["regApellido"]),
"telefono" => $_POST["regTelefono"],
"verificacion" => $encriptarEmail
);
$tabla = "usuario";
$respuesta = ModeloUsuarios::mdlRegistroUsuario($tabla, $datos);
if ($respuesta == "ok") {
/*===================================================================
= HERE I SEND A CONFIRMATION MAIL ACCOUNT =
===================================================================*/
$envio = $mail->Send();
if (!$envio) {
echo'error';
} else {
echo 'success';
}
}else{
echo 'error2';
}
}
}
}
when i make a submit the error goes to error2 and in my model i have this
public static function mdlRegistroUsuario($tabla, $datos){
$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (usuario, email, password, nombre, apellidos, telefono, verificacion) VALUES (:usuario, :email, :password, :nombre, :apellidos, :telefono, :verificacion)");
$stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR);
$stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR);
$stmt->bindParam(":password", $datos["password"], PDO::PARAM_STR);
$stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR);
$stmt->bindParam(":apellidos", $datos["apellidos"], PDO::PARAM_STR);
$stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR);
$stmt->bindParam(":verificacion", $datos["verificacion"], PDO::PARAM_STR);
if ($stmt->execute()) {
return "ok";
} else {
return errorinfo();
}
$stmt->close();
$stmt = null;
}
In my error_log appears this errors
#0 route/Controladores/usuarios.controlador.php(33): ModeloUsuarios::mdlRegistroUsuario('usuario', Array)
#1 route/registro.php(42): ControladorUsuarios::ctrRegistroUsuario()
#5 {main}
thrown in route/Modelos/usuarios.modelo.php on line 31
I really don't know what the problem is hope someone can help me

PDO not working function

register.php
<?php
include_once "pdo.php";
if(isset($_POST["submit"])){
$user_pw = hash("sha256", $_POST['password']);
$params = [
'pcode' => $pcode,
'password' => $user_pw,
'name' => $_POST['name'],
'phone' => $_POST['number'],
'grade' => $_POST['grade']
];
sql($db, "INSERT INTO member (pcode, password, name, phone, grade) VALUES (:pcode, :password, :name, :phone, :grade)", array($params));
}
?>
pdo.php
try {
$db = new PDO("mysql:host=".HOST.";dbname=".NAME.";charset=utf8", "".USER."", "".PASS."");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// PDO fetch docs: http://php.net/manual/en/pdostatement.fetch.php
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo $e->getMessage();
}
// Simple function to handle PDO prepared statements
function sql($db, $q, $params, $return) {
// Prepare statement
$stmt = $db->prepare($q);
// Execute statement
$stmt->execute($params);
// Decide whether to return the rows themselves, or just count the rows
if ($return == "rows") {
return $stmt->fetchAll();
}
elseif ($return == "count") {
return $stmt->rowCount();
}
error
Warning: Missing argument 4 for sql(), called in /home/vvvvvv/html/summit/new.php on line 55 and defined in /home/vvvvvv/html/summit/pdo.php on line 19
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /home/vvvvvv/html/summit/pdo.php:24 Stack trace: #0 /home/vvvvvv/html/summit/pdo.php(24): PDOStatement->execute(Array) #1 /home/vvvvvv/html/summit/new.php(55): sql(Object(PDO), 'INSERT INTO mem...', Array) #2 {main} thrown in /home/vvvvvv/html/summit/pdo.php on line 24
what's problem?
Your parameters are already an array when you create the data, so when you pass them as array($params), it nests the data. So just remove that in your call...
sql($db, "INSERT INTO member (pcode, password, name, phone, grade)
VALUES (:pcode, :password, :name, :phone, :grade)",
$params, "rows" );
Not sure what you want the last parameter to be, but I would recommend changing it to something else. Having a literal like "rows" or "count" can be prone to errors. Change it to a boolean - something like true means return the rows, false means a count.

PDO exception trying to insert data into a blob

I am trying to insert a very large JSON object into a blob and I am getting an exception error indicating invalid parameter number 'not defined'.
code:
<?php
session_start();
require_once('sconfig.php');
require_once('mail/config.php');
try{
$token = $_POST['stripeToken'];
$customer = \Stripe\Customer::create(array(
'email' => $_SESSION['SESS_EMAIL'],
'card' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $_SESSION['PLAN'],
'currency' => 'usd'
));
} catch (Exception $e) {
echo "<br>";
echo "Handle your exception fool!";
}
//var_dump($customer);
echo "<br>";
//var_dump(json_decode($customer));
echo "<br>";
//echo $_SESSION['PLAN'];
$pdo = new PDO(
'mysql:host=' . DB_HOST . ';dbname=' . DB_DATABASE,
DB_USER,
DB_PASSWORD
);
//here we insert plan into the database following purchase
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$session_var = $_SESSION['SESS_MEMBER_ID'];
//ATTENTION!!! All of these variable need to be changed when price gets changed
if($_SESSION['PLAN'] === '3500'){
$plan_var = 1;
echo $plan_var;
$sql = 'UPDATE accounting SET active = 1, plan = :plan_var WHERE id = :session_var';
$sql2 = 'INSERT INTO transactions (customer_object, charge_object) VALUES(:customer, :charge)';
}
else if($_SESSION['PLAN'] === '2500'){
$plan_var = 2;
echo $plan_var;
$sql = 'UPDATE accounting SET active = 1, plan = :plan_var WHERE id = :session_var';
$sql2 = 'INSERT INTO transactions (customer_object, charge_object) VALUES(:customer, :charge)';
}
else if($_SESSION['PLAN'] === 'NULL'){
echo "Call a Dr. Something bad happened, or the programmer needs to be fired";
header("location: ../index.php?p=failed");
}
else {
echo "This looks like a paid invoice. Thank you!";
$plan_var = 9;
echo '<br>';
echo $plan_var;
echo '<br>';
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
$sql = 'UPDATE accounting SET plan = :plan_var WHERE id = :session_var';
$sql2 = 'INSERT INTO transactions (invoice_num) VALUES(:invoice_num)';
//header("location: ../index.php?p=success");
}
$statement = $pdo->prepare($sql);
$statement2 = $pdo->prepare($sql2);
$statement->bindParam(':plan_var', $plan_var, PDO::PARAM_STR, 1);
$statement->bindParam(':session_var', $session_var, PDO::PARAM_STR, 1);
$statement2->bindParam(':customer', $customer, PDO::PARAM_LOB);
$statement2->bindParam(':charge', $charge, PDO::PARAM_LOB);
$statement2->bindParam(':invoice_num', $_SESSION['INVOICE_NUM'], PDO::PARAM_STR, 255);
$user = $statement->execute();
$user = $statement2->execute();
var_dump($statement);
//header("location: ../index.php?p=success");
//echo $token;
?>
The ERROR I am receiving is as follows:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in /usr/home/nyctelecomm/www/pages/scharge.php:79 Stack trace: #0 /usr/home/nyctelecomm/www/pages/scharge.php(79): PDOStatement->bindParam(':customer', Object(Stripe\Customer), 3) #1 {main} thrown in /usr/home/nyctelecomm/www/pages/scharge.php on line 79
How do I get blob data into a mysql database using pdo?
Based on your stack trace
Fatal error: Uncaught exception
'PDOException' with message 'SQLSTATE[HY093]:
Invalid parameter number: parameter was not defined' in
/usr/home/nyctelecomm/www/pages/scharge.php:79 Stack trace:
#0 /usr/home/nyctelecomm/www/pages/scharge.php(79):
PDOStatement->bindParam(':customer', Object(Stripe\Customer), 3)
#1 {main} thrown in /usr/home/nyctelecomm/www/pages/scharge.php on line 79
It looks like PHP is stumbling over the following line (#79)
$statement2->bindParam(':customer', $customer, PDO::PARAM_LOB);
My guess if you're trying to bind the parameter :customer into a SQL statment that doesn't have the parameter :customer defined. Looking at all the possible values of $sql2
$sql2 = 'INSERT INTO transactions
(customer_object, charge_object) VALUES(:customer, :charge)';
$sql2 = 'INSERT INTO transactions
(customer_object, charge_object) VALUES(:customer, :charge)';
$sql2 = 'INSERT INTO transactions (invoice_num) VALUES(:invoice_num)';
It seems like you're not always binding a :customer parameter.
I'd refactor your code to ensure you're not binding parameters that don't exist in your SQL.

What's wrong with this PHP PDO statement for SQL insert?

I've already got username, password and other variables stored, but I keep getting an error "Invalid parameter number: number of bound variables does not match number of tokens" in this line:
$database->query(
'INSERT INTO users_inactive(verCode, username, password, email, date, type)
VALUES (:vercode, :username, :password, :email, :date, :type)',
array(
':vercode' => $verCode,
':username' => $username,
':password' => $password,
':email' => $email,
':date' => $date,
':type'=>'customer')
);
Is there anything wrong with it? I've made sure each of these columns is available in my user_inactive table.
This is the $database wrapper function:
public function query($query, $bind = null, $fetch = 'FETCH_ASSOC') {
/* Prepare the query statement */
$this->statement = $this->pdo->prepare($query);
/* Bind each value supplied from $bind */
if($bind != null) {
foreach($bind as $select => $value) {
/* For each type of value give the appropriate param */
if(is_int($value)) {
$param = PDO::PARAM_INT;
} elseif(is_bool($value)) {
$param = PDO::PARAM_BOOL;
} elseif(is_null($value)) {
$param = PDO::PARAM_NULL;
} elseif(is_string($value)) {
$param = PDO::PARAM_STR;
} else {
$param = FALSE;
}
/* Bid value */
if($param) {
$this->statement->bindValue($select, $value, $param);
}
}
}
/* Execute Query & check for any errors */
if(!$this->statement->execute()){
$result = array(
1 => 'false',
2 => '<b>[DATABASE] Error - Query:</b> There was an error in sql syntax',
);
return $result;
}
/* Return all content */
if($fetch == 'FETCH_ASSOC') {
$result = $this->statement->fetch(PDO::FETCH_ASSOC);
} elseif($fetch == 'FETCH_BOTH') {
$result = $this->statement->fetch(PDO::FETCH_BOTH);
} elseif($fetch == 'FETCH_LAZY') {
$result = $this->statement->fetch(PDO::FETCH_LAZY);
} elseif($fetch == 'FETCH_OBJ') {
$result = $this->statement->fetch(PDO::FETCH_OBJ);
} elseif($fetch == 'fetchAll') {
$result = $this->statement->fetchAll();
}
return $result;
}
}
Taken from Tutis Login.
Just some clues,You are probably missing some colons. Check out here
PHP Mysql PDO number of bound variables does not match number of tokens
Or probably there is some case sensitive going on on your colons
The error seems to be in your wrapper function. PDO::PARAM_NULL == 0, so this value does not pass through
if($param) {
...
}
So you do not call bindValue() for NULL values. Instead, use:
if ($param !== FALSE) {
...
}
EDIT - reading again your code, this would be better code of the foreach() block, producing less cryptic error messages in the future :)
foreach($bind as $select => $value) {
/* For each type of value give the appropriate param */
if(is_int($value)) {
$param = PDO::PARAM_INT;
} elseif(is_bool($value)) {
$param = PDO::PARAM_BOOL;
} elseif(is_null($value)) {
$param = PDO::PARAM_NULL;
} elseif(is_string($value)) {
$param = PDO::PARAM_STR;
} else {
// Report error about invalid type and return from the function
...
}
// we should bind every value from $bind array, unconditionally!
$this->statement->bindValue($select, $value, $param);
}
Give this a shot:
<?php
$sql = $database->prepare(
'INSERT INTO users_inactive(verCode, username, password, email, date, type)
VALUES (:vercode, :username, :password, :email, :date, :type)');
$sql->execute(array(
'vercode' => $verCode,
'username' => $username,
'password' => $password,
'email' => $email,
'date' => $date,
'type'=>'customer')
);

Categories