I am trying to connect to MSSQL in PHP using sqlsrv api. When I run phpinfo(), it shows an a section for sqlsrv. But while actually writing code, I cannot connect to MSSQL. I am using SQL Server R2. I connect to the database from the Management Studio using the specified hostname. Here is the code:
<?php
$serverName = "TEST-PC\SQLEXPRESS";
$databaseName = "TestDB";
$connectionInfo = array("Database"=>"$databaseName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ){
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
else{
echo "Connection created";
}
$tsql = "SELECT * FROM Test";
$result = sqlsrv_query($conn, $tsql);
echo "Rows returned: ".sqlsrv_num_rows($result);
sqlsrv_close();
?>
The code prints NOTHING on the page, not even any error message. Here is the entries in php.ini file:
extension=php_sqlsrv_53_ts_vc9.dll
extension=php_pdo_sqlsrv_53_ts_vc9.dll
Any help please?
Since you did not pass a user or password, the driver is trying to connect via Windows Authentication. By running PHP from IIS, it will connect with the credentials of what whatever user IIS is running under (such as NT AUTHORITY\IUSR). You need to add the IIS user to the list of allowed logins to SQL Server, and then add a user associated with that login to the database.
Did you mean to put "$connectionOptions" where you have "$connectionOptions"?
Turn on error_reporting for php for more verbose output.
[EDIT]
A few possibile solutions:
Check your Connection String properties for the MSSQL Database you're connecting to (i.e. are you matching the values exactly, or can you use (local)
It's possible the User you're logged in on doesn't have proper access to the database. That sounds like an oversimplification, but check out your IIS settings, as well as FastCGI.impersonate settings. Turn on IIS Windows Authentication settings in IIS, and fastcgi.impersonate = 1. There's a thorough article about this potential issue here: http://blogs.msdn.com/b/brian_swan/archive/2010/02/10/sql-server-driver-for-php-understanding-windows-authentication.aspx
It is because sqlsrv_query() uses SQLSRV_CURSOR_FORWARD cursor type by default. However, in order to get a result from sqlsrv_num_rows(), you should choose one of these cursor types below:
SQLSRV_CURSOR_STATIC
SQLSRV_CURSOR_KEYSET
SQLSRV_CURSOR_CLIENT_BUFFERED
For more information, check: Cursor Types (SQLSRV Driver)
In conclusion, Try this Code:
$tsql=sqlsrv_query("SELECT * FROM Test");
$row_count = sqlsrv_num_rows($tsql);
echo $row_count;
Related
I am having connection issues when trying to connect from a PHP script to a SQL server database.
I have used the PDO method - My script can be seen below, connecting using Windows authentication, the object referenced in my script has been created in the database, roles and permissions have been defined.
I am testing locally using WAMP, calling a simple file called insert.php from the webroot.
My SQL server is installed on the same machine and my SQL version is 2012.
The script when executed should simply echo the results of the PATIENT table to the screen for now.
In both of my Apache and PHP versions of the php.ini file i have added the necessary extension to use the sqlsrv drivers and installed all the of the necessary drivers.
Yet still I get the error:
could not find driver1
The script:
<?php
try
{
$conn = new PDO("sqlsrv:Server=localhost ;Database=MindTrackDb", "", "");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e)
{
die( print_r( $e->getMessage() ));
}
$tsql = "SELECT * FROM PATIENT";
$getResults = $conn->prepare( $tsql);
$getResults->execute();
$results - $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row) {
echo $row['PATIENT_ID'].''.$row['FORENAMES'].''.$row['SURNAME'].''.$row['EMAIL'];
echo '<br>';
}
?>
My question is 2 part really:
A) Is this the best method to communicate to a SQL server database with PHP or is there a better method?
B) What could the driver error possibly be - I have followed various suggestions from here and nothing has worked.
I am attempting to write some connection code with PHP to a Oracle database my school is hosting.
I'm using oci_connect() at the moment to make this connection, but it is failing.
$conn = oci_connect('username', 'password', 'hostname/SID');
I can access the oracle database through sqlDeveloper, as well as phpmyadmin, so I know the login information is correct.
I checked the oracle version with select * from v$version;, it shows as 12c Enterprise.
What is wrong with my php code for connecting? Is there a better way to make an oracle connection through PHP?
This is the test code I'm running, from http://php.net/manual/en/function.oci-error.php
<?php
echo "running";
$conn = oci_connect("username", "paswwrod", "address/SID");
if (!$conn) {
$e = oci_error(); // For oci_connect errors do not pass a handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
echo "ending";
?>
The string "running" gets echoed, but "ending" does not, the script just stops working when it attempts oci_connect()
have you also tried including the port number to the oracle db server like so?
$conn = oci_connect("user", "pass", "localhost:1234/xe");
i just wanted to insert data into database from a form, with php. i ran the code below in my Localhost using XAMPP and everything was fine but where i upload it to my host it didn't work.
Question is What shold i put for $servername and when should i look for it ?
There is my codes:
Register.php (in localhost)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$Name = $_POST['Name'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header("Location:#");
}
//Inserting Data
try{
$sql = "INSERT INTO User (uName , uUsername , uPassword , uEmail) VALUES ('$Name' , '$Username' , '$Password' , '$Email')";
mysqli_query($conn, $sql);
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$conn->close();
header("Location:#");
}
?>
If your MySQL database is on the SAME SERVER as your PHP script, then the usual logical approach is that your host is localhost. The same as you used on your local computer -- because they're on the same machine.
However, if your MySQL database is on ANOTHER SERVER seperate from your PHP scripts the you will need to access that server using a web address for your PHP to connect to yout MySQL.
We can't tell you what that is, and your server hosts (of your MySQL server) will be able to tell you and provide you with the correct login credentials.
I believe it would be more usual for MySQL and PHP to be on the same disk, especially for non-professional systems as your appears to be, so then the issue would be:
Are your login details set up correcty on your server? (same username/password)
Are there any MySQL errors or PDO errors (if you connect with PDO). Don't redirect on error, but instead output the error to a log file so you can read WHY the MySQL in your code didn't connect.
It is still possible for you to set your PHP to communicate with your localhost MySQL via a remote address (such as servername=$_SERVER['SERVER_NAME'];). (see note below)
Many online accounts (in things such as CPanel) will block you from accessing the MySQL as a root or at least will not give you the root MySQL password. Using root to access MySQL via PHP is NOT a good idea and you should instead set up a specific MySQL user for your PHP with only enough privileges that you need to read/write to the DB, and nothing more.
If your MySQL is remote (not localhost) then you may also need to supply a Port Number with the connection details. Usual port numbers are 3306 but this is something you'd need to know from your server hosts.
Immediately after a header(Location:); redirection instruction you should always set die(); or exit to stop PHP processing the rest of the script.
Your SQL insert data is highly suseptible to SQL injection and other SQL attacks and compromise. You should really, REALLY look into using MySQL Prepared Statements, you're already coding in OO style so you're almost there already.
Example remote connection from the manual
<?php
/***
* Remember 3306 is only the default port number, and it could be
* anything. Check with your server hosts.
***/
$conn = new mysqli('remote.addr.org.uk', 'username', 'my_password', 'my_databasa', '3306');
/***
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
***/
if ($conn->connect_error) {
error_log('MySQL Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
/***
* Upon failure, the above will output a connection error notice such as
* user not found or password incorrect. It won't explicity say these
* things but you should be able to deduce which from the notice
***/
echo "Success... \n" . $conn->host_info ;
$mysqli->close();
# : I seem to think that MySQL detects when the remote address given is the same as the server address and auto converts it to localhost, but I'm not sure on this.
The long and the short of it is that if your MySQL is on the same
server as your PHP it makes no sense to open up a network loop to send
data out just to get it back again. Use localhost instead.
I asked my host service providers about the "$servername" and they answered me that the "$serverneme" is localhost.
I am trying to connect to a MySQL server using PHP's 'mysql_connect()' function, but the connection fails. This is my code:
$con = mysql_connect("example.net", "myusername","") or die("Could not connect: ".mysql_error());
I placed this code inside a PHP script, which I try to open using a web browser (the script is stored on a remote host which has PHP enabled) but it doesn't work. It doesn't return the die error either. Echoing something before the $con successfully outputs in the browser, whereas nothing outputs after that line. If I type:
mysql -h example.net -u myusername
from a remote machine, I could connect to the DB without any problem and do queries and other modifications.
Update :
I also tried this after some suggestion, but no improvement:
<?php
$usern = "myusername";
$dbh = new PDO('mysql:host=servername.net;dbname=test', $usern, "");
echo $usern;
?>
What operating system is the remote host running PHP using? Perhaps MySQL isn't enabled in php.ini. Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
Have you tried using PDO or the MySQLi interface? If you're trying to learn PHP, you should not be using the mysql_* functions regardless. See if you can access the database by using a line similar to this:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
If you need more detailed documentation, this code comes directly from the documentation itself.
EDIT: Also, try using PDO's error checking functionality. This example creates a database connection using PDO and tries to perform a simple query. It doesn't use prepared statements or any of those features, so it's not production-ready code (i.e. *don't just throw this into your code without understanding how to improve it) and you'll need to edit it to include a SELECT query that's relevant to your database, but it should at least tell PDO to provide more information about the errors it encounters.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM booksa";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo()));
$r = $q->fetch(PDO::FETCH_ASSOC);
print_r($r);
?>
Is the php file located on the same server as the mysql database, if so you might have to use 'localhost' as the first argument for mysql_connect() instead the external address.
I have PHP sample code which will fetch the data from the MYSQL database through ODBC driver on Linux(CentOS) machine.
I have created DSN and same able to connect through following command
isql -v
But when i try to same DSN through PHP code i am getting "No tuples available at this result index" due to which unable to read the data from database through PHP APACHE configuration.
If anyone provides the solution,It will more helpful for me to proceed further.
Below are my sample code and other details,Please correct if anything wrong on below configuration details-
Below is sample PHP code:
<?php
$conn = odbc_connect("DSN", "username", "password");
$sql = 'select * from tablename';
$rs = odbc_exec($conn,$sql);
echo "<table><tr>";
echo "<th>User Name</th></tr>";
while(odbc_fetch_row($rs)) {
$user = odbc_result($rs,"fieldname");
echo "<tr><td>$user</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
Below is odbc.ini file:
[DSN]
Description = MySQL ODBC Database
DRIVER = MySQL
TraceFile = /tmp/odbcerr.log
SERVER = 127.0.0.1
PORT = 3306
USER = username
PASSWORD = password
DATABASE = database
OPTION = 3
SOCKET = /var/lib/mysql/mysql.sock
Below is odbcinst.ini file:
[MySQL]
Description = ODBC for MySQL
Driver = /usr/lib/libmyodbc5.so
Setup = /usr/lib/libodbcmyS.so
FileUsage = 1
UsageCount = 3
The comments in the documentation for odbc_connect suggest that this can be caused by using an incorrect cursor type. Try each of the three possible values as the fourth argument: SQL_CUR_USE_IF_NEEDED, SQL_CUR_USE_ODBC, or SQL_CUR_USE_DRIVER.
I am very curious as to why you're using ODBC to connect to MySQL. PHP has many better ways to read from MySQL, including the excellent PDO class (which itself can connect via ODBC if needed).