DEBUG PDO Connection & PHP Output - php

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

Related

Why doesn't the Insert work for me in SQLITE3?

when executing the form, the data is not inserting. I have activated SQLITE3 and I am not skipping any type of error.
The echo of the try is to see what was wrong but nothing. I see everything right.
Does anyone help me?
$username = $_POST['nombre'];
$clave = $_POST['clave'];
$apenom = $_POST['apenom'];
try {
$bd = new SQLite3("test");
//preparamos la sentencia
echo "INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')";
$bd->exec("INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')");
/* while ($row = $resultado->fetchArray()) {
echo "{$row['username']} {$row['clave']} {$row['apenom']} \n";
} */
} catch (\Throwable $th) {
echo $th;
}
Do take the advice from the comments into account, database security is not something you should 'wing'...
As for a little help on setting up a connection and importantly debugging if anything goes wrong so you know what to fix, the following 'skeleton' might help:
<?php
try {
// connect to your database
$sqlite = new SQLite3('test.db');
}
catch (Exception $e) {
// if no connection could be established a exception is thrown
echo $e->getMessage();
}
// your query
$query = '...';
$result = $sqlite->query($query); // result object (FALSE on error)
if (!$result) {
// query failed for some reason...
echo $sqlite->lastErrorMsg();
} else {
// do something with result
}

PHP rollback method has failed

I have tried this piece of code and unfortunately rollback method failed!
Thank in advance!!
$bash = new mysqli('localhost', 'root', '','dbastegoi');
$bash->autocommit(FALSE);
echo 'timologio';
$r =$bash->query("INSERT INTO tbparastatika (strArithmos, fkERGO, strPROMITH, sngCOST, intTYPOS, intDRASH) VALUES ('1','1001','123123123',800138,1,1)");
//ΕΙΣΑΓΩΓΗ ΤΙΜΟΛΟΓΙΟΥ
$i = $bash->insert_id;
ECHO PHP_EOL;
echo 'dapanh';
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
} catch (Exception $e) {
echo 'error2';
}
$bash->commit();
$bash->rollback();
//$SYNDESH->commit();
//$SYNDESH->rollback();
$bash->close();
You can not make a commit first and then a roolback. You have to make a commit if your query runs without error or make a rollback if you get an error:
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
$bash->commit();
} catch (Exception $e) {
echo 'error2';
$bash->rollback();
}

PHP: creating 2 PDOs for 2 different DBs, one blocks the second one

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 :)

Crate/PDO Usage Examples

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;
}
?>

How to Conditionally Retrieve Rows from the Database in PHP?

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.

Categories