pdo OPENJSON insert with php not working (Azure SQL) - php

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 />

Related

Fatal error: Uncaught exception 'PDOException' thrown in C:\xampp\htdocs\register.php on line 19

I have received:
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 MariaDB server version for the right syntax to use near '5538ac14bb2ca7514f9f4d8826f3c45e'')' at line 1' in C:\xampp\htdocs\register.php:19 Stack trace: #0 C:\xampp\htdocs\register.php(19): PDO->exec('insert into use...') #1 {main} thrown in C:\xampp\htdocs\register.php on line 19.
How can this be solved, like what should be done?
<?php
session_start();
// If the form has been submitted
if (isset($_POST['submitted'])){
// Create a database connection
$db = new PDO("mysql:dbname=johnsoa7_db;host=localhost", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Get and sanitise the inputs, we don't need to do
// this with the password as we hash it anyway
$safe_forename = $db->quote($_POST['forename']);
$safe_lastname = $db->quote($_POST['lastname']);
$safe_email = $db->quote($_POST['email']);
$hashed_password = $db->quote(md5($_POST['password']));
// Insert the entry into the database
$query = "insert into users values (default, $safe_forename, $safe_lastname, $safe_email, '$hashed_password')";
$db->exec($query);
// Get the ID
$id = $db->lastInsertId();
// Output success or the errors
echo "Congratulations! You are now registered. Your ID is: $id";
}
?>
You have an error in this line:
$query = "insert into users values (default, $safe_forename, $safe_lastname, $safe_email,'$hashed_password')";
default should be quoted if it is string.
If it is a variable, you missed $.
Please see the comment by #ceejayoz:
As he said you don't need quoted around $hashed_password...

How to connect to mssql with 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!

How to acces .mdb and return value from it using php

I've a mdb file called short_db.mdb in my server which is placed under wwwroot\db\short_db.mdb,I have created a sample php script called fetchmdb.php to fetch values from aforementioned mdb i.e follows
<?php
$count =0;
$db_path = "short_db.mdb ";
$odbc_con = new COM("ADODB.Connection") or die("Cannot start ADO");
$constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";";
$odbc_con -> open($constr); //line - 9
$sql = "SELECT top 5 `id`
,val1
,val2
FROM `tbl_accounts`";
echo $sql;
$odbc_con -> execute ($sql);
$rs = null;
$conn = null;
echo "done";
?>
and this fetchmdb.php is also hosted into the same place where mdb file is located (wwwroot\db\fetchmdb.php) so both mdb and php files are under in one directory(wwwroot\db)
So, When I run my url(http://thesite.com/db/fetchmdb.php) getting following error
Fatal error: Uncaught exception 'com_exception' with message 'Source:
Microsoft OLE DB Provider for ODBC Drivers Description:
[Microsoft][ODBC Microsoft Access Driver] Could not use '(unknown)';
file already in use.' in
E:\HostingSpaces\medlabsi\remedyonline.in\wwwroot\db\mdb.php:9 Stack
trace: #0 E:\HostingSpaces\mysite\thesite.com\wwwroot\db\mdb.php(9):
com->open('DRIVER={Microso...') #1 {main} thrown in
E:\HostingSpaces\mysite\thesite.com\wwwroot\db\mdb.php on line 9
Fixed the issue using this solution

SQL Server Version Error with PHP

I built a simple website, it's like a watered down directory. You list all entries and then can click on an entry to know more details.
It works fine on my test server, but swapped over to another server it breaks. I am unsure why exactly, and I have not altered the code from the working code. So I assume that it is a version error.
However I am unsure what, and therefore can't think of alternative ways to write it.
Here is the sample of code causing problems:
$username456 = 'username';
$password456 = 'password';
$entryid = $_POST['entryid'];
$conn = new PDO('mysql:host=hostaddress;dbname=dbname', $username456, $password456);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tlo = $conn->query("SELECT * FROM entries WHERE entryID = {$entryid} ");
$tlo->setFetchMode(PDO::FETCH_ASSOC);
while($row = $tlo->fetch()) {
//loop stuff
}
I don't see how it's different from the code working on another page, however this is the error I keep getting thrown:
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 '' at line 1' in /homepages/11/d211013232/htdocs/WEBSITE/entry.php:54 Stack trace: #0 /homepages/11/d211013232/htdocs/WEBSITE/entry.php(54): PDO->query('SELECT * FROM e...') #1 {main} thrown in /homepages/11/d211013232/htdocs/WEBSITE/entry.php on line 54
Anyone know what it might be?
Remove the curly brackets around $entryid, and you need to close the string before concatenating variables:
$tlo = $conn->query("SELECT * FROM entries WHERE entryID = '" $entryid "' ");
Try changing this
$tlo = $conn->query("SELECT * FROM entries WHERE entryID = {$entryid} ");
to this
$tlo = $conn->query("SELECT * FROM `entries` WHERE entryID = '$entryid'");

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