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
Related
I'm running a query to get the contents for a web slider.
$serverName = "livedata";
$connectionInfo = array( "Database"=>"DB", "UID"=>"User", "PWD"=>"PWD" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Sliders.DisplayFrom, Sliders.DisplayUntil, Sliders.Sort, Sliders.Image, Sliders.Link, Sliders.Target FROM Sliders WHERE (((Sliders.DisplayFrom)<GetDate()) AND ((Sliders.DisplayUntil)>getdate())) ORDER BY Sliders.sort;";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn, $sql);
$maxx = 0;
while($row = sqlsrv_fetch_array($result)) {
$maxx++;
}
while($row = sqlsrv_fetch_array($result)) {
echo “<br>” . $row[‘Image’];
}
The second loop does not output any results. why? Is it because $row is already at the end? If so, how do I move first like in ASP without having to create $result2 and $row2, 3, 4, 5, ...
Would it be better to use for loops like in vb.net?
for ($i = 0; $i <= $maxx; $i++){
}
But then How do I specify the output if I have no $row?
and if I only wanted to output the first row like I do in vb.net, how would I write the following in PHP?
dsqueryResults.tables(0).rows(0).item("Image");
would I still use a while loop and have a variable inside the loop to hold the row number and only output if row = 0?
$WhichRow = 0;
while($row2 = sqlsrv_fetch_array($result2)) {
if ($whichRow == 0){
echo “<br>” . $row2[‘Image’];
}
$WhichRow++;
}
Use the $max++ counter inside the while loop if you really want to use that for other purposes.
If you just want a count then run a count query on MySQL or do an array count of returned result.
If you just want to print 1 row use
LIMIT 0,1
at the end of your query as there's no point in fetching all rows and waste resources.
Based on additional comments you can try this to get your current row number.
$result = sqlsrv_query($conn, $sql);
$rownumber = 0;
while($row = sqlsrv_fetch_array($result)) {
$rownumber = $rownumber + 1;//Your current row number.
echo “<br>” . $row[‘Image’];
}
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);
?>
I have an iOS app which I built an API to extract some data from a SQL Server database. When my app sends a query with an empty string, it doesn't return any rows, even though it should.
$connectionInfo = array( "Database"=>db, "UID"=>$user, "PWD"=>$pass);
$conn = sqlsrv_connect($ip, $connectionInfo);
if ( $conn ) {
//connected
}
else {
echo "Error:"; echo "<br>";
die( print_r( sqlsrv_errors(), true));
}
/**************************************/
/* RETRIEVAL */
/**************************************/
$prod = new StdClass(); $arr = array(); $temp = array();
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
$stmt = sqlsrv_prepare( $conn, $sql, array($search));
sqlsrv_execute( $stmt );
$i = 0;
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
else {
while ( $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
$newProd = clone $prod;
$newProd->mainInfo = $row['name'];
$newProd->secondInfo = $row['qty'];
$arr[] = $newProd;
}
}
http_response_code(200);
echo json_encode($arr);
sqlsrv_close($conn);
I built the API with PHP and Apache on macOS where it worked as intended. When I copied the files on a Windows server, if my app accessed a link similar to 192.168.0.102/file.php?search= it would return no rows on Windows, and in macOS it would return all the rows of the table, as I wanted to. I know the script works and there are no issues, because if my app accesses a link similar to 192.168.0.102/file.php?search=someName it returns the corresponding rows. I want the app to display all the rows if the variable search is empty. Should I use some other way to achieve this, or is it some mistake on my part.
you can achieve that by not using sql condition when "search" $_GET param is not supplied or is empty.
Example how to achieve that, change your code from:
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
to something like this:
$search = null;
if (true === array_key_exists('search', $_GET) && false === empty($_GET['search'])) {
$search = '%' . $_GET['search'] . '%';
}
$sql = "SELECT name, qty FROM table";
if (false === is_null($search)) {
$sql .= ' WHERE name LIKE ?';
}
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.