Returning id from access database - php

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);
}

Related

Informix ODBC Driver... Invalid connection string attribute?

I had never used PDO for to connect with Informix database before, this error poped up while I was running a basic query:
SQLSTATE=01S00, SQLDriverConnect: -11005 [Informix][Informix ODBC Driver]Invalid connection string attribute.
And this is my code:
<?php
class prueba{
private static $cn = null;
public static function conectar(){
if(self::$cn !== null ) {
return self::$cn;
}
try{
self::$cn= new PDO("informix:host=localhost; service=30000;
database=mrroot; server=mrserver; protocol=onsoctcp;
EnableScrollableCursors=1", "mrtony", "");
return self::$cn;
} catch (PDOException $ex){
die($ex->getMessage());
}
}
public static function consulta(){
$query = "SELECT * FROM fr_envio";
$cn = prueba::conectar();
$resultado = $cn->prepare($query);
$resultado->execute();
echo '<table>';
while ($row = $resultado->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>'.$row['enviopre'].'</td>';
echo '<td>'.$row['enviofra'].'</td>';
echo '<td>'.$row ['enviopec'].'</td>';
echo '<td>'.$row ['envioval'].'</td>';
echo '</tr>';
}
echo '</table>';
}
}
$prueba = new prueba();
$prueba->consulta();
?>
I've tested the same code on Mysql, just change the connection string, and everything works perfect, it seems like the connection string is missing something, and I dont know what it could be.
I followed what is says in this tutorial:
https://www.ibm.com/support/knowledgecenter/en/SSGU8G_12.1.0/com.ibm.virtapp.doc/TD_item2.htm
Ummm... try specifing the connection string in just one line.
root#irk:/usr3/products/php53# cat test.php
<?php
$db = new PDO("informix:host=irk;service=3046;database=stores7;
server=irk1210;protocol=onsoctcp;EnableScrollableCursors=1;", "informix", "ximrofni");
print "Connection Established!\n\n";
$stmt = $db->query("select * from systables");
$res = $stmt->fetch( PDO::FETCH_BOTH );
$rows = $res[0];
echo "Table contents: $rows.\n";
?>
root#irk:/usr3/products/php53# php test.php
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE=01S00, SQLDriverConnect: -11005 [Informix][Informix ODBC Driver]Invalid connection string attribute.' in /usr3/products/php5/test.php:4
Stack trace:
#0 /usr3/products/php5/test.php(4): PDO->__construct('informix:host=i...', 'informix', 'ximrofni')
#1 {main}
thrown in /usr3/products/php5/test.php on line 4
root#irk:/usr3/products/php53#
Like this:
root#irk:/usr3/products/php53# cat test.php
<?php
$db = new PDO("informix:host=irk;service=3046;database=stores7; server=irk1210;protocol=onsoctcp;EnableScrollableCursors=1;", "informix", "ximrofni");
print "Connection Established!\n\n";
$stmt = $db->query("select * from systables");
$res = $stmt->fetch( PDO::FETCH_BOTH );
$rows = $res[0];
echo "Table contents: $rows.\n";
?>
root#irk:/usr3/products/php53# php test.php
Connection Established!
Table contents: systables.
root#irk:/usr3/products/php53#

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());
}

Using PHP to query a MDB file, and return JSON

I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);

Query Error on db connection

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.

oci_parse error message

I get this error message, what does it mean and how to fix it?
Warning: oci_parse() expects parameter 1 to be resource, null given in /user_auth_fns.php on line 3
$conn = db_connect();
$result = oci_parse($conn, "select * from user where username='$username' and passwd = sha1('$password')");
if (!$result){
$err = oci_error();
echo "Could not log you in.";
exit;
}
$r = oci_execute($result);
if (!$r) {
$error = oci_error($conn);
echo "Could not log you in." . $error['message'];
exit;
}
function db_connect()
{
$db = "dbms";
if ($c=oci_connect("username", "password", $db)){
echo "Successfully connected to Oracle.\n";
OCILogoff($c);
} else {
$err = OCIError();
echo "Oracle Connect Error " . $err[text];
}
}
Edit 2 fixed the problem, another error message, what other compression function(other than SHA1) should use for oracle?
Warning: oci_execute() [function.oci-execute]: ORA-00904: "SHA1": invalid identifier in /user_auth_fns.php on line 10
I don't know what db_connect() is returning. Maybe it is just creating a connection by its own. Try this:
$conn = oci_connect("userName","password","hostName");
fill up the useName & password & hostName here. if you are having problem with hostName then try to put the whole connection string there. example:
$conn = oci_connect('userName', 'password', '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT = )) (CONNECT_DATA = (SERVICE_NAME = ) (SID = )))');
then you can create a query like
$query="....";
then you can parse like this:
$result = oci_parse($conn, $query);
if you succeed in querying then $result holds Boolean value 'true'.
Your $conn variable is null. How do you instantiate that?
Edit
You instantiate $conn from db_connect(), which is not part of the standard PHP library so I can not tell you what's wrong with it other than it's returning null.
Edit 2
You're db_connect() doesn't return anything. Additionally, you close the connection immediately after opening it. Try this:
function db_connect()
{
$db = "dbms";
if ($c=oci_connect("username", "password", $db)){
echo "Successfully connected to Oracle.\n";
//OCILogoff($c); // You probably don't want to close the connection here
return $c;
} else {
$err = OCIError();
echo "Oracle Connect Error " . $err[text];
}
}
It means that $conn has no value, it is null. What did you want to have in $conn? Go back and check that.

Categories