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
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);
?>
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
i have SQL server database , and I'm using php to connect to it and using queries.
i've read two records from the database for one employee. and i need them to calculate the works hours to the employee. but i couldn't figure how to select to fields from the same column to the same employee. as in the picture:
E003 2014-03-17 08:10:12 2221
E003 2014-03-17 10:05:02 2222
E003 2014-03-17 12:15:20 2221
E003 2014-03-17 15:03:30 2222
the 2221 is the entring door, and the 2222 is the exit door. i want to select the time from the 2222 and substract them to have the works hours for the employee. can you help me with that pleas, this is my code:
<?php
$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>";
/**********************************************/
$FRISTsql = "SELECT [EmpID],[DATE],[TIME],[OBJECT] FROM [AccessCard].[dbo].[TimeAtt] WHERE [EmpID]='E003'";
$Fstmt = sqlsrv_query( $conn, $FRISTsql );
if( $Fstmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $Frow = sqlsrv_fetch_array( $Fstmt, SQLSRV_FETCH_ASSOC) ) {
$R1 = $Frow['EmpID'];
$R2 = $Frow['DATE']->format('Y-m-d');
$R3 = $Frow['TIME']->format('H:i:s');
$R4 = $Frow['OBJECT'];
ECHO $R1."   ";
ECHO $R2."    ";
ECHO $R3."    ";
ECHO $R4."</BR> ";
}
sqlsrv_free_stmt( $Fstmt);
For the given results you can do the following. But extending for 4000 records, you may need to look for some query manipulation.
Plz, check the date comparison part as i may not be correct by the PHP syntax and function. But this can be used as a general concept.
<?php
$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>";
/**********************************************/
$FRISTsql = "SELECT [EmpID],[DATE],[TIME],[OBJECT] FROM [AccessCard].[dbo].[TimeAtt] WHERE [EmpID]='E003' order by [DATE],[TIME]";
$Fstmt = sqlsrv_query( $conn, $FRISTsql );
if( $Fstmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
else {
$enterTime; $exitTime;
while( $Frow = sqlsrv_fetch_array( $Fstmt, SQLSRV_FETCH_ASSOC) ) {
$R1 = $Frow['EmpID'];
$R2 = $Frow['DATE']->format('Y-m-d');
$R3 = $Frow['TIME']->format('H:i:s');
$R4 = $Frow['OBJECT'];
if($enterTime == null && $R4 == 2001)
{
$enterTime = $R3;
}
if($exitTime == null && $R4 == 2002)
{
$exitTime = $R3;
}
else if($R3 < $enterTime && $R4 == 2001)
{
$enterTime = $R3;
}
else if($R3 > $exitTime && $R4 == 2002)
{
$exitTime = $R3;
}
ECHO $R1."   ";
ECHO $R2."    ";
ECHO $R3."    ";
ECHO $R4."</BR> ";
}
ECHO "User:".$R1." for date".$R2." worked for ".($exitTime - $enterTime);
}
sqlsrv_free_stmt( $Fstmt);
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.