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
Related
I have a array containing of 250 eight character code. I am trying to insert this array to the table tbl_coupon. This is code I tried which is inserting only 1 data to the database.
I couldnot figure out where I did mistake.
$db = new Connection();
$sql = $db->query('insert into tbl_coupon(code) values(:code)');
$db->beginTransaction();
try {
foreach ($coupons as $coupon) {
$db->bind(':code', $coupon);
}
$db->execute();
} catch (\Exception $e) {
echo $e->getMessage();
$db->cancelTransaction();
}
$db->endTransaction();
Call $db->execute(); inside the foreach loop. The bind() just "replaces" the placeholder, so it is 250 times replaced and only the last one is executed.
$db = new Connection();
$sql = $db->query('insert into tbl_coupon(code) values(:code)');
$db->beginTransaction();
try {
foreach ($coupons as $coupon) {
$db->bind(':code', $coupon);
$db->execute();
}
} catch (\Exception $e) {
echo $e->getMessage();
$db->cancelTransaction();
}
$db->endTransaction();
$db->execute();
Place this line inside for loop. You are binding the values inside for loop, the values will be binded to the statement and replaced till the last element in the array.
Then after completion of for loop you are calling $db->execute(), this will store only the last value of your array to the table
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();
}
I moved over from plain MYSQL to PDO MYSQL and started using prepared statements. With my old system I was able to query the database and store the information in a array. I would then use usort to sort the table by money amount.
Since I've moved to PDO I'm having trouble using the array I get out of it. My origional code is as follows:
$sql = "SELECT name, item, cash, props FROM Donators";
$result = $conn->query($sql);
$result_array = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result_array[] = $row;
//var_dump($result_array);
}
} else {
echo "You have yet to join our servers!";
}
$conn->close();
function custom_sort($a,$b) {
return $a['cash']<$b['cash'];
}
usort($result_array, "custom_sort");
This results in the table being sorted by the column 'cash'. The code below is from my PDO code.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT name, item, cash, props FROM Donators");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$result_array = array();
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
$result_array[$k] = $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
function custom_sort($a,$b) {
return $a['cash']<$b['cash'];
}
//print_r($result_array);
usort($result_array, "custom_sort");
$length = count($result_array);
usort will cause this error:
Warning: Illegal string offset 'cash'
Printing the array $result_array shows
Array ( [name] => Жэка90 [item] => none [cash] => 1000 [props] => 0 )
I use the following code:
// In case an error occured during statement execution, throw an exception
if (!$stmt->execute()) {
// Error handling with $stmt->errorInfo()
}
// Fetch all results
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
It doesn't need a foreach loop to process the data afterwards.
Changing the for loop to
foreach($stmt->fetchAll() as $k=>$v) {
Fixed this.
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.
I am trying to return a set of results from PHP to android.
I have been able to return a single results but now I am trying to return multiple ones I am having some trouble figuring out how to do this as an array.
PHP function:
public function searchForPeople($tower) {
$uuid = uniqid('', true);
$result = mysql_query("SELECT * FROM users WHERE tower='$tower'") or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
//if just one result return it
if ($resultNo == 1) {
// return result
$resultSet[] = mysql_fetch_array($result);
return $resultSet;
//if more than one loop through
} else {
//add each row to an array
while($row = mysql_fetch_array($result)) {
$resultSet[] = $row;
}
return $resultSet;
}
} else {
return false;
}
}
Section of index.php where i POST my data from android to:
//SEARCH FOR PEOPLE
else if ($tag == 'searchPeople') {
$tower = $_POST['tower'];
$result = $db->searchForPeople($tower);
// check array has been created
if ($result != false) {
$response["success"] = 1;
$count = 0;
foreach($result as $row) {
$response[$count]["user"]["name"] = $row["name"];
$response[$count]["user"]["email"] = $row["email"];
$count++;
}
echo json_encode($response);
} else {
$response["error"] = 2;
$response["error_msg"] = "No users found";
echo json_encode($response);
}
}
else {
echo "Invalid Request";
}
I am then trying to get the information back in android as below however recieving the error that there is no value for 0 meaning there must be a problem in the way I have returned the json in PHP.
JSONObject results = new JSONObject(resultsString);
JSONObject json_row = results.getJSONObject("0");
JSONObject json_user = json_row.getJSONObject("user");
Im sure this is a problem with returning the PHP array of SQL results. Probably when I am looping through them to add them to either $resultSet or $response.
Any help greatly appreciated.
EDIT:
Here are the errors I am getting:
11-14 19:42:37.270: E/JSON(639): "[{\"uid\":\"4\",\"unique_id\":\"505efc638e0f48.78430999\",\"name\":\"fish\",\"email\":\"fish\",\"encrypted_password\":\"r\/Hb7uXrHN8bFuRoKlG8+Y5LdKFjM2QyZDUyYzQ1\",\"salt\":\"c3d2d52c45\",\"created_at\":\"2012-09-23 13:11:15\",\"updated_at\":\"2012-11-03 09:56:15\",\"location\":\"888\",\"tower\":\"IS\",\"base_location\":\"\",\"client_site\":\"\",\"graduate\":\"0\",\"location_updated\":\"0000-00-00 00:00:00\"}]"
11-14 19:42:37.270: E/JSON Parser(639): Error parsing data org.json.JSONException: Value [{"uid":"4","unique_id":"505efc638e0f48.78430999","name":"fish","email":"fish","encrypted_password":"r/Hb7uXrHN8bFuRoKlG8+Y5LdKFjM2QyZDUyYzQ1","salt":"c3d2d52c45","created_at":"2012-09-23 13:11:15","updated_at":"2012-11-03 09:56:15","location":"888","tower":"IS","base_location":"","client_site":"","graduate":"0","location_updated":"0000-00-00 00:00:00"}] of type java.lang.String cannot be converted to JSONArray
I recently used a routine similar to the one below. No matter if there is just one result or many results, it always works.
$dbuser = // user name;
$dbpass = // password;
$dbhost = // host name;
$dbname = // database name;
$sql = "SELECT * FROM users WHERE tower=" . $tower;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '({"items":'. json_encode($results) .'});';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
You should dump your resultsString to debug Log to see how it looks like and whether it is the expected JSON string. Then you can see where, in the server or the client, you must fix the code.
I'd also look into JSONObject.getJSONArray(), since the response you're sending back consists of nested arrays, AFAICS.
I believe you should use
mysql_fetch_assoc
To pull the rows in PHP. Then your result comes ready to be json_encoded into the string you'll need to return to Android.
So try this:
function sqlToJSON($sql){
$sth = mysql_query($sql);
//if this is an update or an insert nothing to return
if($sth === false || $sth === true){
return null;
}
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
return json_encode($rows);
}
You should be able to run the result of this method through new JSONObject(res); on the Java side
without having to do any additional translation... I'm saying this from memory, so, it may not be 100% right, but if not, it's pretty close.