mysql_result conversion to sqlsrv - php

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.

Related

Pull data from mssql to array - PHP

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

PHP - Insert Value with Key from another array into Array in Specific Place

I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!

SQLSRV query to array

I try to query a SQL database and save data into a custom array, but the array always repeats last row*num rows on database.
php:
class Cst
{
public $ParagemID;
public $Designacao;
public $DecimalDeGrauY;
public $DecimalDeGrauX;
}
require 'config.php';
$dsn = array( "Database"=>"$database", "UID"=>"$username", "PWD"=>"$password", "LoginTimeout"=> 60);
$db = sqlsrv_connect($server, $dsn);
$sql = "SELECT ParagemID, Designacao, DecimalDeGrauY, DecimalDeGrauX FROM adoParagens WHERE ParagemID >= 20000";
$stmt = sqlsrv_query($db, $sql);
$locations = new Cst();
$location=array();
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$locations->ParagemID = $row->ParagemID;
$locations->Designacao = $row->Designacao;
$locations->DecimalDeGrauY = $row->DecimalDeGrauY;
$locations->DecimalDeGrauX = $row->DecimalDeGrauX;
//echo json_encode($locations);
$location[$i]= $locations;
$i++;
}
echo json_encode($location);
It looks like you're always working with same instance of that object. Updating it for each row will also update all copies of it, as they are in fact the same object.
Try this instead.
...
$location = array();
while( $row = sqlsrv_fetch_object($stmt) )
{
$data = array();
$data['ParagemID'] = $row->ParagemID;
$data['Designacao'] = $row->Designacao;
$data['DecimalDeGrauY'] = $row->DecimalDeGrauY;
$data['DecimalDeGrauX'] = $row->DecimalDeGrauX;
$location[]= $data;
}
...
try using a 2 dimensional array.
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$location[$i][$locations->ParagemID/*put your val*/] = $row->ParagemID;
$location[$i][$locations->Designacao/*put your val*/] = $row->Designacao;
$location[$i][$locations->DecimalDeGrauY/*put your val*/] = $row->DecimalDeGrauY;
$location[$i][$locations->DecimalDeGrauX/*put your val*/] = $row->DecimalDeGrauX;
//echo json_encode($locations);
$i++;
}

SQL Select statement below < operator not working

So for some reason when I use the = operater in my prepared statement there is no problem however when I use the below operator ( < ) it gives an error.
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
So I know mysql gives false if there is a problem with my query. however I cant see the problem.
function availableapps($security)
{
if(empty($databasemanager)) { $databasemanager = new databasemanager(); }
$db = $databasemanager->connectionstring();
$result = $db->prepare("SELECT name FROM applications Where security<?");
$result->bind_param("s", $security);
$result->execute();
$types = array();
while(($row = mysqli_fetch_assoc($result->get_result()))) {
$types[] = $row['name'];
}
$result->close();
return $types;
}
Just for demonstration purposes,
final working code:
function availableapps($security)
{
if(empty($databasemanager)) { $databasemanager = new databasemanager(); }
$db = $databasemanager->connectionstring();
$result = $db->prepare("SELECT name FROM applications Where security<?");
$result->bind_param("s", $security);
$result->execute();
$results = $result->get_result();
$types = array();
while($row = $results->fetch_assoc()) {
$types[] = $row['name'];
}
$result->close();
return $types;
}
while ($row = $result->fetch_assoc()) {

How to return error message if there is no data in the database?

I wanted the logic is if there is data in the database then query the data. Or else if there is no data then it will show an error message.
Here is my code:
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
} else {
return $data = $query;
}
Before this code, if the code that query from database:
//Query string and put it in a variable.
if(isset($_POST['dob_chi'])){
$query = "SELECT * FROM $table_n WHERE dob_chi = :date";
} else {
$query = "SELECT * FROM $table_n WHERE dob_eng = :date";
}
I tried input a non data to execute the code but somehow it didn't show error and straight process to the scripting area.
The script below:
//create a while loop for every entry in our DB where the date is match.
while ($row = $stmt->fetchObject()) {
$r1 = $row->rowone;
$r2 = $row->rowtwo;
$r3 = $row->rowthree;
$englishdate = $row->dob_eng;
$chinesedate = $row->dob_chi;
//add all initial data into the matrix variable for easier access to them later
$rows[0]
$rows = array(
array($r1),
array($r2),
array($r3),
array()
);
}
//incoporate modulo value as an argument.
function incmod($a, $m)
{
return ($a % $m) + 1;
}
//Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod)
function populateRow($rowId, $populationCount, $mod)
{
//function to access the global variable.
global $rows;
$row = $rows[$rowId];
while (sizeof($row) < $populationCount) {
$rowInd = sizeof($row) - 1;
$m = incmod($row[$rowInd], $mod);
array_push($row, $m);
}
//set the row back into the global variable.
$rows[$rowId] = $row;
}
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
}

Categories