PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label sqlsrv. Show all posts
Showing posts with label sqlsrv. Show all posts

Saturday, July 2, 2022

[FIXED] How do I display SQL Server table data using PHP?

 July 02, 2022     php, sql-server, sqlsrv, xampp     No comments   

Issue

I'd like to start displaying some data from a sql server database I work with using PHP. I believe my connection to the database is working but I can't get any data from the Facility table to display in the browser. I've been using an Apache server through XAMPP to run PHP(PHP version 8.0). The SQL server(version 2012) is on another machine in the building. So far I have:

  1. Downloaded the sqlsrv extension files called, "php_sqlsrv_80ts.dll", and "php_sqlsrv_80_ts.dll". Both are in my XAMPP php.ini file as new extensions (see below) enter image description here
  2. Restarted my Apache and MySQL servers after adding the two new extensions.
  3. Tested my connection and tried displaying some results using the code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MSSQL Connection Test</title>
</head>
<body>
    <?php
        $serverName = "###"; //serverName\instanceName
        $connectionInfo = array( "Database"=>"UTRBDMSNET", "UID"=>"###", "PWD"=>"###");
        $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));
        }

        $query = "SELECT * FROM Facility;";
        $result = sqlsrv_query($conn, $query);
        $resultCheck = sqlsrv_num_rows($result);

        if ($resultCheck > 0) {
            while ($row = sqlsrv_fetch_assoc($result)) {
                echo $row['Operator'] . "<br>";
            }
        }
    ?>
</body>
</html>

When I go to the file in my browser I get this message, "Connection established". I don't see anything in the console. It's hard to tell what's going wrong without any error messages. Ideally, I would like to display something from any of the tables in my database to see if things are working.


Solution

After looking at the two links @cottton posted, I was able to query some data from the database. I found a couple of issues with my code:

  1. It doesn't seem to like when I use * in my SQL query. If I specify what column I want to see and tell it to echo the first row in the table, like this, SELECT Operator FROM Facility, it works fine. When I say SELECT * FROM Facility and specify the column in the echo statement it gives me this error:

"Warning: Undefined array key "Operator" in C:\Users###\Documents\GitHub_Repos\Utah_OG_Website\MSSQLQueryTest.php on line 58".

  1. I needed to use sqlsrv_fetch_array and SQLSRV_FETCH_NUMERIC in a while statement. NOTE - It only accepts upper-case SQLSRV_FETCH_NUMERIC vs sqlsrv_fetch_numeric.
  2. If I use if ($resultCheck > 0) {} it won't show me any results. I'm assuming it's something related to the type of data being returned, not completely sure yet.

Here's the working piece of code for comparison:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MSSQL Connection Test</title>
</head>
<body>
    <?php
        $serverName = "###"; //serverName\instanceName
        $connectionInfo = array( "Database"=>"###", "UID"=>"###", "PWD"=>"###");
        $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));
        }

        $query = "SELECT Operator FROM Facility;";
        $result = sqlsrv_query($conn, $query);
        $resultCheck = sqlsrv_num_rows($result);

        while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) {
            echo $row[0] . "<br>";
        }
    ?>
</body>
</html>



Answered By - Hiebs915
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 12, 2022

[FIXED] Dynamic doctrine database connection

 March 12, 2022     php, sql-server, sqlsrv, symfony     No comments   

Issue

I have a project of an monitoring application under symfony 5.

Currently I've done most of the work working with a single database containing logs from another application. What I'm looking to do now is to be able to connect dynamically to a database (MSSQL). For the moment the connection to the database is done via the file "doctrine.yaml".

Doctrine.yaml

 doctrine:
  dbal:
   default_connection: default
    connections:
     default:
       driver: pdo_sqlsrv
       host: 192.168.1.33
       port: null
       dbname: 'job'
       user: 'sa'
       password: 'Lasernet@2020'
       charset: utf8mb4

   orm:
    default_entity_manager: default
    entity_managers:
     default:
       connection: default
       mappings:
        Main:
         is_bundle: false
         type: annotation
         dir: "%kernel.project_dir%/src/Entity/Main"
         prefix: 'App\Entity\Main'
         alias: default

I did this for the dynamic connection

DynamicConnection.php

<?php

namespace App\Doctrine;


class DynamicConnection {


    public function __construct($dbname,$user,$password,$host,$driver,$port)
    {
        $this->dbname = $dbname;
        $this->user = $user;
        $this->password = $password;
        $this->host = $host;
        $this->driver = $driver;
        $this->port = $port;

    }

    public function changeDatabase(){



        $connectionParams = array(
            'dbname' => $this->dbname,
            'user' => $this->user,
            'password' => $this->password,
            'host' => $this->host,
            'driver' => $this->driver,
            'port' => $this->port
        );

        $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
    
        if($conn){
            return $conn;
        }else{
            return "no";
        }

    }


    public function getParams()
    {
        $connectionParams = array(
            'driver' => $this->driver,
            'host' => $this->host,
            'port' => $this->port,
            'dbname' => $this->dbname,
            'user' => $this->user,
            'password' => $this->password,
            'charset' => "utf8mb4",
            'driverOptions' => [],
            'defaultTableOptions' => []
        );

        return $connectionParams;
    }

}

And in my Controller

/**
 * @Route("/testconnection", name="test_connect")
 */
public function testConnection(){


    $dbname = "job";
    $user = "sa";
    $password = "Lasernet@2020";
    $host = "192.168.1.34";
    $driver = "pdo_sqlsrv";
    $port = null;

    $connection = new DynamicConnection($dbname,$user,$password,$host,$driver,$port);
    $params = $connection->getParams();


    $newEm = EntityManager::create($params,$this->em->getConfiguration(), $this->em->getEventManager());


    $job = $newEm->getRepository(Job::class)->findAll();
    dd($job);
        
}

The problem is that the findAll() returns all the records of the database "192.168.1.33" not the one of "192.168.1.34" which behaves a different number of records.

Is there another way to connect dynamically to the database or to modify the "doctrine.yaml" file directly using JS for example, but I don't think this is the best solution.

If someone has a solution to my problem to make my findAll() return the info from the 192 database .168.1.34

Small precision the two databases have the same structure of tables, fields, etc.


Solution

I had a very similar issue recently. The solution that worked for me was a wrapper class.

<?php

declare(strict_types=1);

namespace App\DBAL;

use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;

final class MultiDbConnectionWrapper extends Connection
{
    public function __construct(
        array $params,
        Driver $driver,
        ?Configuration $config = null,
        ?EventManager $eventManager = null
    ) {
        parent::__construct($params, $driver, $config, $eventManager);
    }

    public function selectDatabase(string $dbName): void
    {
        if ($this->isConnected()) {
            $this->close();
        }

        $params = $this->getParams();
        $params['dbname'] = $dbName;
        parent::__construct($params, $this->_driver, $this->_config, $this->_eventManager);
    }
}

If you want to change a db host, change $params['host'] = 'XX.XX.XXX.XXX';

# config/packages/doctrine.yaml
doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'
        wrapper_class: App\DBAL\MultiDbConnectionWrapper
class ProductController extends AbstractController
{
    private EntityManagerInterface $em;
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
    public function add(Request $request): JsonResponse
    {
        $connection = $this->em->getConnection();
        if(!$connection instanceof MultiDbConnectionWrapper) {
            throw new \RuntimeException('Wrong connection');
        }

        $databaseName = 'some_db_name';
        $connection->selectDatabase($databaseName);

You can find full implementation in this repo.



Answered By - Karol Dabrowski
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 29, 2022

[FIXED] How to call a stored procedure in CodeIgniter USING SQL SERVER

 January 29, 2022     codeigniter, php, sql-server, sqlsrv, stored-procedures     No comments   

Issue

I'm bulding my application using Codeigniter and SQL server as my database (I am using the SQLSRV PHP extension to connect to SQL ). The problem happens when I try to call Stored Procedures:

$query = $this->db->query(
          "EXECUTE verificacion_fechas '".$codigo."',".$estado.",'".$llave_maestra."','".$fecha_actual."'"); 

Another way I have tried to create the query with less data is the following , however, it is generating an error:

Error Number: 01000 [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Ejecutando SQL directamente, sin cursor. EXECUTE provando15 34,2,'key05','2015-07-22'

I dont really know what im doing wrong. Can someone please help me?


Solution

remove the word Execute and it will work.

$query = $this->db->query(
      "verificacion_fechas '".$codigo."',".$estado.",'".$llave_maestra."','".$fecha_actual."'");


Answered By - steve
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing