PDO: select fetch last columns as NULL - php

when i select data from ODBC with PDO (in PHP) some columns are fetched as NULL, but in database data exists. Where i execute same query with odbc_* functions it works fine.
Here is code i using
$sql = "SELECT * FROM table WHERE rowid = 123456";
$connection = odbc_connect("Velocis RDS", $usr, $pwd);
$result = odbc_exec($connection, $sql);
while ($data = odbc_fetch_array($result)) {
print_r($data);
}
With this all columns are fetched correctly :
$connection = new PDO("odbc:Velocis RDS", $usr, $pwd);
$stmt = $dbConn->prepare("SELECT * FROM table WHERE rowid = 123456");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
print_r($stmt->fetchAll());
with this code last 9 columns are fetched as NULL. There is nothing special with this columns. It contains text or numbers.
Any help would be appreciated. Thanks in advance.

I actually had the exact same issue with a different type of database where the id field worked but the others returned null via pdo_odbc and worked 100% with odbc. After a lot of research I came across a PHP Bug report with similar issue (Bug#61573) but paved the way to for me to figure out a fix.
Try type casting the fields to VARCHAR. This worked for me. The issue is that pdo_odbc does not work with several types that odbc can.
For reference or if still needed please include the PHP version and table schema as these are important to figure out fixes. :)

Related

INSERT statement does not work with PDO

EDIT: PDO appears to have an issue with the French character in the column name Unité. Is there a solution to this, or do I need to rename the column in the database?
SELECT statements work with PDO, but the INSERT statement does not.
Connection string:
$dbCon = new PDO("mysql:host=".$host.";dbname=".$dbName.";charset=utf8", $username, $password);
Working SELECT statement:
$sql = 'SELECT * FROM availability WHERE event_id=:postID';
$stmt = $dbCon->prepare($sql);
$stmt->execute(array(':postID'=>$postID));
$result = $stmt->fetchAll();
Non-functioning INSERT statement:
$sql = 'INSERT INTO `availability` (`event_id`,`Nom`,`Address`,`Address2`,`Tel1`,`Tel2`,`Tel3`,`Classement`,`Soleil`,`Unité`,`Dispo`,`Ville`,`Type`,`URL`,`Jour1`,`Jour2`,`Jour3`,`Jour4`,`Jour5`,`Jour6`,`Jour7`,`Jour8`,`Jour9`,`Jour10`,`Jour11`,`Jour12`,`Jour13`,`Jour14`,`Jour15`,`visible`) (SELECT :postID,`Nom`,`Address`,`Address2`,`Tel1`,`Tel2`,`Tel3`,`Classement`,`Soleil`,`Unité`,`Dispo`,`Ville`,`Type`,`URL`,`Jour1`,`Jour2`,`Jour3`,`Jour4`,`Jour5`,`Jour6`,`Jour7`,`Jour8`,`Jour9`,`Jour10`,`Jour11`,`Jour12`,`Jour13`,`Jour14`,`Jour15`,`visible` FROM `default_hotels`)';
$stmt = $dbCon->prepare($sql);
$stmt->execute(array(':postID'=>$postID));
$result = $stmt->fetchAll();
Another working SELECT statement:
$sql = 'SELECT post_title FROM wp_posts WHERE id=:postID';
$stmt = $dbCon->prepare($sql);
$stmt->execute(array(':postID'=>$postID));
$records = $stmt->fetchAll();
All of the statements appear in this order in my script. The variables are re-used and not cleared.
The SQL INSERT statement that I provided works when submitted through phpmyadmin but not PDO.
The PDO charset parameter in the connection string started being supported in PHP 5.3.6. Before that it did nothing. So the problem is that the connection to your database is not actually run in utf8, but likely latin1. Hence the encoding of the column name in PHP and in MySQL doesn't match, hence MySQL misunderstands the column name, hence can't find the column you ask for.
See https://stackoverflow.com/a/279279/476 for alternative ways to specify the connection encoding, upgrade your version of PHP, or use ASCII-only for column names (that's a good idea anyway, specifically because it makes compatibility issues like this much less of a problem).

Fetch data with PHP and MySQL of a "text" column with special characters on it

I've a MySQL database that has this definition on one of its tables (theTable)
CREATE TABLE `theDatabase`.`theTable` (
`id` INT NOT NULL AUTO_INCREMENT ,
`thecolumn` TEXT NOT NULL ,
PRIMARY KEY (`id`) );
I'm trying this with PHP:
/*File executeSelect.php*/
mysql_connect("theServer","theUser","thePassword") or die(mysql_error());
mysql_select_db("theDatabase") or die (mysql_error());
$q = mysql_query($_REQUEST['query']);
while($e = mysql_fetch_assoc($q))
$output[] = $e;
print(json_encode($output));
mysql_close();
If I do a executeSelect.php?query=select * from theTable, the information shown for the column thecolumn is NULL if thecolumn has special characters. I've thecolumn defined as text because I need to store large texts on it (500~1000 letters).
For example, a executeSelect.php?query=select * from theTable with id=1;thecolumn=asdf in theTable works OK, but the same executeSelect with id=1;thecolumn=ásdf in theTable gives NULL for thecolumn.
I've tried to execute the same query using the MySQL console and it works OK. I'm using Apache 2.4 and PHP 5.3.
What I'm misshing here that my php code doesn't retrieve data from text columns of MySQL in a right way?
I would advise strongly against this as it's liable to SQL injection attacks from this kind of method
Should the code not be:
while($e = mysql_fetch_assoc($q))
$output[] = $e['thecolumn'];
print(json_encode($output));
mysql_close();
I would not recommend this method, and would recommend using PDO also
After 2 years, it bothers me that there is no answer in this question that solves my issue.
As pointed by Mike W in the comments of the question, the issue was with encoding in the sql client.
If using MySQLi, something like described in PHP: mysqli::set_charset - Manual can be used.
In my scenario, it was just a matter of doing a simple $mysqli->set_charset("utf8") right after opening the connection.

Call to a member function bind_result() on a non-object in ... on line 17

I have a books database, using mysqli and prepared statements I am SELECTing all the fields in the DB bar 1. The reason for this is the error
Call to a member function bind_result() on a non-object in C:\xampp\htdocs\registersite\phpscripts1\mysqli11.php on line 17
If I miss that field out I do not have any problems, as soon as I add it I get the error.
The database itself is fairly simple, a total of 13 fields, the PK being the id. The majority of the fields are varchar.
png screenshot of DBase
Database file link
The database field causing the problem is a field 12, condition. It is set as a varchar(10) but as soon as I introduce it to the SELECT statement it throws a spanner in the works throwing the error above.
I would be grateful if someone could advise why the other fields are working fine yet this one just causes problems.
Here is the relevant section of code. Line 17 is the bind_result call.
include 'connectvariables2.php';
$conn = new mysqli(DB_HOST, DB_USER, DB_PSWD, DB_NAME) or die("error");
$stmt = $conn->prepare("SELECT id, subject,section,topic,subtopic,title,publisher,authors,isbn13,isbn10,cdincluded,condition,notes FROM books ORDER BY id ASC");
var_dump($stmt);
$stmt->bind_result($id,$subject,$section,$topic,$subtopic,$title,$publisher,$authors,$isbn13,$isbn10,$cd,$cond,$notes);
$stmt->execute();
$stmt->store_result();
CONDITION is a reserved word in mysql, so you need to escape it using backicks:
$stmt = $conn->prepare("SELECT id, subject,section,topic,subtopic,title,publisher,authors,isbn13,isbn10,
cdincluded,`condition`,notes FROM books ORDER BY id ASC");
$stmt = $conn->prepare("SELECT id, subject,section,topic,subtopic,title,publisher,authors,isbn13,isbn10,cdincluded,‌​condition,notes FROM books ORDER BY id ASC"); var_dump($stmt);
$stmt->bind_result($id,$subject,$section,$topic,$subtopic,$title,$publisher,$au‌thors,$isbn13,$isbn10,$cd,$cond,$notes);
$stmt->execute();
$stmt->store_result();
The above is your current code which you have provided.. You are performing the correct steps to retrieve data from your database, but ordering your execution process wrong. You should read up the on the documents for how to correctly bind a result and store the results.. Here is what your execution process should look like:
$stmt = $conn->prepare("");
$stmt->execute();
$stmt->bind_result();
$stmt->fetch();
But you are trying to store the result, so replace $stmt->fetch() with
$stmt->store_result();
Stmt::prepare
stmt::execute
stmt::bind_result
stmt::fetch
stmt::store_result
Regarding your query when adding another referenced column.. condition is a reserved key word in mysql.. You need to escape it, so your query will be:
SELECT id, subject,section,topic,subtopic,title,publisher,authors,isbn13,isbn10,
cdincluded,`condition`,notes FROM books ORDER BY id ASC
I had the same problem. And reason was that my table doesn't contains column name which I specified in prepareQuery method.

Switch between multiple database in PDO

I'm new to PDO. I would like to know if there is anything similar to mysql_select_db in PDO, so that i can switch between different databases during runtime without the need for creating a new object.
I know that I am a couple of months late but you should be able to switch between databases from within your query.
examples:
$sql = "SELECT * FROM dbname.tablename";
$sql = "SELECT * FROM anotherdbname.anothertablename"
So even if your original $pdo object was used 'blahblah' as the dbname, you should still be okay based on the select examples I provided.
It looks like PDO does not have database switching because not every database engine supports it.
AFAIK PostgreSQL does not have database switching, but offer schemas and u can switch between those.
However if you're using mysql check if this works for you:
$pdo = new PDO('mysql:dbname=db1;host=127.0.0.1','user','pass');
$sql = 'select count(*) from table_name';
$res = $pdo->query($sql);
print_r($res->fetchAll());
$pdo->exec('USE db2');
$res = $pdo->query($sql);
print_r($res->fetchAll());
You actually do not need to specify the database upon connection at all. As long as you specify the database in every query, as Laz stated, this will work:
$dbh = new PDO('mysql:host=127.0.0.1','USER','PASS');
$query = "SELECT * FROM database1.table1";
$query = "SELECT * FROM database2.table1";
There is not, you will need to create two PDO objects for the separate connections if you would like to use both at runtime.
Edit: Interesting point by #laz below (which I'm guessing is the cause of negative votes on my answer). I was thinking under the assumption that the databases were on separate servers tbh, in which case my answer stands.
you don't even need to specify the database in every query, just use msyql syntax
USE db_name
and then write your requests
you can make this :
$database1 = new PDO("mysql:host=localhost;dbname=db1;charset=utf8;",$username, $password);
$database2 = new PDO("mysql:host=localhost;dbname=db2;charset=utf8;",$username, $password);
simple 😀

using codeigniter and need to get id of last auto-incremented id for next query, using oci8

Using codeigniter and oci8 for a project.
$this->db->insert_id(); would would perfect for getting the last auto-incremented id of the previous query, but it does not seem to work on an oracle database.
Any help is appreciated. I would LOVE to use mysql, but an oracle database is a requirement.
$this->db->insert_id(); for codeigniter, is just like php's mysql_insert_id()
See here:
Get the auto-generated ID after an insert
$data = array("value1","value2","value3");
$db = OCILogon("user","password");
$stmt = OCIParse($db,"insert into mytable values (myid.nextval,:myfield) returning id into :id");
OCIBindByName($stmt,":ID",$id,32);
OCIBindByName($stmt,":MYFIELD",$myfield,32);
while (list(,$myfield) = each($data)) {
OCIExecute($stmt);
echo "$myfieldgot id:$id\n";
}
You could also look at using a DB interface layer like PDO
How about getting the next sequence number?
SELECT ' || cTableName || '_seq.currval from dual
?

Categories