Getting Error Message For oci_execute() Error (PHP) - oracle

I would like to get the specific error message if a query fails in Oracle 10g. For MySQL, PHP has the mysql_error() function that can return details about why a query failed. I check the php.net manual for the oci_execute() function, but from what I see it only returns false on fail.
I tried using oc_error(), but I am not getting anything from it.
Here is a code sample:
$err = array();
$e = 0;
//Cycle through all files and insert new records into database
for($f=0; $f<sizeof($files); $f++)
{
$invoice_number = $files[$f]['invoice_number'];
$sold_to = $files[$f]['sold_to'];
$date = $files[$f]['date'];
$sql = "insert into invoice (dealer_id, invoice_number, invoice_date)
values ('$sold_to', '$invoice_number', '$date')";
$stid = oci_parse($conn, $sql);
$result = oci_execute($stid);
//If query fails
if(!$result)
{
$err[$e] = oci_error();
$e++;
}
}
print_r($err);
Response for print_r($err):
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => )

Have you tried to pass $stid to oci_error?
$err[$e] = oci_error($stid);

The oci_error() function takes an argument that specifies the context of your error. Passing it no argument will only work for certain kinds of connection errors. What you want to do is pass the parsed statement resource, like so:
$err = oci_error($stid);
(Note also that the return value from oci_error is an array, so I assigned the entire output to your $err array variable)

Related

Trying to get Values between 2 dates but need start date and end date should be as given instead of as per database

I am trying to get data between "Start" and "End" dates from database which is working fine and query giving me the result, Say
Start = 09-02-2022.
End = 10-03-2022.
Database values start = "01-03-2022 to 09-03-2022" so i am getting result from date say 16-02 to 01-03.
But i want result should start with 09-02 and end with 10-03. If value is not present in database then it should give as "0"
Check attached Image for reference.
Code for Getting dates for last 30 days -
$getalldates = array();
for($d = (Carbon::today()->subDays(30)); $d->lte(carbon::today()); $d->addDay())
{ $getalldates[] = $d->format('Y-m-d');}
Code for Getting data from database
$rahul = Buffalomilkrecord::select(DB::raw('date'), DB::raw('sum(totalmilk) as totalmilk, DATE_FORMAT(date,"%d") as "daykey"'))
->whereBetween('date', [$olddate, $todaydate] )
->groupBy(DB::raw('date'))
->orderBy('date','asc')
->get()->pluck('date')->toArray();
Thanks in Advance.
This is what i tried
$result = array();
foreach($getalldates as $date){
$totalmilk= Buffalomilkrecord::select(DB::raw('sum(totalmilk) as totalmilk'))->whereDate('date',$date)->pluck('totalmilk');
if($totalmilk){
$result[] = array($date =>$totalmilk);
} else {
$result[] = array($date =>0);
}
}
I am expecting
This is my output 0 => array:1 [▼ "2022-02-09" => Illuminate\Support\Collection {#348 ▼ #items: array:1 [▼ 0 => null ] }
and i am expecting "2022-02-09" = "0"
Check Image

Laravel differences linux and windows hosting

This is very strange: On Windows these functions with exactly the same databases works greats, but when I upload the project to Linux the pageinfo() function returns null. Of course the first thing I thought was that this has to do with case sensitivity, but all seems well formatted...
In my Page Model:
public function pageinfo() {
return $this->hasMany('App\Models\PageToElement', 'page_id');
}
(The Model PageToElement is exactly called like this)
In my controller:
$this->info = Page::find($page->page_id);
$meta = $this->info->pageinfo->where('element_id', 1)->first();
On Windows this nicely returns array:
App\Models\PageToElement Object (
[attributes:protected] => Array(
[id] => 1
[page_id] => 1
[element_id] => 1
[element_parent_id] => 0
[parent_id] => 0
[sorting] => 0
[is_active] => 1
[created_at] => 2015-12-07 10:00:03
[updated_at] => 2015-12-07 10:00:03
)
)
But on Linux, the response is null
What am I overlooking?
After some research, I came to the conclusion that $meta = $this->page->pageinfo->where('element_id', 1)->first(); returns null on the Linux server. But when I do $meta = $this->page->pageinfo; I do get more than one item in return. When I then do $meta = $this->page->pageinfo->first(); it returns one. So I think somehow the where('element_id', 1) is not working for Linux.
But what do you know, $meta = $this->page->pageinfo->where('element_id', '1')->first(); works! element_id is an integer, so why does it need quotes???
But what do you know, $meta = $this->page->pageinfo->where('element_id', '1')->first(); works! But then again not on Windows.
So I wounded up adding an extra line $id = 1; and parsing that in the query.
Strange workaround though

`sequel` orm fails when a string value is passed in a hash in `where` clause

I don't have idea what's going on when I use .where(:status_name => 'Active') instead of .where("status_name = 'Active'") it also happens when I use a string variable instead of harcode the 'Active' string
[1] pry(#<DefenseFeature>)> #db[:defense_status_tbl].select(:defense_status_id).where(:status_name => 'Active').single_record
Sequel::DatabaseConnectionError: Mysql2::Error: Can't connect to MySQL server on '127.0.0.1' (61)
from /Users/calopez/.rvm/gems/ruby-2.1.5/gems/mysql2-0.3.17/lib/mysql2/client.rb:70:in `connect'
[2] pry(#<DefenseFeature>)> #db[:defense_status_tbl].select(:defense_status_id).where("status_name = 'Active'").single_record
=> {:defense_status_id=>2}
Showing sql query generate:
[3] pry(#<DefenseFeature>)> #db[:defense_status_tbl].select(:defense_status_id).where(:status_name => 'Active')
=> #<Sequel::Mysql2::Dataset:0x3fc29dcc5d2c>
[4] pry(#<DefenseFeature>)> #db[:defense_status_tbl].select(:defense_status_id).where("status_name = 'Active'")
=> #<Sequel::Mysql2::Dataset: "SELECT `defense_status_id` FROM `defense_status_tbl` WHERE (status_name = 'Active')">

CodeIgniter ActiveRecord adding a random id field

$updatedOrder = array(
'ship_status' => 'shipped',
'shipped_carrier' => (string)$selectedShipper->shipper->name,
'base_rate' => (float)$selectedShipper->rate,
'discount_rate' => (float)$selectedShipper->rate,
'tracking_number' => '123',
);
$this->orders_m->where('id', $tmpOrder->id)
->update('orders', $updatedOrder);
This yields the following SQL query: UPDATE default_orders SET ship_status = 'shipped', shipped_carrier = 'UPS Next Day Air', base_rate = 22.85, discount_rate = 22.85, tracking_number = '123' WHERE id = '1' AND id = 'orders'
Where did that last bit come from? id='orders'?
Just make sure that $tmpOrder->id is a variable and not an array.
var_dump($tmpOrder->id);
Maybe there is an error somewhere where you are getting the $tmpOrder and it returns an array for that.

Codeigniter CSV upload then explode

I have some code that uploads the CSV file to the specified folder, but it doesn't update the database.
public function do_upload()
{
$csv_path = realpath(APPPATH . '/../assets/uploads/CSV/');
$config['upload_path'] = $csv_path;
$config['allowed_types'] = '*'; // All types of files allowed
$config['overwrite'] = true; // Overwrites the existing file
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->layout->buffer('content', 'program/upload', $error);
$this->layout->render();
}
else
{
$image_data = $this->upload->data();
$fname = $image_data['file_name'];
$fpath = $image_data['file_path'].$fname;
$fh = fopen($fpath, "r");
$insert_str = 'INSERT INTO wc_program (JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish) VALUES '."\n";
if ($fh) {
// Create each set of values.
while (($csv_row = fgetcsv($fh, 2000, ',')) !== false) {
foreach ($csv_row as &$row) {
$row = strtr($row, array("'" => "\'", '"' => '\"'));
}
$insert_str .= '("'
// Implode the array and fix pesky apostrophes.
.implode('","', $csv_row)
.'"),'."\n";
}
// Remove the trailing comma.
$insert_str = rtrim($insert_str, ",\n");
// Insert all of the values at once.
$this->db->set($insert_str);
echo '<script type="text/javascript">
alert("Document successfully uploaded and saved to the database.");
location = "program/index";
</script>';
}
else {
echo '<script type="text/javascript">
alert("Sorry! Something went wrong please proceed to try again.");
location = "program/upload";
</script>';
}
}
}
When I run var_dump($fh); it shows: resource(89) of type (stream)
When I run var_dump($fpath) it shows: string(66) "/Applications/MAMP/htdocs/site/assets/uploads/CSV/wc_program.csv"
So it all uploads but what is wrong with it not updating the database?
I have tried all kinds of changing the fopen method but still no joy, I really need it to add to the database and the insert query and set query should do the trick but it doesn't.
Any help greatly appreciated!
You are not running any query on the database. You are mixing active record syntax with simple query syntax. The active record insert query will be executed by calling.
$this->db->insert('my_table');
db::set() does not actually query the database. It takes in a key/value pair that will be inserted or updated after db::insert() or db::update() is called. If you build the query yourself you need to use the db::query() function.
Review the active directory documentation.
You can use $this->db->query('put your query here'), but you lose the benefit of CodeIgniter's built in security. Review CodeIgniter's query functions.
I'll give you examples of just a few of the many ways you can insert into a database using CodeIgniter. The examples will generate the query from your comment. You will need to adjust your code accordingly.
EXAMPLE 1:
$result = $this->db
->set('JobRef', 911847)
->set('Area', 'Coastal')
->set('Parish', 'Yapton')
->set('AbbrWorkType', 'Micro')
->set('WorkType', 'Micro-Asphalt Surfacing')
->set('Timing', 'TBC')
->set('TrafficManagement', 'No Positive Traffic Management')
->set('Location', 'Canal Road (added PMI 16/07/12)')
->set('Duration', '2 days')
->set('Start', '0000-00-00')
->set('Finish', '0000-00-00')
->insert('wc_program');
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n\n";
print_r($result);
EXAMPLE 2 (Using an associative array):
$row = array(
'JobRef' => 911847,
'Area' => 'Coastal',
'Parish' => 'Yapton',
'AbbrWorkType' => 'Micro',
'WorkType' => 'Micro-Asphalt Surfacing',
'Timing' => 'TBC',
'TrafficManagement' => 'No Positive Traffic Management',
'Location' => 'Canal Road (added PMI 16/07/12)',
'Duration' => '2 days',
'Start' => '0000-00-00',
'Finish' => '0000-00-00'
);
$this->db->insert('wc_program', $row);
// This will do the same thing
// $this->db->set($row);
// $this->db->insert('wc_program');
echo $this->db->last_query();
Example 1 and 2 are using the Active Record. The information is stored piece by piece and then the query is built when you make the final call. This has several advantages. It allows you to build queries dynamically without worrying about SQL syntax and order of the keywords. It also escapes your data.
EXAMPLE 3 (Simple Query):
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
("911847","Coastal","Yapton","Micro","Micro-Asphalt Surfacing","TBC","No Positive Traffic Management","Canal Road (added PMI 16/07/12)","2 days","0000-00-00","0000-00-00")';
$result = $this->db->query($query);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
This way leaves all the protection against injection up to you, can lead to more errors, and is harder to change/maintain.
If you are going to do it this way you should use the following syntax, which will protect against injection.
EXAMPLE 4:
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);';
$row = array(
911847,
'Coastal',
'Yapton',
'Micro',
'Micro-Asphalt Surfacing',
'TBC',
'No Positive Traffic Management',
'Canal Road (added PMI 16/07/12)',
'2 days',
'0000-00-00',
'0000-00-00'
);
$result = $this->db->query($query, $row);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
CodeIgniter will replace each "?" in the query with the corresponding value from the array after it is escaped. You can use this to run many queries that are of the same form, but have different data just by updating the $row array and benefit from CI's built in security.

Resources