For some reason, this custom PDO class fails to write to the database. It simply quietly fails - no error message thrown. A very similar custom PDO class (ReadPDO) works wonderfully for reading from the database. The SQL statement generated works fine when it's queried to the DB through PHPMyAdmin. I've double-checked the user permissions, and everything seems in order.
I suspect I'm misunderstanding how something works. Any ideas?
// Creates a write-only PDO, using config settings from inc_default.php
class WritePDO extends PDO{
public function __construct(){
//Pull global DB settings
global $db;
global $write_host;
global $write_username;
global $write_password;
try{
parent::__construct("mysql:dbname={$db};host={$write_host}", $write_username, $write_password);
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
}
private function updatePlayer(){
$conn = new WritePDO();
$sql = "UPDATE {$this->hvz_db}
SET
hvz_bitten ='{$this->hvz_bitten}',
hvz_died ='{$this->hvz_died}',
hvz_feedCode ='{$this->hvz_feedCode}',
hvz_status ='{$this->hvz_status}',
hvz_feeds ='{$this->hvz_feeds}',
hvz_lastFed ='{$this->hvz_lastFed}',
hvz_ozOpt ='{$this->hvz_ozOpt}',
hvz_parent ='{$this->hvz_parent}'
WHERE users_id ={$this->id}";
$query = $conn->exec($sql);
}
The SQL it spits out is as follows:
UPDATE hvz_2011_spring SET hvz_bitten ='', hvz_died ='', hvz_feedCode ='NOMNOM', hvz_status ='Human', hvz_feeds ='0', hvz_lastFed ='', hvz_ozOpt ='0', hvz_parent ='' WHERE users_id =1
are you sure the sql is correct?
The exec doesn't send any error message.
Try doing var_dump($conn->errorInfo()); after $conn->exec($sql);
/Emil
Related
suppose I have the class named as User and user is an object of that class,
now I call a function named as storevalues from user(an object of class User).
In the storevalues function,__construct function is called which assign the value to the class member.$this->name,$this->email,$this->password.
finally I try to store these values in DATABASE through PDO.
$conn = new PDO(DB_DSN,DB_USERNAME,DB_PASSWORD);
$sql="insert into user_info(name,email,password)values(:name,:email,:password)";
$st=$conn->prepare($sql);
$st->bindValue(":name",$this->name,PDO::PARAM_STR);
$st->bindValue(":email",$ths->email,PDO::PARAM_STR);
$st->bindValue(":password",$this->password,PDO::PARAM_STR);
$st->execute();
But the above code is not working.The connection is successfull made to the database but query is not executed.I want to know what mistake I have done in this code.
When I try assigning the class members value to the new variable then it works.The code below shows that method
$name=$this->name;
$email=$this->email;
$password=$this->password;
$conn = new PDO(DB_DSN,DB_USERNAME,DB_PASSWORD);
$sql="insert into user_info(name,email,password)values(:name,:email,:password)";
$st=$conn->prepare($sql);
$st->bindParam(":name",$name,PDO::PARAM_STR);
$st->bindParam(":email",$email,PDO::PARAM_STR);
$st->bindParam(":password",$password,PDO::PARAM_STR);
$st->execute();
I am a beginner in php and pdo and I know that my code is inefficient.Help me in finding the mistake in first method and identifying my mistakes.
User class
class User
{
public $name=null;
public $email=null;
public $password=null;
public function __construct($data=array())
{
if(isset($data['name']))
$this->name=$data['name'];
if(isset($data['email']))
$this->email=$data['email'];
if(isset($data['password']))
$this->password=$data['password'];
}
public function storevalues($result=array())
{
$this->__construct($result);
$conn = new PDO(DB_DSN,DB_USERNAME,DB_PASSWORD);
$sql="insert into user_info(name,email,password)values(:name,:email,:password)";
$st=$conn->prepare($sql);
$st->bindParam(":name",$this->name,PDO::PARAM_STR);
$st->bindParam(":email",$this->email,PDO::PARAM_STR);
$st->bindParam(":password",$this->password,PDO::PARAM_STR);
$st->execute();
}
}
You may catch the SQL error after the execute:
if ( ! $st->execute) {
Throw new exception('Mysql Error - ' . implode(',', $st->errorInfo()));
}
I have an issue that I can't figure out. I have a class Database which if I use it directly I connect to db regularly. I have another class Categories and I want to call a Database object. The problem is that if I call $db->connect in categories does not work. I tried call mysql_connect directly in Categories and it works fine!
Why can't I use $db->connect (the error is Access denied for user 'user'#'0.0.0.0' (using password: YES).
My code in class Database is:
public function connect($new_link=false){
$this->link_id = #mysql_connect($this->server,$this->user,$this->pass,$new_link);
echo "<br/>link_id = ".$this->link_id;
if (!$this->link_id){//open failed
$this->oops("Could not connect to server: <b>$this->server</b>.");
}
else{
echo "Connected to server <br/>";
}
if(!#mysql_select_db($this->database, $this->link_id)){//no database
$this->oops("Could not open database: <b>$this->database</b>.");
}
else{
echo "Database opened <br/>";
}
// unset the data so it can't be dumped
$this->server='';
$this->user='';
$this->pass='';
$this->database='';
}#-#connect()
My code in class Category is:
public static function selectAll() { // SELECT All Function
$db = Database::obtain();
// connect to the server
$db->connect();
$sql = "SELECT * FROM productCategory";
$rows = $db->fetch_array($sql);
return $rows;
}
Database::obtain code
public static function obtain($server=null, $user=null, $pass=null, $database=null){
if (!self::$instance){
self::$instance = new Database($server, $user, $pass, $database);
}
return self::$instance;
}#-#obtain()
Am I doing sth wrong, that I can't see?
Well, the error message is "Access denied for user 'user'#'0.0.0.0'"
That means when you instantiate your class with $db = Database::obtain(); You don't set the values for server, user, pass, database. Probably the class Database implements a singleton pattern, and the method obtain() just returns the instance without any properties set.
I'm rewriting my php code for mysql database access (now using a class definitions). While I had the old code (using old style functions) working I struggle to get the code for creating tables right - I think the problem relates in particular to the right definition of the sql statement, pls see code below. The new aspect (for me) compared to the old code is that the sql table creation command now must include the name of a database different than the master_database for which the PDO connection is set up (within the class constructor).
I looked at http://dev.mysql.com/doc/refman/5.6/en/create-table.html (I use mysql v5.6) - the part starting with "The table name can be specified as db_name.tbl_name to ..." but I cant get the sql syntax right. If I'm right the sql syntax is wrong what should be the right syntax in the code below for $sql (using the construction with various variables)?
Thnx for your help in advance.
Simplified code:
<?php
define('DB_HOST', '***');
define('DB_NAME', 'MASTER_DATABASE'); //different name
define('DB_USER', 'root');
define('DB_PASS', '*****');
//class definitions
class Database {
private $_db = null; //databasehandler
public function __construct() {
try {
$this->_db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS, array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
));
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_db->query('SET CHARACTER SET utf8');
} catch (PDOException $e) {
exit('Error while connecting to database.'.$e->getMessage());
}
}
private function printErrorMessage($message) {
echo $message;
}
public function createDBTable($dbname,$dbtable,$tablestructure) {
try {
$sql = "CREATE TABLE `".$dbname."'.'".$dbtable.$tablestructure; //NOT CORRECT YET
$success = $this->_db->exec($sql);
return ($success > 0) ? true:false;
}
catch(PDOException $e){
$this->printErrorMessage($e->getMessage());
}
}
}//class
//code using class defs
$dbname = 'Mydatabase'; //just an existing database
$dbtable = 'Persons';
$tablestructure = '(FirstName CHAR(30),LastName CHAR(30),Age INT)';
$mydb = new Database();
if($mydb->createDBTable($dbname,$dbtable,$tablestructure)){
echo 'table creation success';
}
else{
echo 'table creation failure';
}
?>
You can replace you create table line as:-
$sql = "CREATE TABLE ".$dbname.".".$dbtable."".$tablestructure; //NOT CORRECT YET
Also instead of:-
$success = $this->_db->exec($sql);
Use the below lines:-
$stmt = $this->_db->prepare($sql);
$success = $stmt->execute();
Without the above 2 lines, the $succes variable will have value of 0 and although the table can be created, it would echo table creation failed.
Hope this helps.
I need to do continuous parsing of several external stomp data streams, inserts of relevant fields into a MySql db, and regular queries from the db. All of this is in a protected environment - ie I'm not dealing with web forms or user inputs
Because I'm implementing a range of inserts into + queries from different tables, I've decided to set up a PDO active record model - following the advice of Nicholas Huot and many SO contributors.
I've got a simple repeated insert working OK, but after several days of grief can't get a prepared insert to fly. I want to use prepared inserts given there are going to be a lot of these (ie for performance).
Relevant bits of the code are :
=========
Database class :
private function __construct()
{
try {
// Some extra bad whitespace removed around =
$this->dbo = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME, DBUSER, DBPSW, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public static function getInstance()
{
if(!self::$instance)
{
self::$instance = new self();
}
return self::$instance;
}
public function prepQuery($sql) // prepared statements
{
try {
$dbo = database::getInstance();
$stmt = new PDOStatement();
$dbo->stmt = $this->$dbo->prepare($sql);
var_dump($dbo);
}
catch (PDOException $e) {
echo "PDO prepare failed : ".$e->getMessage();
}
}
public function execQuery($sql) // nb uses PDO execute
{
try {
$this->results = $this->dbo->execute($sql);
}
catch (PDOException $e) {
echo "PDO prepared Execute failed : \n";
var_dump(PDOException);
}
}
=========
Table class :
function storeprep() // prepares write to db. NB prep returns PDOstatement
{
$dbo = database::getInstance();
$sql = $this->buildQuery('storeprep');
$dbo->prepQuery($sql);
return $sql;
}
function storexecute($paramstring) // finalises write to db :
{
echo "\nExecuting with string : " . $paramstring . "\n";
$dbo = database::getInstance(); // Second getInstance needed ?
$dbo->execQuery(array($paramstring));
}
//table class also includes buildQuery function which returns $sql string - tested ok
=======
Controller :
$dbo = database::getInstance();
$movements = new trainmovts();
$stmt = $movements->storeprep(); // set up prepared query
After these initial steps, the Controller runs through a continuous loop, selects the fields needed for storage into a parameter array $exec, then calls $movements->storexecute($exec);
My immediate problem is that I get the error message "Catchable fatal error: Object of class database could not be converted to string " at the Database prepquery function (which is called by the Table storeprep fn)
Can anyone advise on this immediate prob, whether the subsequent repeated executes should work in this way, and more widely should I change anything with the structure ?
I think your problem in this line $dbo->stmt = $this->$dbo->prepare($sql);, php want to translate $dbo to string and call function with this name from this. Actually you need to use $this->dbo.
And actually your functions not static, so i think you don't need to call getInstance each time, you can use $this.
after reading a lot of post but not getting this thing running, maybe somone can help me with this.
I am trying to include a PHP (Module.php) file which craps information from db into my index.php. This index.php also includes the file with the database connection. The problem is the included file which handles the db selects seems not to know about the PDO Object, the Script dies which this error:
Fatal error: Call to a member function prepare() on a non-object in
I tried to make the PDO Object global. But unfortunately this is not working.
Thanks a lot for any help (and safe me not going crazy ...)
Tony
index.php
//DB Connection
require_once ("include/db_connect_inc.php");
$request = $_GET['Controll'];
switch ($request) {
case 0:
echo "XY";
break;
case 1:
global $objDb;
//This file should be able to use the DB Object
include("modules/Eat/Module.php");
break;
}
Module.php
global $objDb;
$dbSelect = $objDb->prepare(
"SELECT DISTINCT ON (nummer) nummer
FROM tableX
"
);
$dbSelect->execute();
while($row = $dbSelect->fetch(PDO::FETCH_ASSOC)) {
$all = $row['nummer'];
}
echo "1 - " . $all;
db_connect_inc.php
$strDbLocation = 'pgsql:host=localhost;dbname=test';
$strDbUser = 'root';
$strDbPassword = 'root';
try{
$objDb = new PDO($strDbLocation, $strDbUser, $strDbPassword);
$objDb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
global $objDb;
}
catch (PDOException $e){
//echo 'Fehler beim Öffnen der Datenbank: ' . $e->getMessage();
print "Error!: " . $e->getMessage() . "<br/>";
}
As you don't seem to use any functions, your variable is already set in the global scope, so you should get rid of all the global $objDb; lines.
That should solve the problem as long as there is no error in the first 3 lines where you connect to the database.
Apart from that I would use OOP / classes and use dependency injection to make sure my Module class is always provided with the stuff it needs (a db connection in this case).