I've successfully connected to a PostgreSQL database and even the query is running successfully.
But when I try to print the data using this code echo $data I get error as Array to String Conversion.
Tried searching in the forum and google. Nothing was fruitful.
Please help me.
Code used to convert it to array and print it.
if ( ! $myquery ) {
echo pg_error();
die;
}
$data = array();
for ($x = 0; $x < pg_num_rows($myquery); $x++) {
$data[] = pg_fetch_assoc($myquery);
}
// echo json_encode($data);
// $data2 = array_shift($data);
echo $data;
pg_close($server);
Read the error :
Array to String Conversion
Try to display it using var_dump or print_r because it's an array.
The error says that you want to display an array with echo which can only display string.
exemple : var_dump($data);
To just print the array (for debuging) use var_dump() like this:
var_dump($data)
But if you want to echo every line in the array you have to loop:
foreach ($data as $row) {
echo $row;
}
You are pinting array with echo.Try print_r(); that will print array. Like this print_r($data);
Try using var_dump($var) or print_r($var) functions
Related
I am currently trying to retrieve some info from some json code in PHP. I have some of it achieved but I am trying to get a players name from a nested array and I am having a bit of trouble. This is the json info:
Sorry I had to post on pastebin as JSON wouldnt embed in the code box. ht
tps://pastebin.com/6RZAgKFa
I have pulled in the info like so:
$json_string2 = 'URL TO JSON DATA';
$jsondata2 = file_get_contents($json_string2);
$serverinfo2 = json_decode($jsondata2,true);
And I can view it by printing it.
Now I am trying to loop through it all to just retrieve names, I am trying the following:
foreach($serverinfo2 as $playerinfo) {
foreach($playerinfo as $playerstuff) {
echo $playerstuff;
}
}
But that returns the full array. I then add [name] to the end of echo $playerstuff and it returns a number 1 and a D. Not even relevant, and $playerstuff->name also doesn't work. Can anyone help me at all. Thanks :)
You can try this to achieve data from nested data from json :
<?php
$res = '[{"endpoint":"127.0.0.1","id":"2","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Deadpool","ping":"85"},{"endpoint":"127.0.0.1","id":"1","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Logan","ping":"73"}]';
$result = json_decode($res,true);
// echo '<pre>'; //print_r($result);
foreach ($result as $key => $value) {
// print_r($value);
echo $endpoint = 'endpoint : ' .$value['endpoint'];echo "<br/>";
echo $name = 'name :' .$value['name'];echo "<br/>";
}
?>
I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}
I am having trouble in returning data in php from an SQL query. here is my code:
public function get_audit_message($productId,$accountId)
{
$sql_list ="SELECT notes
FROM ".$this->tables_audit."
WHERE productId = '".mysql_real_escape_string($productId)."'
AND accountId = '".mysql_real_escape_string($accountId)."'
";
$query = $this->db->query($sql_list);
if($query->num_rows() > 0)
{
$return = $query->result_array();
return $return;
}
else return false;
}
the reason I am having trouble is that as it is at return $return; returns the correct number of results but only displays the word "array". then if i change it to return $return[0]; returns the first entry of information correctly.
So what i want to be able to do is select all array numbers e.g return $return[*]; if only was possible.
Any suggestions would be much appreciated.
return $return; is the correct way to return an array from this function, but you can't just echo() the return value, since it's an array. When you try to echo an array, you get just the literal word "Array" (this also raises a notice which you would've seen with error reporting turned on).
You have to iterate over it and print each array element out, or use implode():
$array = $obj->get_audit_message($productId,$accountId); // However you call it
echo implode( "<br />\n", $array) . "<br />\n";
Or:
$array = $obj->get_audit_message($productId,$accountId); // However you call it
foreach( $array as $el) {
echo $el . "<br />\n";
}
Both of the above snippets will produce the exact same output.
There is several easy ways to display content of PHP Array in HTML.
The most simple is to view it via print_r command like this:
print_r ($my_array);
If you need to be "nice" formatted, add PRE tag like this:
echo "<pre>";
print_r($my_array);
echo "</pre>";
or like this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Also, there is similar var_dump and var_export PHP function:
echo "<pre>";
var_dump($my_array);
echo "</pre>";
or
echo "<pre>";
var_export($my_array);
echo "</pre>";
Just choose your preferred stile.
I'm trying to add values to an array via foreach but it only returns the word "Array" not the actual strings.
$msg = array();
foreach ($results as $result) {
$inventory = $result->qoh;
$inventoryOrder = $result->qo;
$product = $result->item;
$totalinv = $inventory+$inventoryOrder;
if ($inventory <= $threshold) {
$message = "Inventory for $product has fallen beneath threshold. $inventory remaining.\n";
$msg[] = array($message);
}
}
print (array_values($msg));
I've tried a few different ways and everytime it returns the word "Array"
You should use print_r, not print. print is for stings only. Try this:
echo '<pre>'; print_r(array_values($msg)); echo '</pre>';
Use var_dump to see the values.
var_dump (array_values($msg));
var_dump will alway show you the type of the result too. Helps a lot in debugging. (Looking at your code, I'm assuming you are doing the same).
I think you need to change the following code:
$msg[] = array($message);
to
array_push($msg, $message);
I am updating my question with a few breakthroughs i was able to achieve today. I used get_object_vars.
This code was able to print out the value i am trying to iterate over.
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
print_r('<pre>'. print_r($arrayPid) .'</pre>');
This http://www.image-share.com/ijpg-1163-165.html is what i saw as a result.
Now since this Object has objects inside it along with the values i need i.e. FileID,FileName etc. I am seeing the error message but a glimpse of the output. The code i used was this (just a very minor change from the above. I used a foreach)
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
//print_r('<pre>'. print_r($arrayPid) .'</pre>');
foreach($arrayPid as $val) {
echo ($val);
echo "<br>";
}
}
As a result of this i saw the following output http://www.image-share.com/ijpg-1163-166.html .
The index number 1 occupies the object and hence the error for string conversion.
If i use a For loop instead of the foreach in the code just above,i am unable to print the values.
I tried:
for($i=0;$i<(count($arrayPid));$i+=1)
{
echo($arrayPid[$i]);
}
But this would print nothing.
Could any one help me with a way so that i can iterate and have the values inside that array $arrayPid.
Would like to have your suggestions, views, doubts on the same.
I am sorry that i am using imageshare but that is the only way i can share my screens.
Thanks
Angie
The correct way to use it is:
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//print_r($fileStatusObtained->FileID);
$fileId [] = $fileStatusObtained->FileID;
...
}