How to connect to mssql with php? - php

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!

Related

Uncaught exception 'PDOException' with message 'invalid data source name' [duplicate]

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.

pdo OPENJSON insert with php not working (Azure SQL)

Normally this code works as a T-SQL script in Visual Studio except in T-SQL I add in:
declare #json nvarchar(MAX) = '{...}'
#json goes in the OPENJSON function
I am attempting to create a PHP script for the OPENJSON insert but this doesn't seem to work. I am a total beginner to all things Azure/SQL/PHP.
For reference on the OPENJSON function:
https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/09/22/openjson-the-easiest-way-to-import-json-text-into-table/
<?php
include_once("connection.php");
$JSONrow = $_POST["jsonrow"];
$table = $_POST["table"];
$with = "(jobticketnumber nvarchar(50), contractor nvarchar(50),joblocation nvarchar(50), ...";
$pdo_JSONinsert = $conn -> prepare('INSERT INTO '.$table.' SELECT * FROM OPENJSON('.$JSONrow.') WITH '.$with.'');
$pdo_JSONinsert -> execute();
$conn = null;
?>
Thanks for the help!
Edit: error from PDO
<br />
<b>Fatal error</b>: Uncaught PDOException: SQLSTATE[42000]: [Microsoft][ODBC Driver 13 for SQL Server]Syntax error, permission violation, or other nonspecific error in D:\home\site\wwwroot\insertrow.php:7
Stack trace:
#0 D:\home\site\wwwroot\insertrow.php(7): PDO->prepare('INSERT INTO job...')
#1 {main}
thrown in
<b>D:\home\site\wwwroot\insertrow.php</b> on line
<b>7</b>
<br />

sql query not executed correctly

My PHP/SQL code doesn't seem to work since the moment that I changed my operating system from Windows 7 to Linux Mint.
$AddUserToDatabase = $DatabaseConnection->prepare(
'INSERT INTO gebruikers (' .
' gebruiker_naam, profiel_foto, wachtwoord,' .
' salt, email, timestamp, admin' .
') VALUES (' .
' :username, :profiel_foto, :wachtwoord,' .
' :salt, :email, :timestamp, :admin' .
')'
);
$AddUserToDatabase->execute(
array(
'username' => $Username,
'profiel_foto' => 'UnknownUser.png',
'wachtwoord' => $EncryptedPassword,
'salt' => $Salt,
'email' => $Email,
'timestamp' => $CurrentTimestamp,
'admin' => '0'
)
);
I didn't change anything about the code since i changed the operating system, and I don't get any errors or warnings from the statement.
After the page has loaded i checked for the new record in de database but it isn't there :(
I find it really odd that after changing from windows to linux the code stoped working.
Does anyone know whats going on?
EDIT:
I just tried to execute some of the other statements but none of them seems to work. I think i have some bad configuration somewhere..
EDIT2
In index.php i am including the next files
include 'Class/Session.php';
include 'Class/Login_Register.php'
$Session->ConnectWithDatabase();
And this is the error, but i dont understand why it says no database selected...
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected'
in /var/www/html/ScriptDeals/Classes/login_register.php:227
Stack trace:
#0 /var/www/html/ScriptDeals/Classes/login_register.php(227):
PDOStatement->execute(Array)
#1 /var/www/html/ScriptDeals/Classes/login_register.php(81):
LoginRegister->RegisterUser('test#live.nl', 'test', '12345678')
#2 /var/www/html/ScriptDeals/index.php(20):
LoginRegister->FormErrorHandling()
#3 {main}
thrown in /var/www/html/ScriptDeals/Classes/login_register.php on line 227
This is what sets my database connection
function ConnectWithDatabase()
{
global $DatabaseConnection;
$DatabaseUsername = 'root';
$DatabasePassword = 'database';
$DatabasePath = 'mysql:host=localhost;port:3306;dbname=scriptdeals';
$DatabaseConnection = new PDO(
$DatabasePath, $DatabaseUsername, $DatabasePassword
);
}
Sorry guys for this question!
I found out that i had to remove port:3306
After i did this i got a error about a missing field in the database.
I added the new field and it works now ^^
Thanks for the help, but sorry for the misplaced question!

create database with pdo in php

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');

MDB access using php

I am having a little bit of trouble trying to write to a .mdb database from php.
The database has a table called comments and it has 3 columns "id", "comment" and "by". The code I have is this.
<?php
$count =0;
$db_path = "newsBlog.mdb";
$odbc_con = new COM("ADODB.Connection");
$constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";";
$odbc_con -> open($constr);
$sql = "INSERT INTO [comments] VALUES (".$_POST['newsId'].",'".$_POST['comment']."', '".$_POST['by']."')";
echo $sql;
$odbc_con -> execute (sql);
$rs = null;
$conn = null;
echo "done";
?>
It takes 3 values from a form on the previous page and should insert them into the database, except I get this error every time:
<b>Fatal error</b>: Uncaught exception 'com_exception' with message '<b>Source:</b> Microsoft OLE DB Provider for ODBC Drivers<br/><b>Description:</b> [Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.' in D:\Hosting\7010757\html\users\kinectfashion\postComment.php:20 Stack trace:
#0 D:\Hosting\7010757\html\users\kinectfashion\postComment.php(20): com->execute('sql')
#1 {main} thrown in <b>D:\Hosting\7010757\html\users\kinectfashion\postComment.php</b> on line <b>20</b><br />
To me, this seams MAD as I am using an insert statement and cannot see what I am doing wrong!
Any help would be much appreciated!
Thanks
$odbc_con -> execute (sql); should be $odbc_con -> execute ($sql);

Categories