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.
Related
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)?
This question already has answers here:
PDO valid characters for placeholders
(2 answers)
Closed 2 years ago.
Hej.
I´m new to PHP but strugling to learn. i have found out that this is the way to handle database connection. Have debugged the code but have one stubborn thing left. Cant seem to wrap my brain around this errorcode. Any pointer in simple way so even i understand. ;-)
I am surfing this pages: https://www.php.net/manual/en/pdostatement.bindparam.php
Error-message:
Database connection establishedPDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\Test\dbtest.php:28 Stack trace: #0 C:\xampp\htdocs\Test\dbtest.php(28): PDOStatement->execute() #1 {main}
<?php
// Require needed classes
require_once('dbhandler.php');
// Create needed objects
$dbh = new DBHandler();
// Check if database connection established successfully
if ($dbh->getInstance() === null) {
die("No database connection");
}
//$datetime = date("Y-m-d H:i:s");
$epost = 'svante#telia.com';
$namn = 'Svante';
$användarnamn = 'Poffe';
$lösenord = '1596';
try {
$sql = "INSERT INTO users(epost, namn, användarnamn, lösenord) VALUES(:epost, :namn, :användarnamn, :lösenord)";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':epost', $epost, PDO::PARAM_STR);
$stmt->bindParam(':namn', $namn, PDO::PARAM_STR);
$stmt->bindParam(':användarnamn', $användarnamn, PDO::PARAM_STR);
$stmt->bindParam(':lösenord', $lösenord, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
echo $e;
}
?>
/Svante
It might be worth trying a simplified version that omits the special characters from the PHP variable and the assigned placeholders.
<?php
require_once('dbhandler.php');
$dbh = new DBHandler();
$e = 'svante#telia.com';
$n = 'Svante';
$a = 'Poffe';
$l = '1596';
$sql = "INSERT INTO users( `epost`, `namn`, `användarnamn`, `lösenord` ) VALUES( :e, :n, :a, :l )";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':e', $e, PDO::PARAM_STR);
$stmt->bindParam(':n', $n, PDO::PARAM_STR);
$stmt->bindParam(':a', $a, PDO::PARAM_STR);
$stmt->bindParam(':l', $l, PDO::PARAM_STR);
$stmt->execute();
Using PostgreSQL 9.6 and PHP 7.2, I am creating a PDO connection, preparing an INSERT query, binding the parameters, then executing the prepared query. I have ATTR_ERRMODE set to ERRMODE_EXCEPTION, and in fact can cause exceptions to be thrown by the execute if, for example, the prepared query has 4 parameters, but I’ve only bound 3.
But if my prepared query doesn’t include a field with a NOT NULL constraint, then the execute hangs for maybe 20 seconds, then the browser displays “the connection was reset”. The Postgres log says:
ERROR: null value in column "fullname" violates not-null constraint
DETAIL: Failing row contains (345, fredf, fredf#bedrock.net, yabadabadoo, null, Bedrock, none, user).
STATEMENT: INSERT INTO users (username, password, location, description, email, role) VALUES ($1, $2, $3, $4, $5, $6)
LOG: could not receive data from client: An existing connection was forcibly closed by the remote host.
These 4 log entries repeat a total of 10 times.
I understand this situation is really a programming issue -- the query should be consistent with the requirements of the database design. But I’d really like to coax the Postgres PDO driver into telling me what the error was, rather than have to go dig through logs.
Sample code
/*
Sample code to demonstrate failure of prepared query execute()
to throw an exception when the prepared query omits a field
with a NOT NULL constraint.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username varchar(50) NOT NULL,
email varchar(100) NOT NULL,
password varchar(255) NOT NULL,
fullname varchar(100) NOT NULL,
location varchar(100) NOT NULL,
description text NOT NULL,
role varchar(50) NOT NULL DEFAULT ''
);
*/
$host = "localhost";
$user = "postgres";
$pass = "password";
$dbname = "database";
/**
* Initialize the PDO connection.
*/
$dsn = 'pgsql:host=' . $host . ';dbname=' . $dbname;
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try {
$handler = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
/**
* Demonstrate failure of execute() to return an error or throw an exception
* Error condition omits the fullname field from the INSERT query, which has a
* "not null" constraint.
*/
$demonstrateProblem = 1;
$badQuery = "INSERT INTO users (username, password, location, description, email, role) " .
"VALUES (:username, :password, :location, :description, :email, :role)";
$goodQuery = "INSERT INTO users (username, password, fullname, location, description, email, role) " .
"VALUES (:username, :password, :fullname, :location, :description, :email, :role)";
if ($demonstrateProblem == 1) {
$query = $badQuery;
} else {
$query = $goodQuery;
}
$stmt = $handler->prepare($query);
if (!$stmt) {
echo "Error in prepare, errorInfo():<br>";
print_r($handler->errorInfo());
}
/**
* Bind the variables
*/
$username = "fredf";
$password = "yabadabadoo";
$fullname = "Fred Flintstone";
$location = "Bedrock";
$description = "none";
$email = "fredf#bedrock.net";
$role = "user";
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
if ($demonstrateProblem == 0) {
$stmt->bindParam(':fullname', $fullname);
} else {
// nothing to do, :fullname is not in the prepared query!
}
$stmt->bindParam(':location', $location);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':role', $role);
/**
* Execute a prepared statement.
*/
echo "Executing prepared query...<br>";
try {
$res = $stmt->execute(); // <-- this statement hangs when the query prepare is bad.
if ($res) {
echo "execute returns true<br> ";
} else {
echo "execute returns false<br> ";
}
} catch (PDOException $e) {
echo "execute error " . $e->getMessage(); // <-- this never appears
}
PostgreSQL log (sequence repeats 10 times)
ERROR: null value in column "fullname" violates not-null constraint
DETAIL: Failing row contains (345, fredf, fredf#bedrock.net, yabadabadoo, null, Bedrock, none, user).
STATEMENT: INSERT INTO users (username, password, location, description, email, role) VALUES ($1, $2, $3, $4, $5, $6)
LOG: could not receive data from client: An existing connection was forcibly closed by the remote host.
Well, you're trying to add data with NULL value for field with NOT NULL constraint on it. You either need to define default value in the Postgresql for "fullname" column, or make it NULL-able.
I think, You need to put prepare statement & bind Parameter code into try block.
Hope it will solve the issue.
Please find code which i used.
$host = "";
$user = "";
$pass = "";
$dbname = "";
/**
* Initialize the PDO connection.
*/
$dsn = 'pgsql:host=' . $host . ';dbname=' . $dbname;
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try {
$handler = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
try{
$query = "insert into ******** values(null, 2709651, NOW(), 'test')";
$stmt = $handler->prepare($query);
$res = $stmt->execute();
if ($res) {
echo "execute returns true<br> ";
} else {
echo "execute returns false<br> ";
}
}catch(PDOException $e){
echo $e->getMessage();
}
You can try with this code. As i am getting below error while inserting null into not-null column.
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "*******" violates not-null constraint
DETAIL: Failing row contains (null, 2709651, 2018-09-13 12:07:03.356125, test).
And this error is from exception handeling.
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
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.