Fetch multiple resultset from SQL Server in Laravel 5.3 - php

Here is the code
$exec = "EXEC RPT_TEST_2resultSet";
$resultSet = \DB::select($exec);
SP is returning 3 result sets. But in php it prints first set of result set only. How to fetch the other 2 set of result sets? Tried the solution suggested by others. Was getting some other errors.

Make a foreach
check example:
foreach ($resultSet as $result) {
echo $result['someDataFromResult'];
}
This will repeat for the amount of data is in the $resultSet array

Found the simple solution for this problem.
$pdo = \DB::connection()->getPdo();
$sql = 'EXEC Test_SP_MultiResultSet';
$stmt = $pdo->query($sql);
do {
$rows = $stmt->fetchAll(\PDO::FETCH_NUM); // Keys will be start from zero , one, two
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); // Column names will be assigned for each value
if ($rows) {
$sheetData[] = $rows;
}
} while ($stmt->nextRowset());
Source Link

Related

how to get db all data using array in php

I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.
public function get_All_Se($stId){
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
$data = $result->fetch_array(MYSQLI_ASSOC);
return $data;
}
public function get_All_Se($stId){
$rows=array();
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
while($data= $result->fetch_assoc()){
$rows[]=$data;
}
return $rows;
}
Run loop over all results and add to some return array.
$rows = array();
while(($row = $result->fetch_array($result))) {
$rows[] = $row;
}
As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).
The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.
public function get_All_Se($stId)
{
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_all(MYSQLI_ASSOC);
}
The code above still has two big issues:
It is open to SQL injection. Use prepared statements to avoid it.
or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Try this way...
<?php
// run query
$query = mysql_query("SELECT * FROM <tableName>");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['<fieldName>']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];
?>

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

PHP - Execute select query and loop through results

I am developing a web service using PHP. I am having some trouble while executing the select query. This is the code I'm using.
DB_Functions.php
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
return mysql_fetch_array($result,true);
} else {
return false;
}
}
GetCompanies.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$companies = array();
//$rows = $db->getCompanies();
while ($row = $db->getCompanies()) {
echo $row['companyName'];
$rowArr = array();
$rowArr['CompanyName'] = $row['companyName'];
$rowArr['CompanyID'] = $row['companyId'];
//array_push($companies, $rowArr);
$companies[] = $rowArr;
}
header('Content-Type: application/json');
$response=array("Companies"=>$companies);
$json = json_encode($response);
echo $json
?>
But the problem is in GetCompanies.php file the while loop is runs endless. The code appears to be ok. Any help would be appreciated.
When you do while ($row = $db->getCompanies()) { you are running the entire query over again and returning the 1st row each time. mysql_fetch_array returns one row.
What you need to do is have getCompanies() loop over all the rows and return an array.
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
$ret = array();
while($row = mysql_fetch_assoc($result)){
$ret[] = $row;
}
return $ret;
} else {
return false;
}
}
Now, getCompanies() will return you an array that you can just foreach over:
$rows = $db->getCompanies();
foreach($rows as $row){
// ...
}
Change your while loop declaration to something like
foreach($rows as $row) {}
And as Pavlin said, move the function call to getCompanies() outside the loop.
Also, how about modifying the query to select a particular set of fields from the database and directly sending them as the response without doing any additional processing?
Since you are implementing Select query without any condition(where clause). And since the company table has data it would always return true in the while loop this makes the while loop an infinite loop. For while to work properly the condition should become false to exit the loop.
Its not a programming flaw its a logical one.
The php docs have all the information you need. You're using the wrong function:
mysqli_fetch_array — Fetch a result row as an associative, a numeric
array, or both
vs
mysqli_fetch_all — Fetches all result rows as an associative array, a
numeric array, or both
Just change your return statement to
return mysqli_fetch_all($result);
or
return mysqli_fetch_all($result, MYSQLI_ASSOC);
to get an associative array.
And of course, you need to move your getCompanies call outside of the loop.
NOTE
php mysql_* functions have been depricated since version 5.5.* and are going to be removed from the language soon. You should look into mysqli_* or PDO.

PHP Array comparison and filtering

I'm newer to PHP and sorting out some code. This is taking two phone number lists… then pulling the numbers in the 2nd list OUT of the first list, making a new filtered list. The full code worked fine when just pulling in one list. Now that I've modified it to filter the list based a 2nd list, the code now fails and I'm getting this warning:
Warning: Illegal string offset 'phone_number' in /var/www/html/send.php on line 7
// Get all of the phone numbers from the List
$sql = "SELECT phone_number FROM dial_list WHERE list_id='$list'";
$result = mysqli_query($link, $sql);
echo mysqli_error($link);
foreach ($result as $row)
{
$all_people[] = $row['phone_number'];
}
// Get phone numbers from our DNC list
$sql = "SELECT phone_number FROM dial_dnc";
$result = mysqli_query($link, $sql);
echo mysqli_error($link);
foreach ($result as $row)
{
$dnc_people[] = $row['phone_number'];
}
// Remove DNC numbers from list
$filtered_people = array_diff($all_people, $dnc_people);
foreach ($filtered_people as $row)
{
$people[] = $row['phone_number'];
}
Line 79 (where the warning comes from) is:
$people[] = $row['phone_number'];
Any help to pinpoint the error or an improvement on how to accomplish this filtering would be greatly appreciated!
You forgot to fetch results from your resultset
foreach ($result as $row) {
should be
while ($row = mysqli_fetch_assoc($result)) {
This can be easily done with mysql alone.
SELECT
dl.phone_number
FROM dial_list AS dl
INNER JOIN dial_dnc as dnc
ON (dl.phone_number = dnc.phone_number)
WHERE list_id='$list'
your $result is a traversable object, not an array. as seen in the docs
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You can loop over the results in 2 different ways:
// precedural style
while ($row = mysqli_fetch_assoc($result)) { ... }
// OOP style
while($row = $result->fetch_assoc()) { ... }
Since you assign $all_people and $dnc_people with $row['phone_number'], $filtered_people doesn't have a phone_number key, instead being number-keyed, probably. Try
foreach($filtered_people as $key => $value)
{
$people[] = $value;
}

Mysql fetch all rows and echo as json

I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
//==== ECHO AS JSON
echo json_encode($array);
Help would be much appreciated.
You need to loop through the results. mysql_fetch_row gets them one at a time.
http://php.net/manual/en/function.mysql-fetch-row.php
The code would end up like:
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()
PLEASE NOTE
The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row in the code above.
http://www.php.net/manual/en/mysqli-result.fetch-row.php
I do like this while quering an ODBC database connection with PHP 5.5.7, the results will be in JSON format:
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
Fetching results allowing edit on fields:
while( $row = odbc_fetch_array($result) ) {
$json['field_1'] = $row['field_1'];
$json['field_2'] = $row['field_2'];
$json['field_3'] = $row['field_1'] + $row['field_2'];
array_push($response, $json);
}
Or if i do not want to change anything i could simplify like this:
while ($array = odbc_fetch_array($result)) { $response[] = $array; }
What if i want to return the results in JSON format?, easy:
echo json_encode($response, true);
You can change odbc_fetch_array for mysqli_fetch_array to query a MySql db.
According to the PHP Documentation mysql_fetch_row (besides that it's deprecated and you should use mysqli or PDO)
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
so you need for example a while loop to fetch all rows:
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
}
echo json_encode($rows);
I leave it to you how to only fetch 3 rows :)
You need to put this in some kind of a loop, mysql_fetch_row returns results one at a time.
See example:
http://www.php.net/manual/en/mysqli-result.fetch-row.php#example-1794
$result = mysql_query( "SELECT * FROM $tableName ORDER BY id LIMIT 3");
$json = array();
while($array = mysql_fetch_row($result)){
$json[] = $array;
}
echo json_encode($json);

Categories