Populate drop down form SQL server using PHP and HTML - php

Whenever I try to run the below code, I get the passed variable ". $record . " as it is.
I am trying to populate a drop-down from a database, but I keep getting a value which I am passing in the while loop.. I know I am making a simple mistake.Can someone please help to solve this issue
<select name="c" multiple="multiple">
<option>--select--</option>
<?php
$dbname = "abc";
$serverName = "xyz"; //serverName\instanceName
try
{
$connectionInfo = array( "Database"=>$dbname);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$SQL_string= "Select distinct [CC] from [abc].[dbo].
[abcdefg] ";
$stmt = sqlsrv_query($conn, $SQL_string);
$records[] = array();
while ($row = sqlsrv_fetch_array($stmt,
SQLSRV_FETCH_ASSOC))
{
$records[] = $row['CC'];
}
foreach ($records as $record)
{
echo' <option value="'. $record . '">' .$record.
'</option>';
}
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
catch(Exception $ex)
{
echo "Connection failed: " . $ex->getMessage();
}
?>

Here's an attempt at simplifying this a bit. I can't guarantee it will work, but it may bring to light the error you are facing:
<select name="c" multiple="multiple">
<option>--select--</option>
<?php
$dbname = "abc";
$serverName = "xyz"; //serverName\instanceName
try
{
$connectionInfo = array( "Database"=>$dbname);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$SQL_string= "Select distinct [CC] from [abc].[dbo].[abcdefg];";
$stmt = sqlsrv_query($conn, $SQL_string);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
echo '<option value="'.$row['CC'].'">'.$row['CC'].'</option>';
}
sqlsrv_free_stmt( $stmt);
}
catch(Exception $ex)
{
echo "Caught exception error: " . $ex->getMessage();
}
?>
</select>

Related

MS SQL statements work in DBeaver but not in PHP (with configuration and setup correct)

I have the following code to verify that my PHP-MS SQL connection and configuration are setup properly. I have about 100 getter functions that are all set up the same to retrieve info from this database:
function ms_getClientLN($repEnvKey) {
$repCustKey = '';
$serverName = "1.1.1.1\\EDGESQL"; //serverName\instanceName
$connectionInfo = array( "Database"=>"EDGESQL", "UID"=>"userid", "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));
}
$sql = "SELECT repCustKey FROM repair WHERE repEnvKey LIKE '$repEnvKey';";
//echo $sql . "<br>";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
} else {
#echo "0 results";
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$repCustKey = $row['repCustKey'];
}
sqlsrv_close( $conn );
//----------===== Get ClientLast from customer table =====----------
$serverName = "1.1.1.1\\EDGESQL"; //serverName\instanceName
$connectionInfo = array( "Database"=>"EDGESQL", "UID"=>"userid", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$clast = '';
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT cuLastName FROM customers WHERE cuKey LIKE '$repCustKey';";
//echo $sql . "<br>";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
} else {
#echo "0 results";
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$clast = $row['cuLastName'];
}
sqlsrv_close( $conn );
return $clast;
}
I then have the following function formatted exactly like the other working hundred that produces no results:
function ms_getRepairHistory($rhRepKey) {
$type = '';
$results[] = array();
$serverName = "1.1.1.1\\EDGESQL"; //serverName\instanceName
$connectionInfo = array( "Database"=>"EDGESQL", "UID"=>"userid", "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));
}
$sql = "SELECT rhWhen, rhWhereNext, rhNotes FROM RepairHistory WHERE rhRepKey LIKE '$rhRepKey';";
echo $sql . "<br>";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
} else {
echo "0 results<br>";
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results[] = $row;
}
sqlsrv_close( $conn );
return $row;
}
I'm even echoing the SQL command and can copy and paste it into DBeaver:
echo $sql . "<br>";
outputs:
SELECT rhWhen, rhWhereNext, rhNotes
FROM RepairHistory
WHERE rhRepKey LIKE '001-167896-001';
Which works in DBeaver with the
Databse.dbo.
prefix attached:

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

SQL query into option form

I have a PHP code to get info from my Microsoft SQL server 2014, but it isnt working, the page it self works fine since it pops up as it should when i comment out the PHP code, but as soon as the PHP code isnt commented out, its just all white, so im assuming problem with the PHP code. I have to get the results from the query out into a drop down menu.
i use this code:
$servername = "VCCSQL03";
$username = "forecast";
$password = "Telefon2";
$dbname = "Forecast";
$connectionInfo = array("Database"=>$dbname, "UID"=>$username, "PWD"=>$password);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if(!$conn) {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
// Check connection
$result = sqlsrv_query($conn,"SELECT * FROM dbo.vw_BrandProduct");
if ($result->num_rows > 0) {
// output data of each row
while($row = sqlsrv_fetch_array($result)) {
echo "<option value='".$row['Brand_ProductID']."' name='".$row['Brand_ProductName']."'</option>";
}
} else {
echo "";
}
sqlsrv_close();
First and foremost, you do not have an open and closed select tag, and your option tags was missing a > to close it properly. Try the below revision, assuming connection is established on the page properly then this should work.
$connectionInfo = array( "Database"=>$dbname, "UID"=>$username, "PWD"=>$password);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(!$conn) {
//// Check connection
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn,"SELECT * FROM dbo.vw_BrandProduct");
if ($result->num_rows > 0) {
// output data of each row
echo "<select name='products'>";
while($row = sqlsrv_fetch_array($result)) {
echo "<option value='".$row['Brand_ProductID']."'>$row['Brand_ProductName']</option>";
}
echo "</select>";
} else {
echo ""; } sqlsrv_close(); ?>

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.

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