This question already has an answer here:
I know there are many question regarding on stackoverflow but i read them all but my didn't fixed, so i asked new question. I have a file named as article.php and i have the this code init. Just a code which is showing error.
public static function getById( $id ) {
$conn = new PDO( DB_HOST, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles WHERE id = :id";
$st = $conn->prepare( $sql );
$st->bindValue( ":id", $id, PDO::PARAM_INT );
$st->execute();
$row = $st->fetch();
$conn = null;
if ( $row ) return new Article( $row );
I am getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'invalid data source name' in C:\wamp64\www\classes\Article.php on line 102
( ! ) PDOException: invalid data source name in C:\wamp64\www\cms\classes\Article.php on line 102
My config file looks like
ini_set( "display_errors", true );
define( "DB_HOST", "localhost" );
define( "DB_USERNAME", "username" );
define( "DB_PASSWORD", "" );
define('DB_NAME', 'name');
Can you tell me why this happens and where i am doing mistake. Thanks
</div>
Your current code seems to be used before with mysql
or mysqli
connector, however PDO
is way more generic and supports multiple database vendors and not just MySQL. So you need to tell PDO
which db to connect, etc.
So PDO
fails to make connection with only db name, your DB_HOST
must be similar to this:
define('DB_HOST','mysql:host=localhost;dbname=testdb');
More options to connect:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
getting this error mysqli_real_escape_string() expects exactly 2 parameters, 1 given
You don't need this since you are using PDO. Use PDO's API instead.