Sqlite PDO query returns no results - php

Getting no results no matter how broad my query
PHP: 5.3
Sqlite3: 3.6
PDO: 5.3.3
I would think this should be a very simple process but even looking around I still don't know why I'm getting 0 results. Here is my code:
<?php
$sqlite = new PDO('sqlite:/example.db');
$result = $sqlite->query('SELECT * from foo');
if(!$result)
{
echo 'fail';
return false;
}
?>
Any ideas on what I am doing wrong? The 'foo' table will only have four columns, and this test db only has one table. Running the query in sqlite displays the results fine.

You have to execute the statement first than fetch the result.
You might add try/catch block around the execute method call. and do some error handling.
Here's an example of catching an Exception. Do not use it as a design guideline.
<?php
try
{
$sqlite = new PDO('sqlite:/example.db');
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$statement = $sqlite->prepare('SELECT * from foo');
try
{
$statement->execute();
}
catch(PDOException $e)
{
echo "Statement failed: " . $e->getMessage();
return false;
}
$result = $statement->fetchAll();
var_dump($result);
?>

Related

Getting "SQLSTATE[HY000]: General error" when running my PHP app

Good day!
I am working on building a dummy application form that inserts data to a mySQL database. When running the functions, I successfully insert the data into the database. However, when the functions worked successfully, I am getting an error SQLSTATE[HY000]: General error
I thought it was occurring within my database access function, but it seems to be connecting alright. Here is my db access function:
function connectToDB($params)
{
try
{
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare($params['sql']);
$stmt->execute($params['bindParam']);
$results = array();
$results['rowCount'] = $stmt->rowCount();
if($results['rowCount'] == 1)
{
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] < 2) {
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] > 2) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] == 2) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $params;
}
Is there something I am missing in my code or is there something that shouldn't be in my db access code? I hope to learn from this to apply it in the future while I'm still trying to learn/improve on my PHP along the way. I hope I did my best to explain my issue and I appreciate your time reading!
Thank you
You do not use fetchAll().
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
with insert queries. Removing this statement it should fix your problem. Remember every fetch and fetchAll from your code.

How to execute multiple queries using PDO for Sql Server

I'd like to execute some queries that doesn't return result set, and then execute a real query, and fetch its result.
Here is an exemple that doesn't work :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1;";
$db->exec($query);
$query = "select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
This code neither doesn't work :
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1; select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
But this code works :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "select 1;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
Thanks for your help
I know this is old, but for other people finding this from Google: you need to use PDOStatement::nextRowset to iterate over the result sets from your multiple queries.
However, it seems there are memory issues when using nextRowset with dblib in some versions (it tried to allocate 94Tb in my case...), so I ended up re-engineering to avoid multiple SQL queries altogether (instead duplicating the value of the DECLARE where it was being used).
PDO::query docs (http://php.net/manual/it/pdo.query.php) say
PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
This could mean that you can execute with query() both queries with and without result

Amfphp Service Browser Not Displaying MySQL Result

I am developing my first project using Amfphp and am writing my first simple Service. Here is my getData method:
public function getData() {
// Connect to the database using PHP Data Objects (PDO).
try {
$pdo = new PDO('mysql:host=localhost;port=8889;dbname=amf_test', 'root', 'root');
} catch (PDOException $e) {
print "Connection Error!: " . $e->getMessage() . "<br/>";
die();
}
// Set an Error Handling mode.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully\n";
// Retrieve all rows.
$tsql = 'SELECT * FROM authors_aut';
$stmt = $pdo->prepare($tsql);
$stmt->execute();
// Echo the SQL Error Code
echo "SQL Error code: " . $pdo->errorCode() . "\n";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$row_count = $stmt->rowCount();
echo $row_count.' rows selected' . "\n";
foreach ($pdo->query($tsql) AS $row) {
$id_aut = $row['id_aut'];
$fname_aut = $row['fname_aut'];
printf("Data: %s (%s) <br />", $id_aut, $fname_aut);
}
// Close the database connection
$stmt = null;
$dbh = null;
// Return the array.
return $results;
}
When I go to the Amfphp Back Office Service Browser, select my getData method and call it I get my comments but no data. Before I added my echo and printf lines I didn't the Service Browser returned nothing leaving me thinking my Service was not working (it still may not be!). My comments appear to show that I have successfully selected the data from the MySQL database but is it being returned?
I welcome your thoughts.
Chris

How to select Oracle DB sdo_geometry in php

My server is nginx and I use adodb5 to manage the connexion to the Oracle DB.
This db query returns rows in a SQL software like SQLDevelopper but I don't know how to make it work in my case.
$sql = "SELECT geom_object FROM geom_table";
Whereas this other request works :
$sql = "SELECT id FROM geom_table";
My connecting code is correct because all my queries return some data, except those involving SDO_GEOMETRY.
include ("adodb5/adodb-exceptions.inc.php");
include ("adodb5/adodb-errorhandler.inc.php");
include ("adodb5/adodb.inc.php");
try {
$db = NewADOConnection("oci8");
$db->Connect($sid, $user, $password);
$db->SetFetchMode(ADODB_FETCH_ASSOC);
} catch (exception $e) {
var_dump($e);
adodb_backtrace($e->gettrace());
exit;
}
try
{
$ret = $db->GetArray($sql);
print count($ret);
}
catch (exception $e)
{
print $e->msg;
exit;
}
The MDSYS.SDO_GEOMTRY field can not be hanlded as it is in PHP.
First I needed to modify my SQL request to return a Well Known Text :
$sql = "SELECT sdo_util.to_wktgeometry(geom_object) FROM geom_table";
Reading the Oracle Documentation on SDO_UTIL we can see that the TO_WKTGEOMETRY return a CLOB.
PHP can still not read the value of the data. There's one more important step, reading the CLOB.
The Php documentation about OCI-Lob informs us that there are two functions able to read a CLOB and return a string : load and read.
$conn = oci_connect($user_prospect, $password_prospect, $sid_prospect);
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (($row = oci_fetch_array($stid)) != false) {
echo $row[column_of_geometry_object]->load();
}
oci_free_statement($stid);
oci_close($conn);

I want to get the exact message out of this error

I understand I have to include mysql_errno y mysql_error here somewhere instead of 'Query Failed' and I tried with $results as an argument but i have not found out how.
If someone can help me out, thanks:
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;
}
Model::closeConnection($db);
return $lastid;
}
throw new Exception(mysql_error(), EX_QUERY_FAILED);

Categories