简体   繁体   中英

Not able to retrieve a single value from php array

We have a Stored Procedure in MSSQL that returns two values:

Agent | Tickets
int   | int

We are successfully connecting to the database server and calling the SP with pdo like this:

<?php 
//Declare hostname variable
$hostname = 'servername';

try {
$conn = new PDO("sqlsrv:Server=$hostname;Database=dbnamee");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$agent = 249;
$stmt = $conn->prepare("{CALL Proc_GetActiveTicketsForAgent (:agent)}");
$stmt->bindParam(":agent",$agent, PDO::PARAM_STR);
$stmt->execute();

$results = array();
do {
$results []= $stmt->fetchAll();
} while ($stmt->nextRowset());

echo '<pre>';
print_r($results);echo "\n"; // all record sets
echo '</pre>';
?>

This outputs the full array (as a test).

What I am trying to do is returning the value of Tickets (for example; 6, which is the current number of tickets on agent 249), and I can do this by using:

$results = $stmt->fetch(PDO::FETCH_OBJ);
print($results->Tickets);

When I go to our index site, and use the include() function, I can output the whole array (this is just a part of the code):

<!DOCTYPE html>
<html>
<head>
<title>sitetitle</title>
<meta charset="UTF-8">
</head>
<body>
<?php include('phpfile.php');

?>
<p>
<?php
echo '<pre>';
print_r($results);echo "\n"; // all record sets
echo '</pre>';
?>
</p>
</body>
</html>

But when I try to use the same function as earlier:

print($results->Tickets);

I get "500 - internal server error"

Can anyone see where I am going wrong? I am starting to go bald from pulling my hair out.

Thanks.

Use something like this after your execute statement:

$results = $stmt->fetchAll()

Then to loop through the results:

foreach($results as $row){
    echo $row['Agent']. ": ". $row['Tickets'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM