Javascript only producing last value of json encoded array - php

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.

Related

Using PHP and MySQL, how do you send a variable into a WHERE... IN clause?

The following SELECT statement works just fine:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (65,70,80)');
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
BUT when I try to send a variable into the WHERE clause, I only get one row back.
In this case $ids is a string that looks like '65,70,80'.
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, $ids);
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Do I need to change the way I'm fetching the data, or is my syntax wrong?
A-HA! Thanks for that link Mihai. Here's the code that works:
First: instead of passing in a string, put ids into an $ids array.
// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (' . $queryPlaceholders . ')');
$sql->execute($ids);
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Try this:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, explode(',', $ids));
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}

Issue Undefined variable after storing mysql query into a php variable

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();
}

foreach is not working in php with pdo

I am using PDO with my PHP project and I don't know why this is not working. It is not showing any error.
I have a function to read data from a database:
function Read_post($con,$table,$limit=6){
try {
$query = "SELECT * FROM {$table} ORDER BY id DESC LIMIT {$limit}";
$stmt = $con->prepare( $query );
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
return "ERROR". $e->getMessage();
}
}
and I use a foreach loop to display the data. But it is not showing anything:
<?php $posts = Read_post($con,"posts"); ?>
<?php foreach ($posts as $key) {
echo "something ";
echo $key["title"];
} ?>
It is not showing the other text as well like if i echo something else only text.
Inside your function Read_post, you have this line:
return $stmt->fetch(PDO::FETCH_ASSOC);
It will not return an array, it will return a PDO object. You can't iterate over a PDO object in the same way as an array. Try this:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
echo the $value of the array in foreach or var_dump($post) to check the array contains
something
<?php foreach ($posts as $value) {
echo "something ";
echo $value;
} ?>

SQL Query won't return what is in the row (PHP)

My PHP:
<?php
function connectDB($user, $pass) {
try {
return(new PDO("mysql:host=localhost;dbname=Test;", $user, $pass));
} catch(PDOException $ex) {
return $ex;
}
}
$db = connectDB("root", "root");
if ($db instanceof PDOException) {
die($db->getMessage());
}
$query = "SELECT * FROM `TABLE`";
$stmt = $db->prepare($query);
$stmt->execute();
$rows = $stmt->fetch();
foreach($rows as $row) {
echo $row['VALUE1'];
echo $row['VALUE2'];
echo $row['VALUE3'];
}
?>
It only echo's the first letter of each value.
Here is what my table looks like:
VALUE1 VALUE2 VALUE3
gomeow book nothing
other book nothing
It only prints out the first letter of the first row many times
Prints out: ggggggbbbbbbnnnnnn
Check your error logs, and try with this and let me know then -
$rows = $stmt->fetch(PDO::FETCH_BOTH);
print_r($rows);

How to get first row of data in sqlite3 using php PDO

How to get first row of data in sqlite3 using php PDO
As per my below code first row data does not display becuase I have used recordset for check row is return or not.
Any idea how to get all data from record set?
My Code.
try {
$dbhandle = new PDO("sqlite:".$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$result=$dbhandle->query("select * from table");
if($result)
{
if($rs1==$result->fetchColumn())
{
while ($rs1 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo "<pre>";
print_r($rs1);
echo "</pre>";
}
}
else
{
// error message
}
}
If you just want to get the first row, then there's no need to use a loop.
$result=$dbhandle->query("select * from table");
if ($result) {
$row = $result->fetch(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($row);
echo "</pre>";
}
Update:
For get all rows.
$result=$dbhandle->query("select * from table");
$rows = array();
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
if ($rows) {
echo "<pre>";
print_r($rows);
echo "</pre>";
} else {
echo "No results";
}
}

Categories