//this is my connection function. It is connecting databse successfully when I check.
$conn = connection($config['servername'],$config['username'],$config['password']);
after this I Used following code to fetch data from Database
$id = 2;
if($conn) {
try {
$stmt = $conn->prepare('SELECT * FROM customer_tbl WHERE cus_id = :id');
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->bindParam(':id', $id);
$results = $stmt->execute();
}catch (PDOException $e){
echo 'Error: ' . $e->getMessage();
}
}
this code showing following error message on the browser
Error: SQLSTATE[IM001]: Driver does not support this function: This driver doesn't support setting attributes
what's wrong with my code?. Why I could not fetch data's from database?
if I want to fetch this specified data from databese using prepare statement
how to code?
Add the following
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
after the connection string with $conn Object
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
To fetch data use
$stmt->execute();
$rows= $stmt->fetch(PDO::FETCH_ASSOC);
print_r($rows); // to print an array
it will return data in associative array format.
PDO provides various fetch options look here
Related
Update query is not reflected into database . This is related to PHP and PDO method of connection. The query I have written is ,
try {
$conn = new PDO('mysql:host=localhost;dbname=***; charset=utf8','root','****[enter image description here][1]');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM providers WHERE password = '$oldpass'";
$statement = $conn->prepare($sql);
$statement->execute();
$providers = $statement->fetchAll();
if(($providers[0]["password"]=="$oldpass") and ("$pass"=="$cpass")){
$statement = $conn->prepare('update providers set password="$cpass" where password="$oldpass"');
$condition=$statement->execute();
echo '<script>alert("Password changed")</script>';
}
else{
echo '<script>alert("Incorrect old password");</script>';
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
EDIT The message on entering corresponding credentials is Password changed.
Is there anything wrong with the query??
Because it does not show the updated password in database (phpMyAdmin)
The changes you've made will only be visible inside the same transactions, and would be implicitly rolled back when you close the connection. In order to persist them in the database, you need to commit them:
$conn->commit();
I'm using PDO for my querys and try to escape some '&' since they make the request invalid. I already tried with mysql_real_escape_string and pdo quote... both didn't escaped the '&'. My values are for example "James & Jack".
As Connector:
$this->connect = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
As Query:
function check_exist($query,$parameter)
{
try
{
$this->connect->prepare($query);
$this->connect->bindParam(':parameter', $parameter, PDO::PARAM_STR);
$this->connect->execute();
return $this->connect->fetchColumn();
unset ($query);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Finaly the Call to action
$db = new database;
$db->connect('framework','localhost','root','');
$result = $db->check_exist('SELECT COUNT(*) FROM cat_merge WHERE cat=:parameter',$cat);
Try using prepared statements this way:
<?php
// Connect to the database
$db = new PDO('mysql:host=127.0.0.1;dbname=DB_NAME_HERE', 'username', 'password');
// Don't emulate prepared statements, use the real ones
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// Prepare the query
$query = $db->prepare('SELECT * FROM foo WHERE id = ?');
// Execute the query
$query->execute($_GET['id']);
// Get the result as an associative array
$result = $query->fetchAll(PDO::FETCH_ASSOC);
// Output the result
print_r($result);
?>
I'm trying to convert my codes to PDO from mysql_query, and starting with this function
function label_for_field($field_name, $table_name) {
$table = array();
// Bind variables to parameters
$param_array = array(':bundle' => $table_name, ':field_name' => $field_name);
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
// Execute
$STH -> execute($param_array);
// Set the fetch mode
$STH -> setFetchMode(PDO::FETCH_OBJ);
while ($row = $STH -> fetch()) {
$info = unserialize($row -> data);
$table[] = $info['label'];
}
return $table[0];
}
and I'm trying out just output it to see if it works
include_once ("includes/connect.php");
include ("includes/functions.php");
echo label_for_field("field_account_number", "account_table");
And here's the connect.php
// Include Constants
require_once ("constants.php");
//Establish Connection
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch (PDOException $e) {
echo $e -> getMessage();
}
I don't know if it's because I'm binding the parameters wrong, it just gave me an server error page
"Server error. The website encountered an error while retrieving ......."
Thanks in advance
You need to set the PDO error mode to produce exceptions before you can catch them.
In your connect.php:
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Then you can have a similar try/catch statement in your function to that of your connection file, and use it to show the error in your development environment.
Try this instead to see if you get valid objects returned from the query.
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
$STH->bindValue(":bundle", $table_name);
$STH->bindValue(":field_name", $field_name);
$STH->execute();
$STH->setFetchMode (PDO::FETCH_OBJ);
$result = $STH->fetchAll();
var_dump($result);
I am using PDO for the first time.
$result=$dbh->query($query) or die($dbh->errorinfo()."\n");
echo $result->fetchColumn();
$row = $result->fetch(PDO::FETCH_ASSOC);
The result of following code is that $row is initilazed ie isset but is empty.
I couldnot get where did I go wrong. thanks in advance
PDO doesn't do the old mysql_* style do or die() code.
Here's the correct syntax:
try {
//Instantiate PDO connection
$dbh = new PDO("mysql:host=localhost;dbname=db_name", "user", "pass");
//Make PDO errors to throw exceptions, which are easier to handle
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Make PDO to not emulate prepares, which adds to security
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = "SELECT * FROM `some_table`";
//Prepare the statement
$stmt = $dbh->prepare($query);
//Execute it (if you had any variables, you would bind them here)
$stmt->execute();
//Work with results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//Do stuff with $row
}
}
catch (PDOException $e) {
//Catch any PDOExceptions that were thrown during the operation
die("An error has occurred in the database: " . $e->getMessage());
}
You should read the PDO Manual, to get better understanding of the subject.
I'm on my way learning about PDO from phpro.org, and a little bit confuse.
<?php
try {
$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\pdo-tutorial.mdb;Uid=Admin");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
What is Uid? and what value should I enter?
And, about the query
<?php
try {
$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\pdo-tutorial.mdb;Uid=Admin");
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM animals";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$result = $stmt->fetch(PDO::FETCH_ASSOC);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I'm using odbc, but why the foreach functions just echo the first row, not looping echoing all my value in the database? here are the result.
Connected to database
ID - 1
animal_type - kookaburra
animal_name - bruce
can you tell me why?
For your second question:
You need to use fetchAll() instead of fetch(), which only gives you one row at a time.
In your code, try:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); (though that will change what your foreach loop looks like).
Alternatively, you can use a while loop to fetch each row as you need it:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//Do something with $row
}
Uid is Username with which you want to connect to database, if your mdb file is not protected you may omit this parameter.
To fetch all results you have to use fetchAll (http://php.net/manual/en/pdostatement.fetchall.php).