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
);
Related
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);
}
I'm making a simple website for a class, and I am trying to save information to my database. The error is not very specific and I do not know which part of my code I need to fix.
Error message:
check the manual that corresponds to your MariaDB server version for
the right syntax to use near ')' at line 2
My PHP code:
<?php
include 'mysqli.php' ;
$result = $con->query("select * from setList s
left join songTable t on s.SetList_ID = t.Song_ID
left join bands b on s.SetList_ID = b.Band_ID");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$setList = $_POST['setlist'];
$venue = $_POST['venue'];
$date = $_POST['dateOfShow'];
$band= $_POST['band'];
$set = $result->fetch_object();
//error handling and form
try {
if (empty($setList) || empty($venue) || empty($date) || empty($band)) {
throw new Exception(
"All Fields Required");
}
if (isset($set)) {
$id = $set->SetList_ID;
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band')";
}
else{
$q = "insert setList (SetList_Name, Venue, Show_Date, Band_Name)
values ('$setList', '$venue', $date, '$band')";
}
$result = $con->query($q);
if (!$result) {
throw new Exception($con->error);
}
header('Location:my_set-lists.php');
} catch(Exception $e) {
echo '<p class ="error">Error: ' .
$e->getMessage() . '</p>';
}
}
?>
The error message tells you exactly where the problem is; you have an extra ). Replace
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band')";
// extra ) is here ---------------------------------------------^
With
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band'";
Note: your next query (starting insert setList) is also going to fail; it should be INSERT INTO setList.... A decent IDE (like PHPStorm) would catch these errors for you.
Also, you are wide open to SQL injection. You really need to be using prepared statements.
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.
I am getting the following error:
[07-Mar-2011 04:52:31] exception 'Exception' in /home1/mexautos/public_html/kiubbo/data/model.php:89
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('')
#5 {main}
This is the line: $lastid = parent::execSql2($query);
Here is the code, if someone can help me to find where the error is:
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
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);
}
}
You have to enclose the variables in {}tags; like so
$query .= " values ('{$this->getModified()}', '{$this->username}', '{$this->url}', '{$this->title}', '{$this->description}', '{$this->points}' )";
The curly brackets let PHP know not to treat the text as a literal. Please note that this will only work in a double-quoted string. (editted the code; I forgot the single quotes around every value)
It might be helpful to echo the string, so that you can check what's going to be executed.
$query .= " values ('".$this->getModified()."', '".$this->username."', '".$this->url."', '".$this->title."', '".$this->description."', '".$this->points."' )";
Looking on my error log I get the following error a lot:
[01-Mar-2011 04:31:27] exception 'Exception' with message 'Query failed' in /home1/mexautos/public_html/kiubbo/data/model.php:89
Stack trace:
#0 /home1/mexautos/public_html/kiubbo/data/article.php(275): 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('')
#5 {main}
If I go to the model.php file I see this:
static function execSQl2($query)
{
/*
Execute a SQL query on the database
passing the tablename and the sql query.
Returns the LAST_INSERT_ID
*/
$db = null;
$lastid = null;
//echo "query is $query";
try
{
$db = Model::getConnection();
$results = $db->query($query);
if(!$results) {
throw new Exception('Query failed', EX_QUERY_FAILED );
}
$lastid = $db->insert_id;
}
catch(Exception $e)
{
/* errors are handled higher in the
object hierarchy
*/
throw $e;
}
Does Anybody see an error, or i should look somewhere else?
Thank you and Regards,
Carlos
Edit:
This is the query: $lastid = parent::execSql2($query);
And this is the context:
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
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 = NOW()".", 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);
}
}
Regards,
Carlos
As heximal said, it's probably an error in your SQL query. Copy and paste the full SQL being queried into PhpMyAdmin or a similar tool and see what errors (if any) come up. Often, the problem is simply a mistyped table or a missing value.
Of course you can also post the query here if you want SO help with it! :D
The error is propably in sql-query. Append to log query text and analyze it.