PDO exception trying to insert data into a blob - php

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.

Related

Returning id from access database

this is my code that is inserting data into an access database using php.
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");
$connStr = "PROVIDER=Microsoft.Ace.OLEDB.12.0;Data Source=" . realpath(‘my access path’) . ";";
// Open the connection to the database
$conn->open($connStr);
$query = “my insert query here which inserts into theaccess database fine”
$query2 = "select ##IDENTITY"
try{
$rs = $conn->execute($query);
$idReturned = $conn->lastInsertId();
echo json_encode($idReturned);
} catch(com_exception $e){
echo($e);
}
I’m trying to get the returned id but all I am getting is the below error :
exception 'com_exception' with message 'Source: ADODB.Connection
Description: Arguments are of the wrong type, are out of acceptable
range, or are in conflict with one another.' in
C:\inetpub\wwwroot\agency\createnewvaluation.php:132 Stack trace: #0
C:\inetpub\wwwroot\agency\createnewvaluation.php(132):
com->lastInsertId() #1 {main}
I went though the results manually and got the code myself
if($dbh->getAttribute(PDO::ATTR_DRIVER_NAME) == 'pgsql') {
} elseif($dbh->getAttribute(PDO::ATTR_DRIVER_NAME) == 'odbc') {
$sb = $dbh->prepare('SELECT ##IDENTITY AS lastID');
$sb->execute();
$row = $sb->fetch(PDO::FETCH_ASSOC);
$arr = array("ref" => $row["lastID"]);
echo json_encode($arr);
} else {
$arr = array("ref" => "error");
echo json_encode($arr);
}

PHP and SQLSTate error

I have this PHP code:
<?php
require_once('../include/inner_global.php');
$id=$_REQUEST['id'];
$hostdb="localhost";
$namedb="architect";
$userdb="root";
$passdb="root";
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
if(isset($_POST['submitDate'])){
if(!isset($_POST['Date'])){
echo "No date selected";
}else{
echo $d = date('Y-m-d',strtotime($_POST['Date']));
}
//foreach($result as $row){
$sql1= "SELECT SUM(total_pay) AS total FROM workers WHERE date_of_pay = :d AND projects_id = :id";
$stmt = $conn->prepare($sql1);
$stmt->bindValue(":d", $d);
$stmt->bindValue(":projid", $id);
$count = $stmt->execute();
$result = $stmt->fetchAll();
echo var_dump($result);
}
?>
And I am getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in C:\wamp\www\architect\pages\projDReport.php on line 25
does someone know what is going wrong? the global.php file, is for session detection, else it will take us to login page.
Change $stmt->bindValue(":projid", $id); to $stmt->bindValue(":id", $id);.
The values you are binding in prepared statements should have same names, as it defined in the statement. In that case it should be named :id and not :projid.

Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found

I tried to run the following code but it returned this erros:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column ''1'' in 'field list'' in /home/cardg/cards/jogar.php:59 Stack trace: #0 /home/cardg/cards/jogar.php(59): PDOStatement->execute() #1 {main} thrown in /home/cardg/cards/jogar.php on line 59
Why this is happening?
<?php
include('config.php');
$usuarion = $_SESSION['login'];
$senhan = $_SESSION['senha'];
// $attrs is optional, this demonstrates using persistent connections,
// the equivalent of mysql_pconnect
$attrs = array(PDO::ATTR_PERSISTENT => true);
// connect to PDO
$pdo = new PDO('mysql:host='.$dbservidor.';dbname='.$dbnome.'', $dbusuario, $dbsenha);
// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare the statement. the place holders allow PDO to handle substituting
// the values, which also prevents SQL injection
$stmt = $pdo->prepare("SELECT estado,usuario1,usuario2,usunivel,id FROM duelos WHERE estado=:estadox AND usuario1!=:usuario");
// bind the parameters
$stmt->bindValue(":estadox", 0);
$stmt->bindValue(":usuario", $usuarion);
// initialise an array for the results
$duelos = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$products[] = $row;
echo $row['usuario1'];
}
}
$usuario = $pdo->query("SELECT id,apelido,usuario,nivel FROM usuarios WHERE usuario = '".$usuarion."' AND senha ='".$senhan."'");
$usulinha = $usuario->fetch(PDO::FETCH_ASSOC);
$usuarioid = $usulinha['id'];
$usunivel - $usulinha['nivel'];
$sqlduelos = "SELECT COUNT(*) FROM duelos WHERE (estado = 1 AND usuario2 = 0)";
if ($resl = $pdo->query($sqlduelos)) {
/* Check the number of rows that match the SELECT statement */
if ($resl->fetchColumn() > 0) {
$msg = "True msg";
}
else{
$msg = "false msg";
$inid = $pdo->prepare("INSERT INTO `duelos` (`usuario1`, `usunivel`) VALUES (
`:usua`,
`:usuni`)");
$inid->bindParam(':usua', $usuarioid);
$inid->bindParam(':usuni', $usunivel);
$inid->execute();
}
}
// set PDO to null in order to close the connection
$pdo = null;
?>
Remove delimiters (backticks) around the placeholders:
$inid = $pdo->prepare("INSERT INTO `duelos` (`usuario1`, `usunivel`)
VALUES (:usua, :usuni)");
... as these are placeholders, which values (bound to them by bindValue) will be escaped automatically. Otherwise, those values will be treated as a column names, causing the error.
As a sidenote, you have a typo here:
$usunivel - $usulinha['nivel'];
... it should be $usunivel = $usulinha['nivel']; most probably.

PDO Fatal Error update

I'm receiving this error and it's got me scratching my head:
Fatal error: Uncaught exception 'PDOException' with message 'invalid
data source name' in
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/functions/sandbox.php:10
Stack trace: #0
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/functions/sandbox.php(10):
PDO->__construct('SELECT title FR...') #1
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/config/setup.php(30):
get_title(NULL, 'blog') #2
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/index.php(2):
include('/Users/aaronwil...') #3 {main} thrown in
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/functions/sandbox.php
on line 10
Here's the sandbox.php code:
<?php ## Sandbox PHP/PDO Functions
function get_page($dbc, $pg) {
$sql = new PDO("SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");
$stmt = $dbc->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content">'.$page['body'].'</div>';}
function get_title($dbc, $pg)
$sql = new PDO("SELECT title FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");
$stmt = $dbc->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
return $page['title'];}
?>
On Setup.php there is a S_GET function to pull the url to call the function on sandbox.php:
if ($_GET ['page'] == '') {
$pg = 'home';}
else {
$pg = $_GET ['page']; }
new PDO("SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");
That's not how you create a PDO object, its parameters are different, it does not take in a query. Following is the constructor prototype.
public PDO::__construct() ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
Send parameters to it accordingly. Send dsn, username, password.
Example from php.net
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Source
Your are not using properly the PDO Library , and thats what causes errors.
Here is an example of one from many correct ways : (Adapt it to your situation and im sure it will help you )
$variable1 = "somthing";
$variable2 = "somewhat";
try
{
require_once("db-info.php");
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$db = new PDO('mysql:host='.$host.';dbname=' . $dbname, $dbuser, $dbpassword, $pdo_options);
$response = $db->prepare('SELECT column1, column2 FROM table WHERE column1 = :value1 and column2 = :value2');
$response->execute(array('value1' => $variable1,
'value2' => $variable2
));
$data = $response->fetch(); // works for one set of data
// if your are trying to fetch multiple line use a (while $data = $response->fetch())
//and insert your code inside the while loop.
//insert your code here....
//.........................
//.............
//using a return true or false may help you with your function case
$response->closeCursor();
}
catch (Exception $error)
{
die('error while selecting data' . $error->getMessage());
}

Throw an exception with the SQL error message

I am getting an error in this code:
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', '$this->points' )";
}
else if($this->id != 0)
{
$query = "update articles set modified = CURRENT_TIMESTAMP, username = '$this->username', url = '$this->url', title = '$this->title', description = '$this->description', points = '$this->points', ranking = '$this->ranking' where id = '$this->id' ";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
error_log($e);
}
What do I have to add so I get some meaningful SQL error message?
(It seems for some queries its not getting the user name)
Edit: I get this error log:
[18-Mar-2011 05:19:13] exception 'Exception' in /home1/mexautos/public_html/kiubbo/data/model.php:90
Stack trace:
#0 /home1/mexautos/public_html/kiubbo/data/article.php(276): Model::execSQl2('update articles...')
#1 /home1/mexautos/public_html/kiubbo/data/article.php(111): Article->save()
#2 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(21): Article->calculateRanking()
#3 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(27): FrontPage->updateRanking()
#4 /home1/mexautos/public_html/kiubbo/index.php(15): FrontPage->showTopArticles('426')
#5 {main}
Thank you,
Regards,
Carlos
The best way to handle this is to use a custom exception that would be thrown by your Database Handler.
class DatabaseErrorException{
public function __construct( $errorMesssage, $query ){
throw new Exception( $errorMessage . " for query: " . $query );
}
}
and so you can either detect the error in your database library and throw from there, or in your try statement you can have:
if( $db->someError )
throw new DatabaseErrorException( $db->someError, $query );
and your catch statement would turn into
catch( DatabaseErrorException $e ){
error_log( $e->getMessage( ) );
//Or whatever handling you wish to do with it.
}
error_log('Failed to set record in articles table: '.
$e->getMessage().
"\n".$query
);

Categories