Internal Server Error Zend Query - php

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!
}

Related

Is there a way to handle large arrays of colums from MySQL when importing via $POST

I am trying to work on a API to import data to MySQL Database.
I have it working on a small scale.
I have now altered it so its more in line with the current database. Its a large table and been poorly structured, But for simplicity and maintaining am trying to keep MySQL database and the Applications database inline.
MSQL = Windows based application:
MySQL = The Server database, Am extracting Data out of MSQL hosted locally and importing it to a MySQL Database hosted externally.
As i have expanded the code, its no longer working, this could be a number of factors like the table needs structuring / indexing / primary, or i am passing too much data via a query. The application is starting to look very messy.
The question is, is it necessary and better practice me listing out each column and matching up the data sets apposed to trying to utilize the MySQL INFORMATION_SCHEMA to list the columns instead.
Here is the code so far, I have already removed a number of columns.
We have a Server and Host:
Server Code
Class file: Api.php
class API
{
private $connect = '';
function __construct()
{
$this->database_connection();
}
function database_connection()
{
$this->connect = new PDO("mysql:host=$Host;dbname=$DatabaseName", $DatabaseUsername, $DatabasePassword);
}
function insert() // Insert Function
{
if(isset($_POST["Branch"]))
{
$form_data = array(
':Branch'=>$_POST['Branch'],
':Date'=>$_POST['Date'],
':Week'=>$_POST['Week'],
':Period'=>$_POST['Period'],
':Invoice_No'=>$_POST['Invoice_No'],
':Invoice_Reference'=>$_POST['Invoice_Reference'],
':Line_No'=>$_POST['Line_No'],
':Till_No'=>$_POST['Till_No'],
':Operator'=>$_POST['Operator'],
':Stock_Code'=>$_POST['Stock_Code'],
':Barcode'=>$_POST['Barcode'],
':Line_Quantity'=>$_POST['Line_Quantity'],
':Weight'=>$_POST['Weight'],
':Weight_Unit'=>$_POST['Weight_Unit'],
':Man_Weighed'=>$_POST['Man_Weighed'],
':Unit_ID'=>$_POST['Unit_ID'],
':Line_Price_Band'=>$_POST['Line_Price_Band'],
':Original_Sell'=>$_POST['Original_Sell'],
':Actual_Sell'=>$_POST['Actual_Sell'],
':Cost'=>$_POST['Cost'],
':Vat_Rate'=>$_POST['Vat_Rate'],
':Discount_Rate'=>$_POST['Discount_Rate'],
':Value_Goods'=>$_POST['Value_Goods'],
':Value_VAT'=>$_POST['Value_VAT'],
':Value_Sale'=>$_POST['Value_Sale'],
':Value_Cost'=>$_POST['Value_Cost'],
':Price_Override_Amount'=>$_POST['Price_Override_Amount'],
':Price_Overrided'=>$_POST['Price_Overrided'],
':Discounted'=>$_POST['Discounted'],
':Account_No'=>$_POST['Account_No'],
':Sub_Account_No'=>$_POST['Sub_Account_No'],
':Customer_Account'=>$_POST['Customer_Account'],
':Sub_Customer_Account'=>$_POST['Sub_Customer_Account'],
':Cust_Type_ID'=>$_POST['Cust_Type_ID'],
':Super_Department_ID'=>$_POST['Super_Department_ID'],
':Department_ID'=>$_POST['Department_ID'],
':Group_ID'=>$_POST['Group_ID'],
':Sub_Group_ID'=>$_POST['Sub_Group_ID'],
':Retail_Location_ID'=>$_POST['Retail_Location_ID'],
':Retail_Sub_Location_ID'=>$_POST['Retail_Sub_Location_ID'],
':Entry_Method'=>$_POST['Entry_Method'],
':End_Sale_Discount_Rate'=>$_POST['End_Sale_Discount_Rate'],
':Loyalty_Discount_Rate'=>$_POST['Loyalty_Discount_Rate'],
':Date_Time_Stamp'=>$_POST['Date_Time_Stamp']
);
$query = "
INSERT INTO Lines
(Branch, Date, Week, Period, Invoice_No, Invoice_Reference, Line_No, Till_No, Operator, Stock_Code, Barcode, Line_Quantity, Weight, Weight_Unit, Man_Weighed, Unit_ID, Line_Price_Band, Original_Sell, Actual_Sell, Cost, Vat_Rate, Discount_Rate, Value_Goods, Value_VAT, Value_Sale, Value_Cost, Price_Override_Amount, Price_Overrided, Discounted, Account_No, Sub_Account_No, Customer_Account, Sub_Customer_Account, Cust_Type_ID, Super_Department_ID, Department_ID, Group_ID, Sub_Group_ID, Retail_Location_ID, Retail_Sub_Location_ID, Entry_Method, End_Sale_Discount_Rate, Loyalty_Discount_Rate, Date_Time_Stamp) VALUES
(:Branch, :Date, :Week, :Period, :Invoice_No, :Invoice_Reference, :Line_No, :Till_No, :Operator, :Stock_Code, :Barcode, :Line_Quantity, :Weight, :Weight_Unit, :Man_Weighed, :Unit_ID, :Line_Price_Band, :Original_Sell, :Actual_Sell, :Cost, :Vat_Rate, :Discount_Rate, :Value_Goods, :Value_VAT, :Value_Sale, :Value_Cost, :Price_Override_Amount, :Price_Overrided, :Discounted, :Account_No, :Sub_Account_No, :Customer_Account, :Sub_Customer_Account, :Cust_Type_ID, :Super_Department_ID, :Department_ID, :Group_ID, :Sub_Group_ID, :Retail_Location_ID, :Retail_Sub_Location_ID, :Entry_Method, :End_Sale_Discount_Rate, :Loyalty_Discount_Rate, :Date_Time_Stamp)
";
$statement = $this->connect->prepare($query);
if($statement->execute($form_data))
{
echo $statement ;
$data[] = array(
'success' => '1'
);
}
else
{
var_dump($statement) ;
$data[] = array(
'success' => '0'
);
}
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}
}
Calling the Function: Handler test_api.php
// This does have an include for Api.php
if($_GET["action"] == 'insert')
{
$data = $api_object->insert();
}
Host code
This wont be the final thing, as ill be extracting from MSQL building the array and posting this way, This is just laid out like so for testing
<?php
$form_data = array(
'Branch' => '1',
'Date' => '8/11/2018 13:42:00',
'Week' => '1',
'Period' => '1',
'Invoice_No' => '9999998',
'Invoice_Reference' => '99999998',
'Line_No' => '1',
'Till_No' => '1',
'Operator' => '99',
'Stock_Code' => '123456',
'Barcode' => '654321',
'Line_Quantity' => '99',
'Weight' => '',
'Weight_Unit' => '',
'Man_Weighed' => '',
'Unit_ID' => '',
'Line_Price_Band' => '1',
'Original_Sell' => '99.99',
'Actual_Sell' => '99.99',
'Cost' => '9.99',
'Vat_Rate' => '1',
'Discount_Rate' => '',
'Value_Goods' => '',
'Value_VAT' => '',
'Value_Sale' => '',
'Value_Cost' => '',
'Price_Override_Amount' => '',
'Price_Overrided' => '',
'Discounted' => '',
'Account_No' => '',
'Sub_Account_No' => '',
'Customer_Account' => '',
'Sub_Customer_Account' => '',
'Cust_Type_ID' => '',
'Super_Department_ID' => '',
'Department_ID' => '',
'Group_ID' => '',
'Sub_Group_ID' => '',
'Retail_Location_ID' => '',
'Retail_Sub_Location_ID' => '',
'Entry_Method' => '',
'End_Sale_Discount_Rate' => '',
'Loyalty_Discount_Rate' => '',
'Date_Time_Stamp' => ''
);
$api_url = "localhost/Modules/API/Server/test_api.php?action=insert"; //change this url as per your folder path for api folder
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
// var_dump($response);
curl_close($client);
$result = json_decode($response, true);
echo $response ;
foreach($result as $keys => $values)
{
if($result[$keys]['success'] == '1')
{
echo 'update';
}
else
{
echo 'error';
echo $response ;
}
}
At the moment its not working, I am not sure why, As it was working fine with a much smaller dataset.
And my IDE hasnt reported of any errors or typos, But thats something else, if you do spot a error, please do say.
The question is, is there a better way to work with large number of columns.
In previous API's i have basically just dumped the data to txt and imported from a deliminator. So this is all very new to me.

Mysqli Connect Database Error When Connetion Unstable When Database Is Loaded Twice Codeigniter

I have unsolved case when use $this->load->database("Db",TRUE); Please note that iam using codeigniter in here.
Here is the case :
I make a controller named "cdata" this controller handle and save a device log from absence machine. I am using ADMS type absence machine.
How ADMS Machine work ?
When an employee do a finger scan, the absence machine will send a Http Request named "cdata". This "cdata" contain a log from absence in raw data so i will use handle raw data in codeigniter to capture a log absence like time, user id, state checkin or check out. So when ADMS machine send a request "cdata" i will have a controller named "cdata" to handle it.
The script "cdata" is like below :
class cdata extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$result = "NONE";
$table = $this->input->get('table');
$sn = $this->input->get('SN');
$op = $this->input->get('options');
if ($table == "ATTLOG"){
$data = file_get_contents("php://input");
log_message('error', $data);
echo "OK:1
POST from: ".$sn."";
$result = "OK:1";
$arraydata = explode(chr(9),trim($data));
if (count($arraydata) > 0) {
$userid = $arraydata[0];
$date = $arraydata[1];
$state = $arraydata[2];
$verification = $arraydata[3];
$workcode = $arraydata[5];
$reserved = $arraydata[6];
$insertdata = array("sn_device"=>$sn,
"user_id"=>$userid,
"date_time"=>$date,
"state"=>$state,
"verification"=>$verification,
"work_code"=>$workcode,
"reserved"=>$reserved,
"create_date"=>date('Y-m-d H:i:s'),
"ip_address"=>$_SERVER["REMOTE_ADDR"]);
$result = $this->db->insert("tbl_log",$insertdata);
}
$this->db->trans_start();
$this->db->from('tbl_forward');
$this->db->where(array('sn_device = ' => $this->db->escape_str($sn)));
$row = $this->db->get()->result();
foreach ($row as $rows) {
$db = array(
'dsn' => '',
'hostname' => $rows->hostname,
'port' => $rows->port,
'username' => $rows->username,
'password' => $rows->password,
'database' => $rows->database_name,
'dbdriver' => $rows->db_type,
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE);
$this->sqldb = $this->load->database($db, TRUE);
if ($rows->db_type == "sqlsrv") {
$LogNo = $this->models_database->GenerateNo ('DeviceLogs','LogNo');
}
if(count($arraydata) > 0) {
$userid = $arraydata[0];
$date = $arraydata[1];
$state = $arraydata[2];
$verification = $arraydata[3];
$workcode = $arraydata[5];
$reserved = $arraydata[6];
if ($rows->db_type == "mysqli") {
$insertdata = array("DeviceNo" => $rows->receiver_id,
"UserID" => $userid,
"LogDate" => $date,
"EditedUserID" => $userid,
"EditedDeviceNo" => $rows->receiver_id,
"EditedLogDate" => $date,
"CreatedBy" => "ADMS",
"CreatedOn" => date('Y-m-d H:i:s'),
"LogTypeNo" => $state,
"EditedLogTypeNo" => $state,
"IsEdit" => True,
"IsImport" => 1,
"IsAutoCreated" => 1,
"LogSourceNo" => 1,
"IsDefault" => NULL,
"Remarks" => "None",
"UpdateOn" => date('Y-m-d H:i:s'),
"UpdateBy" => "ADMS",
"FileID" => 1,
"TempID" => 1,
"VerifyMethodNo" => 0,
"BranchNo" => NULL,
"FileName" => NULL,
"CardNo" => NULL);
$result = $this->sqldb->insert("DeviceLogs",$insertdata);
} else if ($rows->db_type == "sqlsrv") {
$insertdata = array("LogNo"=>$LogNo,
"DeviceNo" => $rows->receiver_id,
"UserID" => $userid,
"LogDate" => $date,
"EditedUserID" => $userid,
"EditedDeviceNo" => $rows->receiver_id,
"EditedLogDate" => $date,
"CreatedBy" => "ADMS",
"CreatedOn" => date('Y-m-d H:i:s'),
"LogTypeNo" => $state,
"EditedLogTypeNo" => $state,
"IsEdit" => True,
"LogSourceNo" => 1,
"IsDefault" => 1,
"Remarks" => "None",
"UpdateOn" => date('Y-m-d H:i:s'),
"UpdateBy" => "ADMS",
"CardNo" => NULL);
$result = $this->sqldb->insert("DeviceLogs",$insertdata);
}
}
}
$this->db->trans_complete();
}
}
}
That script is use to save an absence log to a local database and then forward a absence log to another database where it is depend on the hostname, username, password and database name.
The problem is here :
When the connection is stable or is good. It doesn't matter how fast i do a finger scan the controller will do as it and the data saved to local and saved to another database without an error.
But when i make the connection unstable or bad connection (this i make a high packet in this two ip, one from machine and one the computer) we can call the connection LAGGER, when i repeatly do a finger scan, i got an error when calling cdata twice in this line :
$this->sqldb = $this->load->database($db, TRUE);
The error is :
Message: mysqli::real_connect(): (HY000/2002): A connection
attempt failed because the connected party did not properly respond
after a period of time, or established connection failed because
connected host has failed to respond.\r\n
It is look like when controller cdata is called i cannot call load database twice when in unstable connection.
What should i do ? What is wrong in here ?
From my opinion maybe this first "cdata" load database $this->sqldb = $this->load->database($db, TRUE); is still loading and then another called "cdata" load database $this->sqldb = $this->load->database($db, TRUE); is called too.
Thank You
Dennis Liu

Query looks OK but I have error

I have this SQL Query
$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');
$sql->execute(array('Status' => 'NotActive', 'Username' => $Username, 'Password' => $PasswordHash, 'FirstName' => $FirstName, 'LastName' => $LastName, 'EmailAddress' => $EmailAddress, 'API_Status' => 'OFF', 'API_Key' => $API_Key, 'About' => $Other));
When executing this query I'm using try { and
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
Now when I run script Iget this PHP error:
Catchable fatal error: Object of class PDOStatement could not be
converted to string in /var/www/html/register.php on line 94
How I can slove this problem?
Problems with question.
Wrong naming. SQL is a text that is passed to prepare(). While returned value is an object. Problem not solved.
Due to wrong naming the OP is trying to echo an object. Problem not solved.
Thanks to the great site of Stack Overflow, the OP is taught terrible wrong way of handling PDO errors, with useless try..catch stuff. Problem not solved.
: is missed for one placeholder. The only problem solved.
As a result, next time this query throws an exception, THE SAME UTTERLY USELESS and irrelevant error message will be produced.
What should be done instead?
$sql = 'INSERT INTO Accounts
(Status, Username, Password, FirstName, LastName, EmailAddress,
API_Status, API_Key, About)
VALUES (:Status, :Username, :Password, :FirstName,
:LastName, :EmailAddress, :API_Status, :API_Key, :About)';
$data = array(
'Status' => 'NotActive',
'Username' => $Username,
'Password' => $PasswordHash,
'FirstName' => $FirstName,
'LastName' => $LastName,
'EmailAddress' => $EmailAddress,
'API_Status' => 'OFF',
'API_Key' => $API_Key,
'About' => $Other
);
$conn->prepare($sql)->execute($data);
What do we have here?
proper naming. if one have a fancy of echoing an SQL query, they will be no mistaken.
readability. No long and windy code off the screen, allowing us to visually inspect the query and find the syntax error.
corrected placeholder syntax.
no statement object is echoed. Neither SQL is, as it makes very little sense in case of a prepared statement.
no stupid try..catch block. Means PHP will be able to notify PHP user in case of error occurred.
you can't echo your sql as you are using, you may need to use debugDumpParams() try something like this.
$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');
$sql->execute(array(':Status' => 'NotActive', ':Username' => $Username, ':Password' => $PasswordHash, ':FirstName' => $FirstName, ':LastName' => $LastName, ':EmailAddress' => $EmailAddress, ':API_Status' => 'OFF', ':API_Key' => $API_Key, ':About' => $Other));
echo $sql->debugDumpParams();

Syntax Error 4200 on a prepared statment with PDO

Hi i try to execute the following prepared statment
$sql = "INSERT INTO cc_a (entite_juridique, enseigne_commerciale, raison_sociale, adresse, adresse2, cp, ville, country, region, departement, tel , email, website , categorie, facebook, twitter, google, siren, lieu_immat, capital, description, status)
VALUES (:entite_juridique, :enseigne_commerciale, :raison_sociale,:adresse, :adresse2,:cp,:ville, :country, :region, :departement, :tel, :email, :website, :categorie, :facebook,:twitter, :google, :siren,:lieu_immat, :capital, :description, :status)";
$sth = $dbh->prepare($sql);
$sth->execute(array(':entite_juridique' => $entite_juridique, ':enseigne_commerciale' => $enseigne_commerciale,':raison_sociale' => $raison_sociale,
':adresse' => $adresse, ':adresse2' => $adresse2,':cp' => $cp,
':ville' => $ville, ':country' => $country, ':region' => $region,
':departement' => $departement, ':tel' => $tel , ':email' => $email,
':website' => $website , ':categorie'=> $categorie, ':facebook' => $facebook,
':twitter' => $twitter, ':google' => $google, ':siren' => $siren,
':lieu_immat' => $lieu_immat, ':capital' => $capital , ':description' => $description, ':status' => $status ));
but i got the followin error code.
I do not see where there is an error...
Erreur : SQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
':entite_juridique, :enseigne_commerciale, :raison_sociale,:adresse,
:adresse2,:c' at line 2
Is someone see why?

PDO Insert SQL not executing with no errors

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.

Categories