php Call to a member function prepare() on a non-object problem - php

<?php
$dbtype = 'mysql';
$mysql_host = "localhost";
$mysql_database = "mydb";
$mysql_user = "root";
$mysql_password = "";
try {
$db = new PDO ( $dbtype . ':host=' . $mysql_host . ';dbname=' . $mysql_database, $mysql_user, $mysql_password, array (PDO::ATTR_PERSISTENT => true ) );
return $db;
} catch ( PDOException $e ) {
return false;
}
?>
Above are my db.php
<?php
require db.php";
...
global $db;
$stmt = $db->prepare ( "INSERT INTO quote (title, contactname) VALUES (:a, :b);" );
I actually able to run it properly under my IDE (ZendStudo wamp server) but once i upload to host server i got this error. Anybody facing the same problem before can guide me how to fix?

There can me many reasons, but one obivious is that is you had a PDOException, then $db == false, which would explain the error message.
Try to check if $db is correctly set as a PDO or false.

PDO does not throw exceptions unless you explicitly instruct it to do so:
$db = new PDO(...);
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Related

NetBeans 8.2 PHP Code Completion Issue

So i've been having an issue with NetBeans code completion. I'm currently trying to set up a database connection that i can use in my other files. Inside of my connection.php file, I have access to all of the usual database methods. My end goal is to use prepared statements for my queries.
However, when i am inside my register.php file, with connection.php required at the top, suddenly code completion doesn't work anymore. I get the generic popup. This is the file i would like to actually use those prepared statements in. I would also like to avoid having to open a new connection in every file.
So my question to you is, is it me or is it NetBeans?
connection.php
$host = "localhost";
$username = "root";
$pass = "password";
$database = "LoganWebsiteUserLogin";
try {
$conn = new PDO('mysql:host=localhost;dbname=' . $database . ';charset=utf8mb4', $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected Successfully!";
} catch (PDOException $e) {
echo "Connection failed! " . $e->getMessage();
}
register.php
<?php
require 'connection.php';
// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];
// trying to access $conn from connection.php here, however autocomplete for
// it is not working. NetBeans doesn't know that $conn is a PDO
$conn->
It works in PhpStorm but not in Netbeans. But anyway, global variables are not recommended and lead to unwanted side effects. Maybe try a different approach.
Example:
connection.php
<?php
function db(): PDO
{
static $pdo = null;
if (!$pdo) {
$host = "localhost";
$username = "root";
$password = "password";
$database = "LoganWebsiteUserLogin";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
];
$pdo = new PDO("mysql:host=$host;dbname=$database;charset=utf8mb4", $username, $password, $options);
}
return $pdo;
}
register.php
<?php
require_once __DIR__ . '/connection.php';
// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];
// Works :-)
db()->

reducing repetitive code in PHP

I'm using this same block of code in numerous PHP files and sometimes in the same PHP file (e.g., when there's an if/else. I know there's a better way, but I'm not quite sure how to do it. I want to replace this big block with something, but not sure what fits. require maybe?
$hostname = 'localhost';
$database = 'dev_testing';
$username = 'root';
$password = 'XXXXXX';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The answers by #maalls and #TahaPaksu are good, but #marcB's comment is even better: usually you'd want to connect to the database only once per script execution. I don't want to kick you right in the direction of dependency injection, but as an intermediate solution, I'd like to suggest this class, which looks roughly like a singleton, but is actually the Memoization pattern implementation (see also PHP Design Patterns for other pattern examples).
Anyway: the code:
class Database() {
static private $connection = null;
public static function getConnection() {
if (static::$connection === null) {
$hostname = 'localhost';
$database = 'dev_testing';
$username = 'root';
$password = 'XXXXXX';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
static::$connection = $dbh;
}
return static::$connection;
}
}
In your script you can call it using
$dbh = Database::getConnection();
You can call that line as often as you like but it will only connect to the database the first time it's called for that script. Subsequent calls will just return the same connection. This will save quite some overhead on your database.
Create a separate file (for ex. "connection.php"), put the code in it, and everywhere you need it, include the following at the begining of your code:
require_once('connection.php');
you can use a global function which you include in top of your php files:
require_once("db.php");
file db.php:
function db_connect(){
$hostname = 'localhost';
$database = 'dev_testing';
$username = 'root';
$password = 'XXXXXX';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
and in your files:
$dbh = db_connect();
...
// don't forget to close db before you open a new connection!
$dbh = null;

PHP - PDO SQLSRV - Connection string is not valid [87]

I´m trying to connect to a SQL Server 2008 R2 via PHP. I used the following code:
try {
$server = "servername.do.ma.in\\MSSQLSERVER";
$user = "username";
$pass = "password";
$db = "databasename";
$dbh= new PDO('sqlsrv:Server = ' . $server . '; Database = ' . $db, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Verbindung fehlgeschlagen: ' . $e->getMessage();
}
But when i run this code i get the following error:
SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87].
Does someone know this error and know what to do?
Thanks in advance.
Solution:
The Port was not defined. The following code worked for me.
I´ve added the Port 1433 to the $server Variable.
$server = "servername.do.ma.in, 1433";
$user = "username";
$pass = "password";
$db = "databasename";
$dbh = new PDO("sqlsrv:Server={$server};Database={$db};", $user, $pass);
This will work:
$dbh = new PDO("sqlsrv:Server={$server};Database={$db};", $user, $pass);
If it's still not valid, there's something wrong with your connection variables.
EDIT:
This looks similar to your problem:
http://laravel.io/forum/01-20-2015-sql-server-2012-db-connection-with-laravel-42

MySQL connection error in configuration file

I want to connect to mysql database using php and following is my configuration file.
<?php
$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";
mysql_connect ($host,$username,$password);
mysql_select_db($db,$username);
?>
but when I run my program it gives me this error:
SQL error: No database selected SQL errno: 1046
SQL: select language, admin from user where username='admin' and password='abc123'
What's wrong with my code?
You forgot a semicolon here
$db = "payroll";
^--- Here
Don't forget to enable error reporting on your code. This is how you do it.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
Switch to Prepared Statements..
A kickstart example..
<?php
$dsn = 'mysql:dbname=payroll;host=localhost';
$user = 'root';
$password = '';
try
{
$dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
Read more here on PHP Manual
$mysqlhost="localhost"; // MySQL-Host
$mysqluser="user"; // MySQL-User
$mysqlpwd="password"; // Password
$connection=mysql_connect($mysqlhost, $mysqluser, $mysqlpwd) or die
("Couldn´t connect");
$mysqldb="database"; // Your Database
mysql_select_db($mysqldb, $connection) or die("Couldnt select database");
I always use this. Here you get every errormessage you need to find your error.
Try this
<?php
$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";
$con = mysql_connect ($host,$username,$password);
mysql_select_db($db,$con);
?>

change Mysqli to sqlsrv

I am new to PHP and need to modify some code in order to compile with my Microsoft SQL Server. The original code is like this. I downloaded it from usercake
<?php
/*
UserCake Version: 2.0.2
http://usercake.com
*/
//Database Information
$db_host = "localhost"; //Host address (most likely localhost)
$db_name = "202"; //Name of Database
$db_user = "202"; //Name of database user
$db_pass = "password"; //Password for database user
$db_table_prefix = "uc_";
GLOBAL $errors;
GLOBAL $successes;
$errors = array();
$successes = array();
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
GLOBAL $mysqli;
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
//Direct to install directory, if it exists
if(is_dir("install/"))
{
header("Location: install/");
die();
}
?>
I already installed sqlsrv and tested the link. It works with my database. Then I changed the code to this:
<?php
//Database Information
$server = "servername";
$connectionInfo = array("Database"=>"databasename","UID"=>"xxxxxx", "PWD"=>"xxxxxx" );
$db_table_prefix = "uc_";
GLOBAL $errors;
GLOBAL $successes;
$errors = array();
$successes = array();
/* Create a new sqlsrv object with database connection parameters */
$mssqlsrv = new sqlsrv($server, $connectionInfo);
GLOBAL $mssqlsrv;
if(sqlsrv_connect_errno()) {
echo "Connection Failed: " . sqlsrv_connect_errno();
exit();
}
//Direct to install directory, if it exists
if(is_dir("install/"))
{
header("Location: install/");
die();
}
?>
I get the following error message:
Fatal error: Class 'mssql' not found in
I think this line is the problem:
$mssqlsrv = new sqlsrv($server, $connectionInfo);
But I do not know how to fix this.
I would use PDO in this case: http://www.php.net/manual/en/pdo.construct.php
You can create a DSN connection to SQL Server
$dsn = "sqlsrv:Server=servername;Database=databasename"
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
The information to connect to SQL server is available here: http://www.php.net/manual/en/ref.pdo-sqlsrv.connection.php

Categories