Detecting error/invalid/illegal queries using PDO driver (MySQL + PHP) - mysql

I just changed all my code from the old mysql driver to PDO.
So far I find that a lot of basic functionalities doesn't exist! Ex. no equivalency to mysql_num_row .. and so on (but that's not the point of this post :/ )
Usually with mysql driver, I'd do:
$result = mysql_query($query);
if(!$result){
displayError(mysql_error());
}
How do you do similar thing using PDO?

Have a look at the documentation here there are 3 modes :
PDO::ERRMODE_SILENT (default)
PDO::ERRMODE_WARNING
PDO::ERRMODE_EXCEPTION
I suggest you enable the last, which causes an exception to be thrown on error :
$pdo = new PDO($dsn,$user,$pass,$options); // Example connection
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
then surround your statement in a try/catch block
try {
// your query here
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
Separate note - mysql_num_row in PDO :
$sql = "SELECT count(*) FROM `table` WHERE x = y";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn()

Use try { } catch {}
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Reference

Related

How to forward a connection failed MySQL to a error page (500)

We made a simple php webpage with a InnoDB tabel, to monitor if InnoDB goes down.
When InnoDB / Mysql goes down we get a error: Connection failed: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory")
But we wanna forward this to a custom error. Lik: InnoDB IS DOWN!!!
Any suggestions how we can do this?
<?php
$servername = "localhost";
$username = "root";
$password = "**************";
$dbname = "innodb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT status FROM monitoring";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "De status van InnoDB is: " . $row["status"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
It's simple, use something like this
<?php
// Configuration of database
// Check connection
if ($conn->connect_error) {
// die("InnoDB IS DOWN");
// OR
echo "<p>InnoDB IS DOWN</p>";
exit();
}
// Rest of your code
OR you may include an HTML page as well in the IF condition if ($conn->connect_error) like:
// Check connection
if ($conn->connect_error) {
include 'error_page.html';
exit();
}
// Rest of your code

getting error back from Prepared statement in case sql injection

I'm trying to test my prepared statement that is protecting one field to get the error message in case of SQL injection. I tried until now thousands of attacks, and all of the values I gave were accepted. Am I using a wrong syntax or attack? I can't see where the problem is. Here is my code:
try {
// $host = "localhost";
// $username = "root";
// $password = "root";
// $db_name = "pokemon";
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.';', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$meldung="";
$name =$_REQUEST['name'];
$gewicht = $_REQUEST['Gewicht'];
$größe =$_REQUEST['Größe'];
$spezies = $_REQUEST['Spezies'];
$stufe =$_REQUEST['Stufe'];
$atacke =$_REQUEST['Attacke'];
$array = explode(',', $_REQUEST['Attacke']);
$stmt = $conn->prepare("INSERT INTO Pokemon (`Name`,`Gewicht`,`grosse`,`spezies`,`stufe`) VALUES (:Name, '".$gewicht."', '".$größe."', '".$spezies."', '".$stufe."')");
$stmt->bindParam(':Name', $name);
// $stmt->bindParam(':Gewicht', $gewicht);
// $stmt->bindParam(':grosse', $größe);
// $stmt->bindParam(':spezies', $spezies);
// $stmt->bindParam(':stufe', $stufe);
$stmt->execute();
}
catch(PDOException $e)
{
$meldung = "Error: " . $e->getMessage();
echo $meldung;
}
thanks

Preparing simple query for PDO connection

I would like to prepare PDO statement and convert results to JSON in PHP. I managed to connect to database by following method:
class DB_CONNECT {
function __construct() {
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
$root = getenv("DOCUMENT_ROOT");
require_once ($root.'/db/db_config.php');
try
{
$db = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_DATABASE.';charset=utf8;port='.DB_PORT, DB_USER, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'OK';
return $db;
}
catch (PDOException $e)
{
print "Connection error!: " . $e->getMessage() . "<br/>";
die();
}
}
function close() {
$db = null;
}
PHP, where I make statements looks like this:
$root = getenv("DOCUMENT_ROOT");
require_once ($root.'/db/db_connect.php');
$db = new DB_CONNECT();
$statement=$db->prepare("SELECT name, surname FROM lecturer");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
When I run this PHP, I'm getting only OK message, that the connection went successfully. What's wrong with that query code?
What does your error log say? From your code, I can tell you that $db doesn't contain a PDO object, as you don't return anything in the constructor of DB_CONNECT. So $db is an object of type DB_CONNECT, not of type PDO, and thus doesn't have prepare as a method.
For a quick fix, change
$db = new DB_CONNECT();
to
$db = DB_CONNECT::connect();
and make connect static.

Cannot connect to MySQL

I am trying to connect to MySQL server (hosted by godaddy) from php using PDO.
But I get this error :
An error occured : SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Note that this is not a database I host.
I was simply given the username and password to construct the database, create the users etc.
function ConnectToDb()
{
try{
$dns = 'mysql:host=1.1.1.1;dbname=dummyDbName';
$username = 'dummyUser';
$password = 'dummyPassword';
$LINK = new PDO($dns, $username, $password);
$LINK->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$LINK->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$LINK){
die('Could not connect : ' .mysql_error());
}
else{
return $LINK;
}
} catch (PDOException $ex){
echo "An error occured : " .$ex->getMessage();
}
}
I know that this works on localhost.
I'm using it no problem, but as soon as I try to connect to the live database it fails.
Anyone has an hint?
Thanks
Follow this format:
$user = "username";
$pass = "password";
$host = "localhost";
$db = "yourDbname";
$dns = "mysql:host=" . $host . ";dbname=" . $db;
$dbh = new PDO($dns, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
when you have to do a query (just an example):
$theid = 10;
$statement = $dbh->prepare('SELECT * FROM yourtable WHERE id = ? and name = ?');
$statement->execute(array($theid,'baronth'));
if you want to see if there's some errors while connecting or doing queryes (and you know how try-catch works), surround it with:
try {
all the code that you wan't to check
}
catch (PDOException $e) {
echo $e->getMessage();
}
it will echo the error.

MySQL & PDO : about efficiency

I have the following code :
<?php
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=*****;dbname=****", "****", "*****");
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
# statement handle (prevents injection)
$STH = $DBH->prepare("SELECT Adresse FROM Agences");
$STH->execute();
# statement handle (prevents injection)
$STHNAMES = $DBH->prepare("SELECT `numero-agence` FROM Agences");
$STHNAMES->execute();
$storeArray = Array();
$nameArray = Array();
while ($row = $STH->fetch()) {
$storeArray[] = $row['Adresse'];
}
while ($row = $STHNAMES->fetch()) {
$nameArray[] = $row['numero-agence'];
}
echo json_encode(
Array("theAddress" => $storeArray,
"theName" => $nameArray)
);
}
catch(PDOException $e) {
echo 'There was an issue inserting thing into database: '.$e->getMessage();
}
?>
My question is : is there a way to combine the two queries and still have an associative array to send back to the client JSON-encoded ? (I am querying this bit of PHP with an ajax call, and need the resulting data)
Thanks.
Can be done in the same query:
# statement handle (prevents injection)
$STH = $DBH->prepare("SELECT Adresse, `numero-agence` FROM Agences");
$STH->execute();
$storeArray = Array();
$nameArray = Array();
while ($row = $STH->fetch()) {
$storeArray[] = $row['Adresse'];
$nameArray[] = $row['numero-agence'];
}