Show all database in sqlsrv by php - php

I want to display all databases in microsoft sql srv for admin panel, but i have problem with get value. I'm try with query:
EXEC sp_databases
This query is executed successfully in sql srv, but when i'm try make this same by PHP, im not see value, no any errors or warnings, return null
My PHP Code:
<?php
$serverName = $_POST['hostname'];
$uid = $_POST['username'];
$pwd = $_POST['password'];
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd);
$connsrv = sqlsrv_connect( $serverName, $connectionInfo);
if($connsrv == TRUE ){
echo "connected";
$tsql = "EXEC sp_databases";
$stmt = sqlsrv_query( $connsrv, $tsql);
while( $row = sqlsrv_fetch_array($stmt)){
echo $row['DATABASE_NAME'];
}
}else{
echo "no connect";
}
?>
I don't know why I not see any result - any suggestions ? :(

One possible explanation for this unexpected behaviour is that CREATE DATABASE or ALTER ANY DATABASE or VIEW ANY DEFINITION permissions are requied to run the sp_databases stored procedure (I can reproduce this with a server login, which has only public role). Set the needed permissions for the connection user, or as another option, try to use the sys.databases system view.
<?php
// Connectuion
$serverName = $_POST['hostname'];
$uid = $_POST['username'];
$pwd = $_POST['password'];
$connectionInfo = array("UID" => $uid, "PWD" => $pwd);
$connsrv = sqlsrv_connect($serverName, $connectionInfo);
if ($connsrv === false){
echo "Not connected";
exit;
}
// sp_databases
echo "Connected. EXEC sp_databases: "."<br>";
$tsql = "EXEC sp_databases";
$stmt = sqlsrv_query( $connsrv, $tsql);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while( $row = sqlsrv_fetch_array($stmt)){
echo $row['DATABASE_NAME']."<br>";
}
sqlsrv_free_stmt($stmt);
// sys.databases
echo "Connected. SELECT * FROM sys.databases: "."<br>";
$tsql = "SELECT * FROM sys.databases";
$stmt = sqlsrv_query( $connsrv, $tsql);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while( $row = sqlsrv_fetch_array($stmt)){
echo $row['name']."<br>";
}
sqlsrv_free_stmt($stmt);
// End
sqlsrv_close($connsrv);
?>

Related

how to get the while loop three different variable into the json array

actually i try to write the program from get the ms sql data select and then selected data insert to the MySQL table.i write the program which one get the final value of the table. because insert query place out side the while loop.how do i get the all the value in to the insert query??
I think can store in the while loop execution data json array.can i retrieve the one by one?
MSSQL DB connection
<?php
$serverName = "servername"; //serverName\instanceName,
portNumber (default is 1433)
$connectionInfo = array( "Database"=>"Databasename",
"UID"=>"username", "PWD"=>"Password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
/*echo "Connection established.<br />";*/
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
test.php
<?php
require_once ('inc/MSSQL_connection.php');
//require_once ('inc/MYSQL_connection.php');
$query ="SELECT EnrolledID,Date,Time FROM dbo.view_attendance
ORDER BY Date,Time";
$result = sqlsrv_query($conn,$query);
if ($result == FALSE){
die(FormatErrors(sqlsrv_errors()));
}
else{
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$emp_no = $row['EnrolledID'];
$date = date_format($row['Date'], 'Y-m-d');
$time = date_format($row['Time'], 'H:i:s');
}
//echo $emp_no;
$conn = mysqli_connect("localhost", "root", "","kelaniya");
$query = "INSERT INTO attendancedata (EnrolledID,Date,Time) VALUES ('{$emp_no}', '{$date}', '{$time}')";
mysqli_query($conn, $query);
}
?>
IMHO you can just move insert into while loop, why not?:
<?php
require_once ('inc/MSSQL_connection.php');
//require_once ('inc/MYSQL_connection.php');
$query ="SELECT EnrolledID,Date,Time FROM dbo.view_attendance
ORDER BY Date,Time";
$result = sqlsrv_query($conn,$query);
if ($result == FALSE){
die(FormatErrors(sqlsrv_errors()));
}
else{
$conn_insert = mysqli_connect("localhost", "root", "","kelaniya");
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$emp_no = $row['EnrolledID'];
$date = date_format($row['Date'], 'Y-m-d');
$time = date_format($row['Time'], 'H:i:s');
//echo $emp_no;
// MySQLli
$stmt = $conn_insert->prepare('INSERT INTO attendancedata (EnrolledID,Date,Time) VALUES (?,?,?)');
// I insert as string as was in original question (table metadata was not given...)
$stmt->bind_param('sss', $emp_no, $date, $time ); // 's' specifies the variable type => 'string'
$stmt->execute();
}
}
?>

I'm trying to display rows in SQL Server with php

the response i get after making connection and running the query is "resource(4) of type (SQL Server Connection)"
<?php
$serverName = "xx.xx.xx.xx";
$uid = "sa";
$pwd = "xxxxxxxxxx";
$databaseName = "courierdb";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$databaseName);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
var_dump($conn);
/* Execute the query. */
$sql = "SELECT * FROM dbo.AwbDomestics";
$stmt = sqlsrv_query( $conn, $sql);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
if (sqlsrv_has_rows($stmt)) {
echo "row:<br>"; var_dump($row); echo "<br><br>";
}
else {
echo "<br/>No Results were found.";
}
}
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
how do i select all the rows in the database without this "resource(4) of type (SQL Server Connection). Any help is much appreciated.
The if (sqlsrv_has_rows($stmt)) test should be around the loop, not inside it.
if (sqlsrv_has_rows($stmt)) {
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
echo "row:<br>"; var_dump($row); echo "<br><br>";
}
else {
echo "<br/>No Results were found.";
}
}
To check for errors from the query, you should check if $stmt is FALSE, not $conn. So change
if ($conn == false)
to
if (!$stmt)
You may try with this script. Using sqlsrv_has_rows() is not necessary. Use sqlsrv_fetch_array() or sqlsrv_fetch()/sqlsrv_get_field() to retrieve data.
<?php
/* Warnings */
sqlsrv_configure("WarningsReturnAsErrors", 1);
/* Connection */
$serverName = "xx.xx.xx.xx";
$uid = "sa";
$pwd = "xxxxxxxxxx";
$databaseName = "courierdb";
$connectionInfo = array(
"UID" => $uid,
"PWD" => $pwd,
"Database" => $databaseName
);
$conn = sqlsrv_connect(
$serverName,
$connectionInfo
);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
/* Execute the query with sqlsrv_fetch_array(). */
$sql = "SELECT * FROM dbo.AwbDomestics";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
//print_r($row, true);
foreach($row as $field => $value) {
echo $field.": ".$value." ";
}
echo "\n";
}
/* Execute the query with sqlsrv_fetch()/sqlsrv_get_field(). */
$sql = "SELECT * FROM dbo.AwbDomestics";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$fc = sqlsrv_num_fields($stmt);
while (sqlsrv_fetch($stmt)) {
for($i = 0; $i < $fc; $i++) {
echo sqlsrv_get_field($stmt, $i, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR))." ";
}
echo "\n";
}
/* End */
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>

How to read from Firebird database and insert the data into MSSQL database?

I want to select some columns from Firebird database and insert them in MSSQL database tables.
When I read the table from Firebird it represent exactly what I need in the localhost, then when I want to insert the data into MSSQL it only inserts the last record. I don't know what cause this, and it's my first time to try this idea.
Would someone tell me what goes wrong?
This is my PHP code:
<?php
$host = 'localhost:c:\firebird.fdb';
$username='';
$password='';
$dbh = ibase_connect($host, $username, $password);
$stmt = "SELECT * FROM TWEEKDAY";
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
$R1 = $row->CODE;
$R2 = $row->DAYNAME;
echo $R1 ." ". $R2 . "\n";
echo "</br>";
}
ibase_close($dbh);
/**********************************************/
$host = "servername\instancename";
$connectionInfo = array( "Database"=>"MSSQLdatabase", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1','$R2')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $obj = sqlsrv_fetch_object( $stmt , SQLSRV_FETCH_ASSOC) ) {
echo $obj->DAYID ."&nbsp ". $obj->DAYN . "<br />";
}
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
When i run my code, it shows in local host as :PIC1
and when i open the mssql database that what the table have:PIC2
it seems like it insert the last value of $R1 $R2.
and when i use this code:
<?php
$host = 'localhost:c:\FIREBIRD.fdb';
$username='';
$password='';
$dbh = ibase_connect($host, $username, $password);
$stmt = "SELECT * FROM TWEEKDAY";
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
$R1 = $row->CODE;
$R2 = $row->DAYNAME;
echo $R1." ". $R2 . "\n";
echo "</br>";
}
ibase_close($dbh);
/**********************************************/
$host = "SERVERNAME\INSTANCENAME";
$connectionInfo = array( "Database"=>"AccessCard", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
for ($RIdx = 0; $RIdx < count($R1); $RIdx++) { // each $R array value
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1[$RIdx]','$R2[$RIdx]')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
} // end of insert loop
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
This is what show in the database:PIC3
$R1 should be an array, as in $R1[] = $row->CODE; Also $R2' obviously. Change your sqlserver insert accordingly. I don't have sql server installed here so i cannot provide tested code.
Here is the sql server code...
$host = "servername\instancename";
$connectionInfo = array( "Database"=>"MSSQLdatabase", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
for ($RIdx = 0; $RIdx < count($R1); $RIdx++) { // each $R array value
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1[$RIdx]','$R2[$RIdx]')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
} // end of insert loop
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
Finaly the problem solved:
here is the solution code
<?php
$host = 'localhost:c:\firebird.fdb';
$username='';
$password='';
$dbh = ibase_connect($host, $username, $password);
$stmt = "SELECT * FROM TWEEKDAY";
/**********************************************/
$host = "servername\instancename";
$connectionInfo = array( "Database"=>"AccessCard", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
/**********************************************/
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
$R1 = $row->CODE;
$R2 = $row->DAYNAME;
echo $R1." ". $R2 . "\n";
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1','$R2')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $obj = sqlsrv_fetch_OBJECT( $stmt) ) {
echo $obj->$R1."&nbsp ". $obj->$R2. "<br />";
$obj++;
}
echo "</br>";
}
ibase_close($dbh);
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
thank you Ryan for your help, it seems that the solution came to my mind while i'm editing my question.
thanks again.

update user details, sql server 2008 sqlsrv

Hello i am having some trouble getting a script to run, i keep getting an error message saying it expects two parameters and i have no idea how to fix it, heres the script:
<?php
session_start ();
if(isset($_SESSION['user'])){
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
$oldpassword = $_POST['oldpassword'];
$newpassword = $_POST['newpassword'];
$serverName = "server";
$connectionInfo = array("Database"=>"database","UID"=>"id", "PWD"=>"pass");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false){
echo "Error in connection.\n";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "SELECT userPass FROM customers WHERE userName='$username'";
$stmt = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => 'static' ));
if ( !$stmt ){
die( print_r( sqlsrv_errors(), true));
}
$rows = sqlsrv_num_rows($stmt);
if($rows === false){
die( print_r( sqlsrv_errors(), true));
}elseif($rows == 0){
echo "No rows returned.";
exit();
}else{
$querychange = sqlsrv_query("UPDATE customers SET userPass='$newpassword' WHERE userName='$username'");
session_destroy();
die ("Your password has been changed. <a href='index.php'>Return</a> to the main page and login with your new password.");
}
}
}
?>
I keep getting this error
PHP Warning: sqlsrv_query() expects at least 2 parameters, 1 given in file_name.php on line 27
Line 27 is where i update customers. If anyone can spot an error in the script can you let me know, also yes I've not done SQL injection, at this stage I'm simply trying to get it working before I implement that.
Thanks for all the help, it's much appreciated
Try passing connection to sqlsrv_query
something like:
$querychange = sqlsrv_query($conn, "UPDATE customers SET userPass='$newpassword' WHERE userName='$username'");

Not getting anything back from sqlsrv_num_rows

I'm trying pull back data from MS SQL via a php page. I have got a valid connection, and am trying a simple SELECT * FROM MyTable but sqlsrv_num_rows is just blank no matter what I do!!!
Here is my code:
function connect() {
$serverName = DB_HOST; //serverName\instanceName
$connectionInfo = array( "Database"=>DB_NAME, "UID"=>DB_USER, "PWD"=>DB_PASSWORD);
$this->connection = sqlsrv_connect( $serverName, $connectionInfo);
sqlsrv_connect( $serverName, $connectionInfo);
if( $this->connection ) {
echo "<br>Connection established.<br />";
}else{
echo "<br>Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
}
The echo for Connection established is working so all AOK there!
Now when I do a simple query:
function query($sql) {
if ($this->debug) {
echo $sql . "<br />";
}
$this->sql = $sql;
$this->recordset = sqlsrv_query($this->connection, $sql);
if (!$this->recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_errors());
}
echo "<br>rows = " . sqlsrv_num_rows($this->recordset);
I get absolutely nothing from the above echo? Any reason why? Or can you suggest a new echo I can try to debug this?
All my code in my DB class is converted from mysql so there may be a few bits wrong that is doing the damage!
I've even tried a super simple version, all the code together and it's still blank/false:
$server = DB_HOST;
$conn = sqlsrv_connect( $server, array( "Database"=>DB_NAME, "UID"=>DB_USER, "PWD"=>DB_PASSWORD) );
$stmt = sqlsrv_query( $conn, "SELECT * FROM MyTable");
$row_count = sqlsrv_num_rows($stmt);
echo "<br>row count = " . $row_count;
if ($row_count === false)
echo "\nerror\n";
else if ($row_count >=0)
echo "\n$row_count\n";
die;
Try this.....
Replace below statement
sqlsrv_query( $conn, "SELECT * FROM MyTable");
as
sqlsrv_query( $conn, "SELECT * FROM MyTable", array(), array("Scrollable"=>"buffered"));

Categories