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#
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 am new to mysqli and was going through a tutorial from: http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17#comment1
I was able to connect to my database using this:
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if($connection === false) {
die('Connection failed [' . $db->connect_error . ']');
}
echo("hello"); //this worked!
But then I tried wrapping it in a function (as discussed in the tutorial)... I saw that you call the connection function from another function... in the tutorial each function keeps getting called from another and another... and I never quite found where the initial call started from to get the domino effect of functions calling eachother.. so anyway, I tried to stop it at two just to test and teach myself.. but it's not working and I don't know why:
function db_connect() {
static $connection;
if(!isset($connection)) {
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
echo("hello2");
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
echo("hello1");
}
db_query("SELECT `Q1_Q`,`Q1_AnsA` FROM `Game1_RollarCoaster`"); //this didn't work :(
Well I ended up taking it out of the functions and made the code super simple (sticking with procedural instead of OOP even though a lot of tutorials use OOP - thought it was better to start this way):
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_Q] . '<-- Here is your question! ' . $row[Q1_AnsA] . '<-- Here is your answer! ';
echo '<br />';
}
mysqli_free_result($result);
mysqli_close($link);
?>
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}
I know this question has been answered before, but I actually have an error when I use an the following:
try {
$conn = new PDO('mysql:host=localhost;dbname=open', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$count=$conn->prepare(" SELECT * FROM `dictionary` WHERE word = ':input' ");
$count->bindParam(":input",$input);
$count->execute();
$no=$count->rowCount();
if( $no > 0 ){
echo "no";
}
Which gives me the error:
Fatal error: Call to a member function prepare() on a non-object in... on line 18
I don't see where the error is, particularly because I based this code off an accepted answer.
try replace this
word = ':input'
by
word = :input
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());
}
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.