I am trying to use PHP to select values from a SQL Server DB and assign values to specific parameters.
The table I am selecting from looks like this:
**ColumnName1 ColumnName2**
DataRow1Col1, DataRow1Col2
DataRow2Col1, DataRow2Col2
DataRow3Col1, DataRow3Col2
DataRow4Col1, DataRow4Col2
I am trying to create a variable that will be equal to DataRow3Col2 which always has a ColumnName1 = DataRow3Col1.
Is this possible?
Here is what I have so far:
$sql = "SELECT * FROM Table where id = {$ID}";
$stmt = sqlsrv_query( $trpConn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$data = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$data[] = $row;
}
sqlsrv_free_stmt( $stmt);
Thank you
$sql = "SELECT * FROM Table where id = {$ID}";
$stmt = sqlsrv_query( $trpConn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$data = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$data[$row['ColumnName1']] = $row['ColumnName2'];
}
sqlsrv_free_stmt( $stmt);
extract($data);
echo $DataRow1Col1;
// The Output is: DataRow1Col2
Related
I pull data from the mssql database. I want to assign the data I have captured as an array. So I want to assign more than one table value to the result. Currently, it only assigns 1 value. When I make $ results [], I can't print. I converted it to an array so I can assign more than one data, but it doesn't work.
<?php
...
$conn = sqlsrv_connect( $serverName, $connectionInfo );
$sql = "...";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array($stmt) ) {
$destekCevap = $row['destekcevap_..'];
$destekCevapFoto = $row['destekcevap_...'];
$results = Array("destekcevap_.." => $destekCevap, "destekCevapFoto" => $destekCevapFoto);
}
echo json_encode($results);
sqlsrv_free_stmt($stmt);
?>
Initialize the array above the while-loop and assign new values in the loop like this:
$results = array();
while( $row = sqlsrv_fetch_array($stmt) ) {
$destekCevap = $row['destekcevap_..'];
$destekCevapFoto = $row['destekcevap_...'];
$results[] = "your values";
}
Cheers,
Niklas
I'm pulling data from mssql. The data I have captured is more than one. It only records one data to Array. As you can see in the photo, there is more than one content with soru_tur = 1. How can I save soru_baslik and soru_icerik data to array? I show the data I have captured in my swift application. A database screenshot has been added with the var_dump output.
" json["soru_baslik"] " >> I want to print it out from swift. The screenshot of the output is as follows
<?php
...
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$json = file_get_contents('php://input');
$sql = "SELECT soru_baslik, soru_icerik FROM ... WHERE soru_tur = 1";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$soruArray = array();
$soruicerikArray = array();
$array = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results[] = Array("soru_baslik" => $row['soru_baslik'], "soru_icerik" => $row['soru_icerik']);
}
//var_dump($array);
echo '<pre>'; print_r($results); echo '</pre>';
sqlsrv_free_stmt( $stmt);
?>
If I understand your question correctly, one issue with your code is that you are initializing the $result variable on each iteration. You need to initialize this variable once and then append items on each iteration. You may try with the following approaches:
Example 1 (fetch only two specific columns):
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$json = file_get_contents('php://input');
$sql = "SELECT soru_baslik, soru_icerik FROM ... WHERE soru_no = 1";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$results = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results[] = array(
"..._baslik" => $row['..._baslik'],
"s..._icerik" => $row['..._icerik']
);
}
header("Content-Type: application/json");
echo json_encode($results);
sqlsrv_free_stmt( $stmt);
?>
Example 2 (fetch all columns):
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$json = file_get_contents('php://input');
$sql = "SELECT soru_baslik, soru_icerik FROM ... WHERE soru_no = 1";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$results = array();
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$a = array();
foreach($row as $column => $value) {
$a[$column] = $value;
}
$results[] = $a;
}
header("Content-Type: application/json");
echo json_encode($results);
sqlsrv_free_stmt( $stmt);
?>
My json code doesn't display anything, I have already tried many codes but nothing has helped.
include('connect.php');
$sql = "SELECT * FROM items";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) //this loop is working
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
}
$json = array();
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
echo json_encode($json); //empty?!
sqlsrv_free_stmt( $stmt);
There are numerous likely issues with this:
1) Have you checked your query actually returns rows?
2) You're looping your data twice (two while( $row = sqlsrv_fetch_array... loops) which is not useful or efficient.
3) the do...while ( sqlsrv_next_result($stmt) ); clause should be unnecessary as well, as fetch_array will know when it's got to the end of the data, and you've only got one resultset, so you don't need to move between them
4) you're echoing raw data as well as JSON, so if you make an ajax call to this script it'll fail because the response will partly contain non-JSON data
I think this will be sufficient to get you some sensible data:
include('connect.php');
$sql = "SELECT * FROM items";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$json[] = $row;
}
echo json_encode($json);
If THIS works:
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) //this loop is working
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
}
the rest must work too.
As ADyson says:
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$json[] = $row;
}
echo json_encode($json);
for double check add your echo in this code, like this:
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
$json[] = $row;
}
echo json_encode($json);
If this code works, accept the ADyson answer
here is a way to solve the issue .Hoping your query is well written.
$dataFinal= array();//final variable that will contain total array for json
for($k=0;$k<count(variable_that_contents_the_resutl_array_query);$k++){
$ligne = array("item_id"=> $row['item_id'],
"item_name"=>$row['item_name'],"Barcode"=> $row['Barcode']);
array_push($dataFinal, $ligne);//add line in array datafinal
}//end for loop
$result = array($dataFinal);
$response = new Response(json_encode($dataFinal));
$response->headers->set('Content-Type', 'application/json');
return $response;
i have a table with two columns id and parent id
I want to get a recursive result child of child of child and so on
here in this example i want to achieve a result like
parent_id = 2
means first time parent is 2
next time result will be as parent
like 4,5,6,15 was id and 2 is parent id
next time 4,5,6,15 will be used as parent id
and result will be id = 7,8,13,14,16 and their id = 4,5,6 and 15
this will continue until last child.
maybe it can help you
<?php
$serverName = "localhost"; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"jdih");
$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));
}
function count_data($var)
{
$serverName = "localhost";
$connectionInfo = array( "Database"=>"jdih");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT count(*) total from test where parent_id = '".$var."'";
$stmt = sqlsrv_query( $conn, $sql );
$rowChild = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
return $rowChild['total'];
}
$sql = "SELECT id from test where parent_id = 0";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$totalchild = count_data($row['id']);
if($totalchild > 0){
$sqlchild = "select id from test where parent_id = '".$row['id']."'";
$stmtchild = sqlsrv_query( $conn, $sqlchild);
while( $rowChild = sqlsrv_fetch_array( $stmtchild, SQLSRV_FETCH_ASSOC) ){
//
$totalchild2 = count_data($rowChild['id']);
if($totalchild2 > 0){
$sqlchild2 = "select id from test where parent_id = '".$rowChild['id']."'";
$stmtchild2 = sqlsrv_query( $conn, $sqlchild2);
while( $rowChild2 = sqlsrv_fetch_array( $stmtchild2, SQLSRV_FETCH_ASSOC) ){
echo $row['id']. ' Has ' . $rowChild['id'].' has '.$rowChild2['id']. '<br>';
}
}else{
echo $row['id']. ' Has ' . $rowChild['id'].'<br>';
}
}
}else{
echo $row['id']. ' Has nothing';
}
}
?>
here is an example,i'm using sql. It's not dynamic but if only two level maybe it will help. You can add conditional check if that has child.
sorry bad english
I'm just starting to learn PHP and I'm having difficulty converting mysql_result to something that uses sqlsrv.
The code I'm trying to convert is:
(edited to include the full code)
function database($querydb) {
global $global;
global $field;
if (isset($global['queries'])) {
$global['queries']++;
} else {
$global['queries'] = "1";
}
$field['queries'] = $global['queries'];
if (isset($global['query_log'])) {
$global['query_log'] .= "\n<br>$querydb";
} else {
$global['query_log'] = "$querydb";
}
$serverName = "XXX";
$uid = "XXX";
$pwd = "XXX";
$dbName = "XXX";
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database" => $dbName, "ReturnDatesAsStrings"=>true);
$conn = sqlsrv_connect($serverName, $connectionInfo);
$stmt = sqlsrv_query($conn, $querydb) or return_error("Query Error: $querydb");
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) )
{
$global['dbresult'] = $row;
}
if ((substr($querydb,0,6)!="INSERT") && (substr($querydb,0,6)!="UPDATE") && (substr($querydb,0,6)!="DELETE")) {
while ($row1 = sqlsrv_fetch_array($stmt))
{
$global['dbnumber'] = mysql_numrows($global['dbresult']); // original $dbnumber
}
return;
}
function return_error($error) {
print $error;
exit;
}
function date_status($date, $username) {
global $global;
global $field;
global $input;
global $text;
$status = "0";
if ($username!="") {
$query = "SELECT countedrow.total, id, start_date, end_date FROM calendar JOIN (SELECT total = COUNT(*) FROM oc_calendar) AS countedrow ON 1=1";
database($query);
for ($i = 0; $i < $global['dbnumber']; $i++) {
$status = "1";
$event_id = sqlsrv_fetch_array($global['dbresult'],$i,"id");
}
}
return $status;
}
I have tried sqlsrv_get_field, sqlsrv_fetch, sqlsrv_fetch_array but I'm obviously not getting the syntax right and missunderstanding this as I'm getting an error of:
sqlsrv_fetch_array() expects parameter 1 to be resource, array given in...
... with what ever I do.
How do I extract the id from the array to set $event_id ? Where am I going wrong?
$querydb = "SELECT countedrow.total, id, start_date, end_date FROM oc_calendar JOIN (SELECT total = COUNT(*) FROM oc_calendar) AS countedrow ON 1=1";
$stmt = sqlsrv_query($conn, $querydb);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$event_id = $row["id"];
}
Does this work?
Why on earth were you mapping all the rows individually in a while to a globalvar and then looping the global var again! just loop it all directly if you need to return it out of a function back global then pass it as a return array NOT a global
You say you don't know how to provide a valid first argument for sqlsrv_fetch_array() but your code already does it right:
$stmt = sqlsrv_query($conn, $querydb) or return_error("Query Error: $querydb");
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
}
But then you get lost in your own spaghetti:
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) )
{
$global['dbresult'] = $row;
}
$event_id = sqlsrv_fetch_array($global['dbresult'],$i,"id");
I honestly suggest that you drop this code and start from scratch.