PDO Insert SQL not executing with no errors - php

I am running this code:
$stmt = $pdo_conn->prepare("INSERT into ticket_updates (ticketnumber, notes, datetime, contact_name, contact_email, customer, internal_message, type) values (:ticketnumber, :notes, :datetime, :contact_name, :contact_email, :customer, :internal_message, :type) ");
$stmt->execute(array(':ticketnumber' => $ticketnumber,
':notes' => $TicketSummary,
':datetime' => date("Y-m-d H:i:s"),
':contact_name' => $Ticket_ContactName,
':contact_email' => $Ticket_ContactEmail,
':customer' => 'Y',
':internal_message' => 'N',
':type' => 'update'));
all the table columns exist and are correct but its not getting past this point
i tried a var_dump($stmt); but get nothing

Use the following to verify the connection is established correctly
try
{
$dbh = new PDO("mysql:host=xxxxxxxxxxxx;dbname=streaming", "xxxx", "xxxx");
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
You can also output errors when you execute like so
$sth->execute() or die(print_r($sth->errorInfo(), true));
Finally you may also need to enable errors on the page, so place this in the header of your page or at the very top if it is a single page:
error_reporting(-1);
The minus 1 means that it will print all errors.
Until you have discovered the error it is very hard to diagnose the issue further, but the issue likely falls down to either the connection to the database or how you have formed the parameter array.

Add error reporting to your pdo:
$pdo_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
before executing the insert command.
Then on the insert command, output your errors
$stmt->execute(array(':ticketnumber' => $ticketnumber,
':notes' => $TicketSummary,
':datetime' => date("Y-m-d H:i:s"),
':contact_name' => $Ticket_ContactName,
':contact_email' => $Ticket_ContactEmail,
':customer' => 'Y',
':internal_message' => 'N',
':type' => 'update')) or die("ERROR: " . implode(":", $pdo_conn->errorInfo()))
This should give you an indication of what is wrong and why things are not executing as expected.

Related

how to work with laravel transaction rollback

I am trying to execute some queries which are dependant on each other, so what I want is if any error occurs then rollback all the queries inside transaction. what I've tried so far is
DB::transaction(function () use($user,$token,$request) {
$billing = User_billings::create([
'users_id' => $user->id,
'agent_id' => null,
'purpose' => 'Some Purpose',
'agent_token_id'=>$token->id,
'amount' => $request->amount,
'payment_method' => 'Agent Token',
'status' => 1
]);
if($billing){
$user_jorunal = User_journal::create([
'bill2_id' => $billing->id, //Intentionally made this error to test transaction, this should be 'bill_id'
'u_id' => $user->id,
'purpose' => 'Topup via Agent Token',
'debit' => $billing->amount,
'invoice_number' => time()
]);
if($user_jorunal){
if($this->agentTokenBalance($request->token_id) == 0){
$token->status=1;
$token->update();
}
return response()->json(['status'=>true,'message'=>'TopUp was Successful!']);
}
}
});
so when I execute this query It generates an error as SQLSTATE[HY000]: General error: 1364 Field 'bill_id' doesn't have a default value, but it also creates a row on user_billings table.
Can you please specify where I am wrong?
all of the above code is running fine, be sure that there is no logical error in query except the intentional one .
I am using laravel 5.7 in this project
PHP version is 7.2.19
following laravel documentation
Manually Using Transactions
use DB::beginTransaction(); to start transaction.
use DB::rollBack(); after each error.
use DB::commit(); when transaction confirmed. ;
laravel reference
Create a $status variable that will make sure that everything has been creeted in db. If any error occur, all db action will be rolled back.
Below, i have adapted your code with that logic.
$status = true;
try
{
DB::beginTransaction();
$billing = User_billings::create([
'users_id' => $user->id,
'agent_id' => null,
'purpose' => 'Some Purpose',
'agent_token_id' => $token->id,
'amount' => $request->amount,
'payment_method' => 'Agent Token',
'status' => 1,
]);
$user_jorunal = User_journal::create([
'bill2_id' => $billing->id, //Intentionally made this error to test transaction, this should be 'bill_id'
'u_id' => $user->id,
'purpose' => 'Topup via Agent Token',
'debit' => $billing->amount,
'invoice_number' => time(),
]);
$status = $status && $billing && $user_jorunal;
} catch (\Exception $e)
{
DB::rollBack();
//throw $e; //sometime you want to rollback AND throw the exception
}
//if previous DB action are OK
if ($status)
{
DB::commit();
if ($this->agentTokenBalance($request->token_id) == 0)
{
$token->status = 1;
$token->update();
}
return response()->json(['status' => true, 'message' => 'TopUp was Successful!']);
} else
{
DB::rollBack();
//return somme errors
}
Please note that MyIsam engine doesn't support transaction as explained here MyIsam engine transaction support.
Haven't used the DB::transaction with a callback method... but you can do the following
DB::beginTransaction();
$billing = new User_billings;
$billing->users_id = $user->id;
// rest of the assignments
$billing->save();
// Rest of your code... Inserts, Deletes, Updates...
DB::commit();
You don't need to implement the DB::rollBack() in this case, if anything fails between those two lines, the transaction won't commit.

ERROR: 6 - No data received from server in infusionsoft iSDK while adding contact

require_once APPPATH.'third_party/infusionsoft_api/iSDK/src/isdk.php';
class Infusion
{
$app = new iSDK;
if($app->cfgCon("infusionapi",$app_name, $api_key)) {
$conDat = array(
'FirstName' => 'ss',
'LastName' => 'aa',
'Email' => 'sachin.patil#gmail.com',
'StreetAddress1' => '11'
);
$conId = $app->addCon("Contact", $conDat);
echo "sss".$conId;
exit;
}
}
Sachin, are you checking to see if an error was generated? If an error is being thrown, you won't get back any return data but the error will be waiting for review in the result faultString() and result faultCode()

Building a response array after binding parameters for PDO

I am trying to build the array that will return to my ajax success. How do I build the array after binding it to something like :some variable.
The following script runs to completion, and inserts with no problem into sql. But the variables comment and transaction come back as null in the response. I think the problem is using $comment and $transaction when building the array. What is the right way to reference these values in the array?
require('../dbcon2.php');
//Connection 1
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("UPDATE listings SET comment = :comment, transaction = :transaction, ad_link = :ad_link WHERE id = :id");
// Bind
$stmt->bindParam(':id', $_POST['id']);
$stmt->bindParam(':comment', $_POST['comment']);
$stmt->bindParam(':transaction', $_POST['transaction']);
$stmt->execute();
// Build array
$response = array
('state' => 200, "success" => true, "id" => ':id', "comment" => $comment, "transaction" => $transaction
);
exit(json_encode($response));
}
catch (Exception $e) {
// create a asociative array
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// encode data and exit.
exit(json_encode($data));
}
As per OP's wish:
Do as you did for "id" => ':id'
"id" => ':id', "comment" => ':comment', "transaction" => ':transaction'
Plus, quoting Jeroen (kudos to)
Why don't you use the $_POST variable? That contains the values you need and you use them already in your database query.
You can't retrieve bound values after calling ->bindParam(); also, the variables $comment and $transaction aren't defined (unless you set them yourself or when using voodoo php settings).
That said, you already know those values:
$response = array(
'state' => 200,
"success" => true,
"id" => $_POST['id'],
"comment" => $_POST['comment'],
"transaction" => $_POST['transaction'],
);
Btw, in the exception branch you have a small bug:
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
^
You should use $e->getMessage() instead.

Mandrill appears to be breaking a MySQL Select

I have stripped this right down, to try and find the source of this issue, but can not pin point it at all.
This successfully echos each of the IDs
$result = mysqli_query($con,"SELECT id FROM users");
// Each user matching criteria
while($row = mysqli_fetch_array($result))
{
echo $row['id'];
}
However when I include Mandrill it stops working, however I will still get the first ID echo'd
// Search Database for users who signed up yesterday
$result = mysqli_query($con,"SELECT id FROM users");
// Each user matching criteria
while($row = mysqli_fetch_array($result))
{
echo $row['id'];
include($_SERVER['DOCUMENT_ROOT'].'/src/Mandrill.php');
$mandrill = new Mandrill('hidden');
try {
$template_name = $content_template;
$message = array(
'html' => '<p>Example HTML content</p>',
'text' => 'Example text content',
'subject' => 'test',
'from_email' => 'hidden',
'from_name' => 'hidden',
'to' => array(
array(
'email' => 'hidden',
'name' => 'Tim',
'type' => 'to'
)
),
'headers' => array('Reply-To' => 'hidden.com'),
'important' => false,
'track_opens' => true,
'track_clicks' => true,
'tags' => array('$meta_tags'),
'google_analytics_domains' => array('hidden'),
'metadata' => array('website' => 'hidden')
);
$ip_pool = 'Main Pool';
$result = $mandrill->messages->sendTemplate('jotText-Auto-i101-welcome', $template_content, $message, $async, $ip_pool, $send_at);
print_r($result);
} catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
}
The error message I get is
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given in /home/timbaker/public_html/jottext/foundation/database_tasks/cron_welcome.php on line 18
Which suggests to me it is a problem with the original query... But I can't work out why Mandrill causes this to happen?
Also worth noting:
- No error messages from Mandril
- Email does successfully send
Initially, $result variable stored only the result of mysqli_query invocation, and it worked quite fine. But when you've added the mail-sending code, you accidentally reused the same variable for storing the result of Mandrill action:
$result = $mandrill->messages->sendTemplate(...);
...thus losing its initial value (of mysqli_result), and swapping it (a resource) with a new value (an array) - hence the error message you got.
Apparently, the easiest way out of this is renaming this variable:
$mailStatus = $mandrill->messages->sendTemplate(...);
print_r($mailStatus); // or do something else with it
The bottom line: try to avoid too generic names - eventually all $vars and $data and $result will bite you quite hard when you mix them. And I'm not even talking about readability here. )
As a sidenote (kudos to #Pierre for mentioning that), you'd better move instantiating of $mandrill variable outside of the loop - otherwise you'll have include working each time a new row is processed.

Internal Server Error Zend Query

Is something wrong with my query
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, ##ServerAdmin## and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
$sql = $db->query(
"INSERT INTO users (user_id, title, first_name, last_name, user_identity_id, email_id, password, office_phone_number, public_id, session_id, address_id, created_by, last_modified_by, created_on, last_modified_on, is_activated, is_deprecated, middle_name, cell_phone_number, superviser_name, superviser_email, superviser_phone_number)
VALUES( :p_user_id,:p_title,:p_first_name,:p_last_name,:p_user_identity_id,:p_email_id,:p_password,:p_office_phone_number,:p_public_id,:p_session_id,:p_address_id,:p_created_by,:p_last_modified_by,:p_created_on,:p_last_modified_on,:p_is_activated,:p_is_deprecated,:p_middle_name,:p_cell_phone_number,:p_superviser_name,:p_superviser_email,:p_superviser_phone_number)",
array(
'p_user_id' => '',
'p_title' => $title,
'p_first_name' => $first_name,
'p_last_name' => $last_name,
'p_user_identity_id' => '',
'p_email_id' => $email,
'p_password' => $pass,
'p_office_phone_number' => $office_ph_no,
'p_public_id' => '',
'p_session_id' => '',
'p_address_id' => '',
'p_created_by' => '',
'p_last_modified_by' => '',
'p_created_on' => '',
'p_last_modified_on' => '',
'p_is_activated' => '',
'p_is_deprecated' => '',
'p_middle_name' => $middle_name,
'p_cell_phone_number' => $cell_ph_no,
'p_superviser_name' => $supervisor_name,
'p_superviser_email' => $supervisor_email,
'p_superviser_phone_number' => $supervisor_ph_no
)
);
$db->commit();
This looks like you're trying to execute a PDO statement using named parameters in Zend.
First thing to check, I assume you've started a transaction?
Also, in my experience named parameters are the same in the query as in the params array, e.g. :param1 is $params = array(':param1'=>'data');
I use the same method as described in the ZF docs "executing a statement using named parameters":
$select = 'select col1,col2 from my_table where con1=:param1 and con2=:param2';
$params = array(
':param1'=> 'somedata',
':param2'=> 'someotherdata'
);
$statement = new Zend_Db_Statement_Pdo($db,$sql);
if($statement->execute($params)){
//ok!
}

Categories