This question already has answers here:
Using constants in a PDO connection string and calling a function with a PDO connection [closed]
(2 answers)
Closed 4 years ago.
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
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.
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
cant connect to mssql server or sqlsrv not showing up on phpinfo
(1 answer)
Closed 2 years ago.
I am trying to connect PHP with mssql and facing this error.
I have downloaded the drivers and installed and configured my PHP.ini file as well.
I am receiving connection established but its not working for mssql_query can any body please help me on this.
<?php
$serverName = "server details";
$connectionInfo = array("Database"=> "mydbname", "UID" => "id", "PWD" => "password");
$conn = sqlsrv_connect($serverName , $connectionInfo);
if($conn){
echo "connection established <br />";
}
else{
echo "connection could not established <br />";
die(print_r(sqlsrv_errors(),true));
}
$query = "SELECT * FROM AgeNames";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
I have added these fields in PHP ini
PHP ini image
and this is what i am getting in phpinfo()
phpinfo
phpinfo screenshot 2
Seems you're using incorrect functions.
You need to use sqlsrv_query function instead of mssql_query i.e.
$result = sqlsrv_query( $conn, $query );
P.S.
mssql_query has been removed since PHP 7.0. Read more here.
This question already has answers here:
Fatal error: Uncaught Error: Call to undefined function mysql_connect()
(9 answers)
Closed 4 years ago.
I have added a post in my WordPress database with the title "titleofpost". I try to use in PHP 7 $wpdb get_results, but I get the following error:
Fatal error: Uncaught Error: Call to undefined function mysql_error().
What is wrong? Any help is appreciated.
I use the code below:
global $wpdb;
$leadTitle="titleofpost";
$sql = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$leadTitle%'";
$post_if = $wpdb->get_results($sql) or die(mysql_error()); //here dies
thy this
global $wpdb;
$leadTitle="titleofpost";
$sql = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$leadTitle%'";
$post_if = $wpdb->get_results($sql) or die(mysqli_error()); //here dies
mysql_* functions have been removed in PHP 7.
You probably have PHP 7 in XAMPP. You now have two alternatives: MySQLi and PDO.
Additionally, here is a nice wiki page about PDO.
Handling errors with PDO
PDO has multiple ways of handling errors.
There are three error modes for PDO.
The first is PDO::ERRMODE_SILENT. This acts much like the mysql_* functions in that after calling a PDO method you need to check PDO::errorCode or PDO::errorInfo to see if it was successful.
The second error mode is PDO::ERRMODE_WARNING. This is much the same except an E_WARNING message is also thrown.
The final error mode is PDO::ERRMODE_EXCEPTION. This one throws a PDOException when an error occurs. This is the method I recommend and will be using it for further examples.
// You can set the error mode using the fourth options parameter on the constructor
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// or you can use the setAttribute method to set the error mode on an existing connection
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//METHOD 2
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
log_error("Failed to connect to database", $e->getMessage(), $e->getCode(), array('exception' => $e));
}
//METHOD 3
try {
$dbh->query("INVALID SQL");
} catch (PDOException $e) {
log_error("Failed to run query", $e->getMessage(), $e->getCode(), array('exception' => $e));
}
According to this, then mysql_error() is deprecated since PHP 5.5.0. Perhaps try error_log() instead (and then look in the php error log).
It's probably this part of your code that causes the error: or die(mysql_error());
Thing i got all the addons working, some unofficial pdo driver for php(5.6)
This is my php;
<?php
$head = $_POST['title'];
$bread = $_POST['html'];
$author = $_POST['selectlist1'];
$postdate = date('y-m-d h:i:s',time());
$cat = $_POST['selectlist2'];
$serverName = 'SERVER\SQLEXPRESS';
$db = new PDO('sqlsrv:Server=$serverName;Database=blog', 'sa', '******');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'INSERT INTO dbo.blog_posts (blog_title, blog_post, blog_author, blog_date, blog_category) VALUES (:head, :bread, :author, :postdate, :cat)';
$query = $db->prepare( $sql );
$query->execute( array(':head'=>$head, ':bread'=>$bread, ':author'=>$author, ':postdate'=>$postdate, ':cat'=>$cat ) );
?>
And i get the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[08001]: [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [53]. ' in C:\inetpub\wwwroot\blog\post.php:9 Stack trace: #0 C:\inetpub\wwwroot\blog\post.php(9): PDO->__construct('sqlsrv:Server=$...', 'sa', '*****') #1 {main} thrown in C:\inetpub\wwwroot\blog\post.php on line 9
i have enabled named pipes etc i have no more ideas what im doing wrong... i have googled several hours...
instead of $serverName i have tried with localhost,127.0.0.1 etcetc but i cant get it working!
after some more digging around i found out that Named Pipes Provider: Could not open a connection to SQL Server [53] is some kind of network problem, dunno what problem tho...
Oke i think im something on the way, now i get:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[22007]: [Microsoft][SQL Server Native Client 11.0][SQL
Server]The conversion of a nvarchar data type to a datetime data type
resulted in an out-of-range value.' in
C:\inetpub\wwwroot\blog\post.php:15 Stack trace: #0
C:\inetpub\wwwroot\blog\post.php(15): PDOStatement->execute(Array) #1
{main} thrown in C:\inetpub\wwwroot\blog\post.php on line 15
i have done so many changes to everything and nothing tbh, but now it finally works, at the end my code looks like this:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$head = $_POST['title'];
$bread = $_POST['html'];
$author = $_POST['selectlist1'];
$postdate = date('Y-m-d H:i:s');
$cat = $_POST['selectlist2'];
$db = new PDO('sqlsrv:server=localhost;Database=blog', '****', '******');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'INSERT INTO dbo.blog_posts (blog_title, blog_post, blog_author, blog_date, blog_category) VALUES (:head, :bread, :author, :postdate, :cat)';
$query = $db->prepare( $sql );
$query->execute( array(':head'=>$head, ':bread'=>$bread, ':author'=>$author, ':postdate'=>$postdate, ':cat'=>$cat ) );
?>
So basically the thing ive tried all along did work, i have changed some ownership thingys in ms sql server management studio etc, i think that did the thing for me!
When I create database without using bind param, it works perfectly.
$login = 'root';
$password = 'root';
$dsn = "mysql:host=localhost";
$opt = array(
// any occurring errors wil be thrown as PDOException
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// an SQL command to execute when connecting
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
);
// Making a new PDO conenction.
$conn = new PDO($dsn, $login, $password,$opt);
$db = $conn->prepare( 'CREATE SCHEMA IF NOT EXISTS account');
$db->execute();
// End Connection and Return to other files.
But after applying the bindParam it is not working properly.
$db = $conn->prepare( 'CREATE SCHEMA IF NOT EXISTS ?');
$db->bindParam(1,`account`);
$db->execute(); //line 18
Showing error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1' in /Applications/MAMP/htdocs/create/index.php:18 Stack trace: #0 /Applications/MAMP/htdocs/create/index.php(18): PDOStatement->execute() #1 {main} thrown in /Applications/MAMP/htdocs/create/index.php on line 18
UPDATE:
<?php
$login = 'root'; // Login username of server host.
$password = 'root'; // Password of server host.
$dsn = "mysql:host=localhost"; // Set up a DSN for connection with Database Frat.
$dbb = 'sale';
$opt = array(
// any occurring errors wil be thrown as PDOException
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// an SQL command to execute when connecting
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
);
// Making a new PDO conenction.
$conn = new PDO($dsn, $login, $password,$opt);
$db = $conn->prepare( 'CREATE SCHEMA IF NOT EXISTS ?');
$db->bindParam(1,'$dbb'); //line 17
$db->execute();
?>
it showing error:
Cannot pass parameter 2 by reference on line 17
There are two big problems here. The first is minor. These lines of code will never work:
$db->bindParam(1,`account`);
$db->bindParam(1,'$dbb'); //line 17
This is because both of them are attempting to call bindParam as a string. This is impossible. bindParam needs a reference to a variable. This is why you get a "cannot pass parameter 2 by reference" error: you can only pass variables by reference.
Either of these, however, would work:
$db->bindParam(1, $dbb); // call bindParam on a variable
$db->bindValue(1, 'account'); // call bindValue on a string literal
The more fundamental problem, however, is your understanding of prepared statements. The idea of prepared statements is not simple substitution of strings into another string. It is fundamentally about separation of the structure of the query from the data. The name of a table is considered part of the structure of the query, not part of the data. You need to put the table name in the original query. Your first code is the way to do it.
$db = $conn->prepare( 'CREATE SCHEMA IF NOT EXISTS account');
This question already has answers here:
Warning: mysqli_error() expects exactly 1 parameter, 0 given error
(4 answers)
Closed 2 years ago.
I am trying to get my head around mysql. Can someone tell my why this mysql query is not working? I am getting the following error:
Warning: mysqli_error() expects
exactly 1 parameter, 0 given in
/home/freebet2/public_html/test.php on
line 11
test.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$conn = db_connect();
$result = $conn->query("ALTER TABLE users ADD COLUMN refer_old INT(10) AFTER refer_id");
if(!$result){
echo "Error with MySQL Query: ".mysqli_error();
}
?>
db.php
<?php
function db_connect() {
$result = new mysqli('localhost', 'user', 'password', 'db');
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
?>
If I change the alter string to something like : $result = $conn->query("SELECT * FROM users refer_id"); I get no error for some reason.
You are mixing the object-oriented and the procedural styles of the mysqli API :
You are using object-oriented :
$result = new mysqli('localhost', 'user', 'password', 'db');
And, then, procedural :
echo "Error with MySQL Query: ".mysqli_error();
You should use either OO, or procedural -- but not both ; and if you choose procedural, the functions expect the link identifier passed as a parameter.
For instance, mysqli_error should be called either using the object-oriented API :
$link = new mysqli(...);
echo $link->error;
Or the procedural API :
$link = mysqli_connect(...);
echo mysqli_error($link);
(Of course, it will not change the fact that you are having an error in your SQL query, but it'll allow you to get the error message, which should help finding the cause of that error)
As far as the sql error is concerned, does 'user' have permissions to alter the table?
Use mysqli_error($result) as mysqli_error expects the connection to be passed as a parameter.