This is my first try to use SQLite, I am trying to retrieve data from SQLite but am not getting success neither its throwing any exceptions.
my respective code is as follows:
$sql_query = "SELECT * FROM `item` WHERE combo LIKE '" . $value . "' LIMIT 1;";
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:src/mydb.s3db");
foreach ($dbh->query($sql_query) as $row) {
$name = $row['name'];
echo "name".$name;
$style = $row['style'];
echo $style;
$appr = $row['appr'];
echo $appr;
$style = $row['style'];
echo $style;
}
} catch(PDOException $e) {
//echo $e -> getMessage();
echo "problem with DB";
echo "<br>";
}
Kindly guide me through this.
Thank you.
//phpnifo();
PDO
PDO support enabled |
PDO drivers mysql, sqlite, sqlite2
pdo_sqlite
PDO Driver for SQLite 3.x enabled |
PECL Module version (bundled) 1.0.1 $Id: pdo_sqlite.c 293036 2010-01-03 09:23:27Z sebastian $
SQLite Library 3.3.7
a) Tell PDO that you want it to use exceptions for reporting errors
$dbh = new PDO("sqlite::memory:");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
b) instead of putting the payload paraemters into the sql statement use prepared parametrized statements
try {
$stmt = $dbh->prepare( 'SELECT * FROM `item` WHERE combo LIKE ? LIMIT 1' );
$stmt->execute( array($value) );
foreach( $stmt as $row ) { ...
c) If you still don't get any output try code that unconditionally prints something. E.g. a SELECT Count(*) will always return at least one record (if no error occurs).
$stmt = $dbh->prepare( 'SELECT Count(*) as cnt FROM `item` WHERE combo LIKE ?' );
$stmt->execute( array($value) );
foreach( $stmt as $row ) {
echo 'Count: ', $row['cnt'], "\n";
}
$stmt = null;
edit: self-contained example
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
echo "start\n";
try {
$dbh = new PDO("sqlite::memory:");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($dbh);
$stmt = $dbh->prepare('SELECT * FROM item WHERE combo LIKE ? LIMIT 1');
$stmt->execute( array('comboB') );
foreach( $stmt as $row ) {
echo
$row['name'], " ",
$row['style'], " ",
$row['appr'], "\n"
;
}
}
catch(Exception $ex) {
var_dump($ex);
}
echo "done.\n";
function setup($dbh) {
$dbh->exec('
CREATE TABLE item (
combo TEXT,
name TEXT,
style TEXT,
appr TEXT
)
');
$stmt = $dbh->prepare('INSERT INTO item (combo,name,style,appr) VALUES (?,?,?,?)');
$stmt->execute( array('comboA','nameA','styleA','apprA') );
$stmt->execute( array('comboB','nameB','styleB','apprB') );
$stmt->execute( array('comboC','nameC','styleC','apprC') );
}
Related
I'am trying to perform simple SELECT query from PHP PDO to MSSQL database. While query contains cyrillic symbols in WHERE condition, result is empty (if not contains, result return successfully). What can I do to correct query?
putenv('ODBCSYSINI=/etc/');
putenv('ODBCINI=/etc/odbc.ini');
$configODBC = config('database.odbc');
try {
$this->pdo = new PDO('odbc:'. $configODBC['default']['source'], $configODBC['default']['username'], $configODBC['default']['password']);
} catch (PDOException $e) {}
...
$statement = $this->pdo->prepare("SELECT * FROM [DB].[dbo].table WHERE policy_num LIKE '%cyrillic_symbols%'");
$result = $statement->execute();
if ($result) {
while ($out = $statement->fetch()) {
var_dump($out[0]);
}
}
PS. MSSQL version 2012. Data in UTF-8 encoding.
I'll post this as an answer, because it's too long for comment. UTF-8 all the way through, suggested by #RiggsFolly has all the answers. In your case, you need to convert values from CP-1251 from/to UTF-8 . I've made this simple test case, see if this will help you:
T-SQL:
CREATE TABLE CyrillicTable (
[CyrillicText] varchar(200) COLLATE Cyrillic_General_CI_AS
)
INSERT INTO CyrillicTable
(CyrillicText)
VALUES
('Понедельник'),
('Вторник')
PHP (file is UTF-8 encoded, using Notepad++):
<?php
# Connection info
$hostname = 'server\instance,port';
$dbname = 'database';
$username = 'uid';
$pw = 'pwd';
# Connection
try {
$dbh = new PDO("odbc:Driver={SQL Server Native Client 11.0};Server=$hostname;Database=$dbname", $username, $pw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server. ".$e->getMessage());
}
# Query
try {
echo "Query"."<br>";
$sql = "SELECT * FROM dbo.[CyrillicTable] WHERE CyrillicText LIKE '%".iconv('UTF-8', 'CP1251', 'онед')."%'";
$stmt = $dbh->query($sql);
while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {
foreach($row as $name => $value) {
echo $name.": ".iconv('CP1251', 'UTF-8', $value)."<br>";
}
}
echo "<br>";
} catch( PDOException $e ) {
die( "Error executing query: ".$e->getMessage());
}
$stmt = null;
# Query
try {
echo "Prepared query"."<br>";
$sql = "SELECT * FROM dbo.[CyrillicTable] WHERE CyrillicText LIKE ?";
$stmt = $dbh->prepare($sql);
$text = 'орни';
$text = "%$text%";
$text = iconv('UTF-8', 'CP1251', $text);
$stmt->bindParam(1, $text, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {
foreach($row as $name => $value) {
echo $name.": ".iconv('CP1251', 'UTF-8', $value)."<br>";
}
}
echo "<br>";
} catch( PDOException $e ) {
die( "Error executing stored procedure: ".$e->getMessage());
}
$stmt = null;
# End
$dbh = null;
?>
Notes:
Consider using parameterized query.
I want to insert some base64 encoded data (up to 500.000 characters per field) in an Oracle DB.
Since i havn't used Oracle with PHP before i started using PDO and set fields to CLOB.
Shortversion of my code (class Db extends \PDO):
<?php
[..snip..]
$dbh = new Db( "oci:dbname=" . DB_TNS, DB_USER, DB_PASS );
$Query = ' INSERT INTO "SENTINEL"."SYSTEM_ERRORS"
( BACKTRACE )
VALUES
( :backtrace )
';
$stmt = $dbh->db_prepare( $Query );
$stmt->bindParam( ':backtrace', $backtrace, \PDO::PARAM_LOB );
$backtrace = $someobject->get_backtrace();
$stmt->execute();
print_r($stmt->errorInfo());
$stmt->closeCursor();
I get:
Array ( [0] => HY000 [1] => 932 [2] => OCIStmtExecute: ORA-00932: Inkonsistente Datentypen: CLOB erwartet, BLOB erhalten (ext\pdo_oci\oci_statement.c:148) )
Anyone know how to solve that with PDO, so i don't have to use the oci driver?
I have found a solution here:
https://bugs.php.net/bug.php?id=57095
[2009-08-11 11:27 UTC] lehresman at gmail dot com
wrote:
A coworker discovered the solution. When dealing with CLOBs in Oracle using PDO,
don't treat it as a LOB. You need to bind it as a PDO::PARAM_STR, and give it the
length of the string (that 4th parameter is the key, it fails with an error message
about LONG type otherwise).
Here is an example of how to successfully insert into a CLOB in Oracle:
<?php
/*
CREATE TABLE clob_test (my_clob CLOB)
*/
$big_string = "";
for ($i=0; $i < 10000; $i++)
$big_string .= rand(100000,999999)."\n";
try {
$pdo = new PDO("oci:dbname=TESTDB", "TESTUSER", "TESTPW");
$stmt = $pdo->prepare("INSERT INTO healthbit.clob_test (my_clob) VALUES (:cl)");
$stmt->bindParam(":cl", $big_string, PDO::PARAM_STR, strlen($big_string));
$pdo->beginTransaction();
if (!$stmt->execute()) {
echo "ERROR: ".print_r($stmt->errorInfo())."\n";
$pdo->rollBack();
exit;
}
$pdo->commit();
$stmt = $pdo->prepare("SELECT my_clob FROM healthbit.clob_test");
$stmt->execute();
$row = $stmt->fetch();
$str = "";
while ($tmp = fread($row[0],1024))
$str .= $tmp;
echo strlen($str); // prints 70000
} catch (Exception $e) {
echo "ERROR: ";
echo $e->getMessage();
$pdo->rollBack();
}
Works perfectly fine for me...
I am using the following code for reading a String from a mysql function:
<?php
print_r($_POST);
try {
$dbh = new PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
print $value ;
//print $dbh ;
$stmt = $dbh->prepare("CALL check_user_exists(?)");
$stmt->bindParam(1, $value, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 50);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
echo "PDO connection object created";
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
This is not reading the returned value , however if I read the value usimg mysql* like :
<?php
$dbhost='myhost';
$dbuser='mydb';
$dbpassword='mypass';
$db='mydb';
$con=mysql_connect($dbhost, $dbuser, $dbpassword) or die("Could not connect: " . mysql_error()); ;
mysql_select_db($db,$con);
$qry_str = "select check_user_exists('chadhass#hotmail.com')";
$rset = mysql_query($qry_str) or exit(mysql_error());
$row = mysql_fetch_assoc($rset);
mysql_close($con);
foreach($row as $k=>$v)
{
print $k.'=>'.$v;
}
?>
This returns correctly . ANy idea wha am I missing ?
function :
CREATE
FUNCTION `check_user_exists`(in_email
VARCHAR(100)) RETURNS varchar(1) CHARSET utf8
READS SQL DATA
BEGIN
DECLARE vcount INT;
DECLARE vcount1 INT;
SELECT COUNT(*) INTO vcount FROM USERS
WHERE USEREMAIL=in_email;
IF vcount=1 then
SELECT COUNT(*) INTO vcount1 FROM USERS
WHERE USEREMAIL=in_email and isactive=1;
if vcount1=1 then
return('1');
else
return('0');
end if;
ELSE
RETURN('2');
END IF;
END
code that worked for PDO ::
<?php
//print_r($_POST);
try {
$dbh = new PDO(PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
$result = $dbh->prepare("select check_user_exists(?) as retval");
$result->bindParam(1, $value, PDO::PARAM_STR, 2);
$result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
$result->execute();
$obj = $result->fetch();
print($obj->retval);
echo "PDO connection object created";
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
The reason is, you aren't fetching the results from the query.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
I am using SQLite for one of my application I’ve a condition that I first run a query and if it returns result then I retrieve its data but if the first query doesn’t return anything I want to run another query that ll just select any random row from the database and ll return the results.
I’ve devised following code its working fine if it matches the data in the first case but this is not working for the second case.
$sql_query = "SELECT (select count(*)) as count,* FROM item WHERE combo LIKE '%" . $ans_combo . "%' LIMIT 1;";
$sql_query_bu = "SELECT * FROM item ORDER BY RANDOM() LIMIT 1;";
ini_set('display_errors', true);
error_reporting(E_ALL);
try {
$dbh = new PDO("sqlite:src/appdb.s3db");
$dbh -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $dbh -> prepare($sql_query);
$stmt -> execute();
foreach ($stmt as $row) {
if ($row['count'] != '1') {
echo $sql_query_bu . "<br/>";
$stmt = $dbh -> prepare($sql_query_bu);
$stmt -> execute();
foreach ($stmt as $row) {
echo $row['name'], " ", $row['name'], " ", $row['name'], "\n";
}
}
echo "Count: " . $row['count'];
echo $row['name'], " ", $row['name'], " ", $row['name'], "\n";
}
} catch(Exception $ex) {
var_dump($ex);
}
unset($dbh);
unset($stmt);
Kindly guide me through this.
Thank you.
If there is no record that matches the WHERE clause the first call to fetch() will return FALSE. In that case you can simply send the ORDER BY RANDOM()* query and fetch the first record.
self-contained example:
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);
$stmt = $pdo->prepare('SELECT * FROM soFoo WHERE combo=? LIMIT 1');
$stmt->execute( array('comboF') ) ;
$row = $stmt->fetch();
$stmt = null;
if ( !$row ) {
$row = $pdo->query('SELECT * FROM soFoo ORDER BY RANDOM() LIMIT 1')->fetch();
}
var_dump($row);
function setup($pdo) {
$pdo->exec('
CREATE TABLE soFoo (
combo TEXT,
x TEXT
)
');
$stmt = $pdo->prepare('INSERT INTO soFoo (combo,x) VALUES (?,?)');
$stmt->execute( array('comboA','A') );
$stmt->execute( array('comboB','B') );
$stmt->execute( array('comboC','C') );
$stmt->execute( array('comboD','D') );
}
(*) ORDER BY RANDOM() is e.g. in MySQL rather costly. I doubt that SQLite has a special routine for this case. Better search for a good alternative for ORDER BY RANDOM()