Here I am sharing code of two functions. Both return an instance of a PDO object. But one of them works fine when a statement is inserted using the PDO connection where as other one does not. The same identical code is used in both cases to insert a record.
This is the function whose returned PDO object works with the insert statement.
public function getPDO() {
/** mysql hostname */
$hostName = 'localhost';
/** mysql database name */
$dbName = 'testDB';
/** db user name */
$userName = 'root';
/** db password */
$password = '';
try {
$str = "mysql:dbname=$dbName;host=$hostName";
$db = new PDO($str, $userName, $password );
return $db;
}catch(PDOException $e) {
echo "PDO connection failed. <br />";
echo $e->getMessage();
return null;
}
}
This is the function whose returned PDO object DOES NOT work with the insert statement. In this function the connection string and other connection parameters are read from static values defined in the class.
public function getPDO() {
try {
$connStr = "mysql:dbName=".self::$dbName.";host=".self::$hostName;
$db = new PDO($connStr, self::$userName, self::$password);
return $db;
}catch(PDOException $e) {
echo "PDO connection failed. <br />";
echo $e->getMessage();
return null;
}
}
Here is how the static variables are defined:
/** mysql hostname */
static $hostName = "localhost";
/** mysql database name */
static $dbName = "testDB";
/** db user name */
static $userName = 'root';
/** db password */
static $password = '';
And here is the piece of code which uses the PDO object to insert a record.
public function save() {
//get the PDO
$db_func = new db_functions();
$pdo = $db_func->getPDO();
$query = "INSERT INTO city(name, state, country) VALUES ('Vienna', 'Virginia', 'USA')";
echo $query;
$count = $pdo->exec($query);
if($count > 0) {
echo '</br> Successful </br>';
}else {
echo '</br> Unsuccessful </br>';
}
}
When I use the second function, the PDO object is created successfully but the insert fails. I do not see any error but the count is 0 and no records in the DB.
I am suspecting this has to do with the way I am declaring and using static variables in my code. Thanks for your help.
It’s not related to static variables, your second method just doesn’t pass the database name properly. It must be ‘dbname’ instead of ‘dbName’.