Has anyone successfully installed Crate/PDO.
I seem to be banging my head against this one.
I have used composer to create the json file and when i try to
<?php
require 'vendor/autoload.php';
try {
$dbh = new PDO('crate:localhost:4200');
foreach($dbh->query('SELECT * from testtable') as $row) {
print_r($row);
}
$dbh = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
It comes up with error Could not find driver.
Any help or installation documents would be great. anyone got any example code working.
The Crate PDO adapter is not official supported and included by PHP PDO, so the Crate PDO class must be used instead of the standard PDO class.
You should either import the Crate\PDO\PDO class by use Crate\PDO\PDO;
or use a full qualified classname:
<?php
require 'vendor/autoload.php';
try {
$dbh = new \Crate\PDO\PDO('crate:localhost:4200', null, null, []);
foreach($dbh->query('SELECT * from testtable') as $row) {
print_r($row);
}
$dbh = null;
}
Just do it this way and you will be okay. Give me a shout if you needs more help.... Sectona
pdo_connect.php
<?php
$db = new PDO (
'mysql:host=localhost;dbname=sectona_db;charset=utf8',
'root', // username
'root6a' // password
);
?>
<?php
require("pdo_connect.php");
$result = $db->prepare('SELECT table_data,table_name FROM testable');
$result->execute(array(
'
));
while ($row = $result->fetch()) {
$tb1=htmlentities($row['table_data'], ENT_QUOTES, "UTF-8");
$tb2=$pid=htmlentities($row['table_name'], ENT_QUOTES, "UTF-8");
echo $tb1;
echo $tb2;
}
?>
Related
I'm using PDO to query some data from my database but I have a section with raw php code that doesn't show up, only in the source as if it's trying to run.
I have the slashes stripped and I have it echoed under pre/code tags so I'm wondering as to why it won't show on the page.
Database
id name(VARCHAR) code (LONGTEXT)
1 test <?php echo /'hello world/'; ?>
PHP File
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=$dbname;charset=utf8', '$username', '$password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare('SELECT name, codeOne FROM table_one WHERE id = :id');
$stmt->bindParam(':id', '1');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'] . '<pre><code>'. stripslashes($row['codeOne']) .'</code></pre>';
}
} catch(PDOException $e) {
return $e->getMessage();
};
?>
What Everyone Sees
test
View Source
test<pre><code><?php echo "Hello";?></code></pre>
Well just use htmlspecialchars() to encode your string, e.g.
echo htmlspecialchars('<?php echo "Hello";?>');
What you see:
<?php echo "Hello";?>
Source code:
<?php echo "Hello";?>
OR if you want to be really fancy you could use: highlight_string(), which also gives some nice color to your string:
echo highlight_string('<?php echo "Hello";?>', TRUE);
I have 2 DBs: 1 in MySQL and the other one on SQLite3.
I need to insert the same data into both. To achieve this by a Form, I'm making a PHP script, that has some issue.
Here below the code then the explanation on what's going on:
// MySQL
try {
$sql = new PDO($pdo_servername, $username, $password, $pdo_options);
$sql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$ret = $sql->exec($query);
if(!$ret){
echo $sql->lastErrorMsg();
} else {
echo "New record created successfully on MySQL DB";
}
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$sql->close();
// SQLite
try {
$sqlite = new PDO($pdo_servername_sqlite3);
$sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$retlite = $sqlite->exec($query);
if(!$retlite){
echo $sqlite->lastErrorMsg();
} else {
echo "New record created successfully on SQLite3 DB";
}
} catch (PDOException $e) {
echo $sqlite . "<br>" . $e->getMessage();
}
$sqlite->close();
The MySQL works fine, while the SQLite3 doesn't even start.
Inverting the blocks, thus first SQLite3 then MySQL, the issue is inverted: the SQLite3 works fine and MySQL doesn't start.
I have not any error returned
I tried also to avoid any try-catch-finally, and I just wrote the code as simple it is, and I got the same identical situation.
Is it forbidden to open 2 PDO connections, to 2 different DBs?
Where is my mistake please?
Try this way, that is the only breakpoint where you really need try...catch:
// MySQL
try {
$sql = new PDO($pdo_servername, $username, $password, $pdo_options);
} catch (PDOException $e) {
echo 'MySQL connection failed: ' . "<br>" . $e->getMessage();
$sql = false;
}
// SQLite
try {
$sqlite = new PDO($pdo_servername_sqlite3);
} catch (PDOException $e) {
echo 'SQLite connection failed: '. "<br>" . $e->getMessage();
$sqlite = false;
}
if ($sql != false) {
$ret = $sql->exec($query);
if(!$ret){
echo $sql->lastErrorMsg();
} else {
echo "New record created successfully on MySQL DB";
}
$sql->close();
}
if ($sqlite != false) {
$retlite = $sqlite->exec($query);
if(!$retlite){
echo $sqlite->lastErrorMsg();
} else {
echo "New record created successfully on SQLite3 DB";
}
$sqlite->close();
}
First of all I want to thank everybody contributed here :)
I would like to post the definitive working code, because some line, should also be changed, respect the above code.
Indeed the PDO method lastErrorMsg(); seems don't exist, and the same for the PDO method close(); It should be used errorInfo()in place of lastErrorMsg();and it's an array. While to close the DB connection: I read somewhere here on Stackoverflow that when the script execution ends, automatically PDO closes it, OR you need to destroy the object assign a null.
Because finally the code suggested by #Alex, with these small changes, was working, I was able to get the errors from PHP highlighting the above details.
Please here below the final working code, hoping that can be useful to any other had my same issue:
/**
* MySQL - try to open it. If it fails,
* it returns which error and continues the execution of the script
*/
try {
$sql = new PDO($pdo_servername, $username, $password, $pdo_options);
} catch (PDOException $e) {
echo 'MySQL connection failed: ' . "<br>" . $e->getMessage();
$sql = false;
}
/**
* SQLite - try to open it. If it fails,
* it returns which error and continues the execution of the script
*/
try {
$sqlite = new PDO($pdo_servername_sqlite3);
} catch (PDOException $e) {
echo 'SQLite connection failed: '. "<br>" . $e->getMessage();
$sqlite = false;
}
/**
* If the connection is made, it executes the Query
* If anything wrong with the Query insertion, an error is returned.
* The script continues
*/
if ($sql != false) {
$ret = $sql->exec($query);
if(!$ret){
print_r($sql->errorInfo()); // THIS is the valid method for PDO Exec and returns an array
} else {
echo "New record created successfully on MySQL DB";
}
}
if ($sqlite != false) {
$retlite = $sqlite->exec($query);
if(!$retlite){
print_r($sqlite->errorInfo()); // THIS is the valid method for PDO Exec and returns an array
} else {
echo "New record created successfully on SQLite3 DB";
}
}
/**
* Closes the DB Connections
*/
$sql = null;
$sqlite = null;
Thanks to all of you for your valid help. I very much appreciated it :)
This code works 100% but when I try to use JSON it does not display any data.
The problem is that I am trying to change all my codes to PDO since I was told that mysql_* function's are depreciated.
<?php
$con = new PDO('mysql:host=localhost;dbname=adnan;charset=UTF-8','root','');
$sql= $con->query('select * from adnan_user');
while($row =$sql->fetch()){
echo $row['user_id'],"\n";
}
?>
Here is the code which I call in json : its also works when I use mysql_ function
But with pdo it does not work .
<?php
$con = new PDO('mysql:host=localhost;dbname=adnan;charset=UTF-8','root','');
$sql= $con->query('select * from adnan_user');
while($row =$sql->fetch()){
$name = $row['name'];
$user= $row['user'];
}
// The JSON standard MIME header.
header('Content-type: application/json');
$array = array('name'=>$name, 'user'=>$user);
echo json_encode($array);
?>
The code for json
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$.getJSON('json.php', function(data) {
$('#myJson').html('<table style="color:red"><tr><td>' + data.name + '</td><td>' + data.user + '</td></tr></table>');
});
});
</script>
</head>
<body>
<div id="myJson"></div>
</body>
</html>
Your DSN in new PDO(...) is wrong, because in MySQL the UTF-8 charset is called utf8:
$con = new PDO('mysql:host=localhost;dbname=adnan;charset=utf8','root','');
See here for more information: http://php.net/manual/en/mysqlinfo.concepts.charset.php
Also you should catch exceptions, so PDO can tell you what's wrong next time:
try {
$con = new PDO(...);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
This will work, but in this case you only get the last record from your database. Why you have * in your sql? If you need all records you need to change the logic in your code.
<?php
$db = new PDO('mysql:host=localhost;dbname=core', 'root', '');
$db->exec("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
$sql = "select * from adnan_user";
$result = $db->prepare($sql);
$result->execute();
$array = array();
while($row = $result->fetch()){
$name = $row['name'];
$user = $row['user'];
}
$array['name'] = $user;
$array['user'] = $name;
header('Content-type: application/json');
echo json_encode($array);
?>
I am trying to connect to mySQL using PDO.
Please forgive me if I have made a glaring error - I am just learining...
<?php
try {
$db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$stmt = $db_conn->query('SELECT * FROM PRODUCTS');
while ($row = $stmt->fetch() ) {
echo '<pre>'; print_r($row); echo '<pre>';
}
?>
the output from the browser is as follows:
query('SELECT * FROM PRODUCTS'); while ($row = $stmt->fetch() ) { echo '
'; print_r($row); echo '
';
}
?>
What have I done wrong??? why is PHP not parsing the PHP script?
UPDATE:
If I create a new php file, and run phpinfo(); it works.
If I paste phpinfo() into the top of the above code as follows:
<?php
phpinfo();
echo '<h1>PDO TEST</h1>';
try {
$db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$stmt = $db_conn->query('SELECT * FROM Products');
while ($row = $stmt->fetch() ) {
echo '<pre>'; print_r($row); echo '<pre>';
}
?>
I get the following output:
PDO TEST'; try { $db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass'); } catch (PDOException $e) { echo 'Could not connect to database'; } $stmt = $db_conn->query('SELECT * FROM Products'); while ($row = $stmt->fetch() ) { echo '
'; print_r($row); echo '
';
}
?>
UPDATE:
Problem solved... It was some kind of file encoding issue. It works perfectly when I copy and paste the code into a new file. Very strange.
Open httpd.conf file and Add this line inside :
AddType application/x-httpd-php .php .phtml
This makes your PHP script execute by PHP interpreter.
Then restart apache server using /etc/init.d/apache2 or httpd restart
Ok, I have a database full of values with one field value for prospects and another for clients...
I'd like to retrieve only the clients information...
How do I write the function???
UPDATE
Here is the script I tried to write:
<?php
try {
$sql = "SELECT * FROM clients" // WHERE history" or die(mysql_error());
foreach ($dbh->query($sql) as $row) {
$row['history'] = $value;
if ($value == 'clients'){
echo "1212";
} else {
echo "Failed";
return;
}
}
$dbh = null;
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
$dbh->rollback();
}
?>
There's no reason to do a rollback here, especially since you haven't started a transaction, and this is just a SELECT, so there's nothing to rollback ... I'm also not sure why you're nulling out $dbh. It's possible to reuse $dbh for other queries, or throughout your application...
Also, your select statement should reflect what data you actually need. If all you need is history, then SELECT history FROM clients[...] is best.
<?php
try {
$sql = "SELECT * FROM clients WHERE history = 'clients'";
$query = $dbh->prepare($sql);
$query->execute();
while($row = $query->fetch())
{
if($row['history'] == 'clients'){
echo '1212';
}
}
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
}
?>
Based on your sample script this would do the same but it would place the conditional operator in the query at the database layer instead of within the script at the application layer:
<?php
try {
$sql = "SELECT * FROM clients WHERE history = 'clients'" // WHERE history" or die(mysql_error());
foreach ($dbh->query($sql) as $row) {
echo "1212";
}
$dbh = null;
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
$dbh->rollback();
}
?>
Of course, it obviously won't reflect non-client rows like your sample did, but from what I could understand of your question this was what you actually wanted to have happen.