I have an issue on my php script. I am trying to store mysql query into a php variable and then I convert the result to string. It seems doing the job in the loop but at the end of my script, I have an error:
Internal Error -
Notice:Undefined variable: result
I want to pass the whole content of the variable $data.
Do you know what i am doing wrong?
Here my php script:
<?php
if (isset($_GET['data']) && $_GET['data']) {
$SelectDataFromRunTable="Select Reference, Variant, HGVSVar FROM run29012016";
$QueryResult=mysqli_query($conn,$SelectDataFromRunTable);
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
print_r($data);
$data=implode(" ",$data);
}//end of while
$NameChecker='astringtest';
$options = array('features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient($URL, $options);
try {
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
} catch (Exception $e) {
echo $e->getMessage();
}
print_r($result);
mysqli_close($conn);
}
?>
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
$data = implode(" ",$data);
}
This can not work, as you overriding $data with every loop:
while($data = mysqli_fetch_array(...)) will evaluate as many times you have rows in your dataset, till the end. The last assignmet is $data = null (e.g. when you reached the end of you result set) and you are going out of the while-loop.
What you can do is, store you data into another variable, like
$soap_data = "";
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
$soap_data .= " " . implode(" ",$data);
}
//...
$result = $client->submitBatchJob(array('data'=>$soap_data, 'process'=>$NameChecker))
->submitBatchJobResult;
Also, what devpro said, it is always better to include a default for variables.
You need to define $result in default at top level like:
<?php
if (isset($_GET['data']) && $_GET['data'])
{
$result = array(); // ADD THIS
$SelectDataFromRunTable="Select Reference, Variant, HGVSVar FROM run29012016";
$QueryResult=mysqli_query($conn,$SelectDataFromRunTable);
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH))
{
print_r($data);
$data=implode(" ",$data);
}//end of while
$NameChecker='astringtest';
$options = array('features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient($URL, $options);
try
{
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
}
catch (Exception $e)
{
echo $e->getMessage();
}
print_r($result);
mysqli_close($conn);
}
?>
What i have changed?
I am adding $result = array(); in default.
You are trying to access $result outside where this var was defined.
try this:
try {
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
print_r($result);
} catch (Exception $e) {
echo $e->getMessage();
}
Related
I m trying to make a query in PHP with the MongoDB\Driver\Query class but with the doc in php.net I didn't really understand how to make it work.
I would like to return a JSON object with all data of my collection.
This for a function PHP running with Php 7.1.2 and MongoDB 3.2.20
$m = new MongoDB\Driver\Manager("mongodb://login:password#127.0.0.1:27017/");
$filter = array('id' => 0);
$options = array(
'projection' => ['name' => $parameters['baseName']]
);
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $m->executeQuery(''db_name.my_collection', $query);
$myJson = json_decode(json_encode($cursor),true);
You can use this as said here:
json_encode(iterator_to_array($cursor))
try
{
$client = new MongoDB\Driver\Manager("mongodb://login:password#127.0.0.1:27017/");
}
catch (Exception $e)
{
echo "***DB Client not created*** " . $e->getMessage();
saveEvent("DB Client not created" . $e->getMessage(), $owner);
exit();
}
$filter = ['id'=> $lookForID];
$query = new MongoDB\Driver\Query($filter);
try
{
$rows = $client->executeQuery('dbName.collectionName', $query);
}
catch (Exception $e)
{
echo "***search failed*** " . $e->getMessage();
exit();
}
foreach($rows as $r){
print_r($r);
}
This question already has answers here:
Use PHP to dump mysql values into JSON file
(3 answers)
Closed 6 years ago.
I wanted to add all arrays from my database in one json encode and decode it later on.. but I ran into a thing which I don't know how to fix.
I'm trying to add all arrays from the sql query in one array and then encode that one array with all the arrays inside it.
My current code:
$dbh = new PDO('mysql:host='.$this->server.';dbname='.$this->database.'', $this->user, $this->pass);
$result = array();
foreach($dbh->query('SELECT * from bier') as $row) {
$result[] += $row;
}
print json_encode($result);
Updated code:
function getData()
{
try {
$dbh = new PDO('mysql:host='.$this->server.';dbname='.$this->database.'', $this->user, $this->pass);
$result = array();
foreach($dbh->query('SELECT * from bier') as $row) {
$result[] = $row;
}
$json = json_encode($result, JSON_PRETTY_PRINT);
var_dump($json);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Currently returns: Boolean False
In PHP, the += compound operator is used to "add & assign"; however, this does not work as you'd expect for inserting items into an array.
Your code should work if you remove the + from that line as #Rajdeep pointed out.
Here is your code, updated with some changes for clarity:
try
{
$data = new PDO('mysql:host='.$this->server.';dbname='.$this->database.'', $this->user, $this->pass);
$data->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$list = [];
foreach($data->query('SELECT * from bier') as $item)
{ $list[] = $item; }
$json = json_encode($list, JSON_PRETTY_PRINT);
echo $json;
}
catch (PDOException $fail)
{
echo $fail->getMessage();
exit;
}
As you probably notice; the [] = character sequence after a variable name (that is an array) inserts the new item in the array being assigned.
The try --> catch block should indicate if there was a problem.
Here's more info on how to check for errors: http://php.net/manual/en/pdo.connections.php
I have a reasonably complicated stored procedure in MSSQL 2008 R2 that, in the end, results in a small table being returned. The PHP will be called from javascript and I want it to return the array as JSON to be used in table in the javascript.
I am using PHP to access it and, using the profiler, can see that I am calling the SP and passing the correct parameters to it.
My PHP looks like this:
try {
$dbh = new PDO("sqlsrv:Server=(local);Database=cddDispo");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode("Error connecting to the server.");
die ();
}
$lot = $_POST["lot-input"];
$layerAdder = $_POST["layer-input"];
$adder = substr($layerAdder,-3,3);
$adder = str_replace('=','',$adder);
$layer = substr($layerAdder,0,strpos($layerAdder,' '));
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$array = array();
try {
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
//I want to build my output array here
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
This is the first time that I have tried to return table results from a stored procedure and even with several PHP Manual/ Google searches I have not figured out how to capture the table back in the PHP. I have a less elegant workaround (write the SP table to a static table and call that table later in the PHP) but would rather figure out if I can do in a more elegant manner. Any advice is much appreciated.
I thought it might be useful if I posted my final code:
function array_push_assoc($array,$key,$value) {
$array[$key] = $value;
return $array;
}
header('Content-type: application/json');
try {
$dbh = new PDO('sqlsrv:Server=(local);Database=cddDispo');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode('Error connecting to the server.');
die ();
}
$lot = $_POST['lot'];
$layer = $_POST['layer'];
$adder = $_POST['adder'];
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$results = array();
$combinedArray = array();
$array = array();
$count = 0;
try {
$sth->execute();
do {
$results[] = $sth->fetchAll(PDO::FETCH_ASSOC);
}while ($sth->nextRowset());
foreach($results as $row) {
if($count == 0) {
$headerArray =
[
'Lot' =>$row['Lot'],
'Layer' =>$row['Measured Layer'],
'Product' =>$row['MES Product'],
'Adder' =>$row['Adder Chart']
];
$combinedArray = array_push_assoc($combinedArray,'header',$headerArray);
}
$count++;
//This is for formatting of final table
if($row['UDL'] == 0) {
$udl = 'NA';
} else {
$udl = round($row['UDL'],4);
}
$infoArray =
[
'Wafer' =>$row['Wafer'],
'Type' =>$row['Type'],
'Count' =>$row['Count'],
'CDD' =>round($row['CDD'],3),
'UCL' =>round($row['UCL'],4)
];
array_push($array,$infoArray);
}
$combinedArray = array_push_assoc($combinedArray,'detail',$array);
}catch (PDOException $e) {
echo json_encode('Error running stored procedure.');
die();
}
echo json_encode($combinedArray);
Could it be that your stored procedure is returning multiple result sets? This includes output like warning messages or number of rows affected. Try adding SET ANSI_WARNINGS OFF or SET NOCOUNT ON at the top of your stored procedures after the AS. You can also try advancing to the next result set in PHP before trying to get the results by calling $stg->nextRowset() before $sth->fetchAll().
Use fetchAll() to get your resultset, then encode that array as your json response:
$array = array();
try {
if($sth->execute()){
$array = $sth->fetchAll(PDO::FETCH_ASSOC);
}else{
$array = array('error'=>'failed to execute()')
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
When you are calling a stored procedure with multiple result sets, you probably do not want to add SET NOCOUNT ON into every procedure you have; you always can add
$dbh->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$dbh->query("SET NOCOUNT ON");
before of
$dbh->prepare($query);
and it will work.
here's the PHP/PDO.
try {
$query = 'SELECT Date,Close FROM DY_AAPL LIMIT 5';
$sth = $db->prepare($query);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)){
$result_array=array();
$result_array[]=$row['Close'];
/* $num = $row['Close']; */
echo json_encode($result_array);
}
}catch (PDOException $e){
echo 'ERROR ' . $e->getMessage();
}
When I attempt to access the array using javascript, it's only outputting the last value in the array. Any pointers?
<script type="text/javascript">
var myjson = JSON.parse('<?php echo json_encode($result_array); ?>');
document.write(myjson);
</script>
I thought it might have something to do with 'JSON.parse,' but I'm not sure. Thanks in advance!
Try
$result_array = array();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$result_array[]=$row['Close'];
/* $num = $row['Close']; */
}
echo json_encode($result_array);
…instead of initializing and outputting the array in each loop turn.
You should echo your end result, not every iteration:
while ($row = $sth->fetch(PDO::FETCH_ASSOC)){
$result_array=array();
$result_array[]=$row['Close'];
}
echo json_encode($result_array);
Try this for your PHP:
try {
$query = 'SELECT Date,Close FROM DY_AAPL LIMIT 5';
$sth = $db->prepare($query);
$sth->execute();
$result_array=array();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)){
$result_array[]=$row['Close'];
}
echo json_encode($result_array);
}catch (PDOException $e){
echo 'ERROR ' . $e->getMessage();
}
It's because your doing the json encode within the while-loop. Place it outside the loop so the entire array get encoded.
Also, you're initializing the array within the while-loop. Which means that it will overwrite itself each time it loops.
I have the following code:
$link = new PDO("mysql:dbname=$databasename;host=127.0.0.1",$username,$password);
$query = $link->prepare("SELECT * FROM index WHERE sbeid=:idvar");
for($j = 1; $j < count($array); $j++)
{
if($array[$j][16] == "TRUE" || $array[$j][16] == "FALSE")
{
$paramforquery = $array[$j][25];
$query->bindParam(":idvar",$paramforquery);
$query->execute();
$result = $query->fetchAll();
//do things with the $result
$query->closeCursor();
}
//else if, do stuff
}
$link = null;
$array is a large array composed of input from a CSV file that successfully loads via fopen().
My problem is this: the query just doesn't work. I know for a fact (ran the query directly on the server with some sample values from the file) that the data is in the database, but when i var_dump the $results each time the for loop runs, I just get an empty array.
What am I doing wrong?
TIA.
Increase the error reporting - the standard advice.
Set the error mode of the pdo object to ERRMODE_EXCEPTION - you hardly can miss an error that way.
Use a debugger or add some debug output to your script - a real debugger is way better.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$array = foo();
echo '<pre>Debug: |array|=', count($array), '</pre>';
$link = new PDO("mysql:dbname=$databasename;host=127.0.0.1",$username,$password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $link->prepare("SELECT * FROM index WHERE sbeid=:idvar");
$query->bindParam(":idvar", $paramforquery);
foreach($array as $row) {
echo '<pre>Debug: row[16]='; var_dump($row[16]); echo '</pre>';
if($row[16] == "TRUE" || $row[16] == "FALSE") {
$paramforquery = $row[25];
echo '<pre>Debug: paramforquery='; var_dump($paramforquery); echo '</pre>';
$query->execute();
echo '<pre>Debug: rowcount='; var_dump($query->rowCount()); echo '</pre>';
$result = $query->fetchAll();
//do things with the $result
$query->closeCursor();
}
//else if, do stuff
}
$link = null;
Are you sure you are getting a connection ?
try {
$link = new PDO("mysql:dbname=$databasename;host=127.0.0.1",$username,$password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
This will catch any exceptions from trying to connect. If this works ok, try putting the query under the $link line and see what's returned.
If your query runs manually, i'd say its something to do with your DB connection. Make sure you've got error reporting turned on.
Additional:
In your query you have this :idvar ? Shouldnt you be using a PHP variable like this $idvar.
so
$query = $link->prepare("SELECT * FROM index WHERE sbeid=" . $idvar);