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;
} ?>
Related
Good day!
I have written a function getData() that is running a query to SELECT all data from my database.
function getData() {
try {
$pdo = new PDO("mysql:host=localhost;dbname=db", 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM table";
$stmt = $pdo->prepare($sql);
$stmt->execute();
foreach ($stmt as $row)
{
echo $row['username'];
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
To output the data, I do a foreach loop and echo the results. No brainer, this situation works for me outside the HTML that I want to output the results in.
But, I hope to output the results inside a HTML table:
<tbody>
<tr>
<?php getData();
foreach ($stmt as $row) { ?>
<td>
<?php echo $row['username']; ?>
</td>
<?php } ?>
</tr>
</body>
Is there something in my code that I am missing? Am I not following a correct procedure? I hope to learn from this to better improve in the coming future and I hope I did my best to ask the question to help understand my situation.
Thank you!
Instead of echo'ing in getData(), you should add each result to an array and return that:
function getData() {
....
$results = array();
foreach ($stmt as $row) {
$results[] = $row; //add each result to the array
}
return $results; //return the data
}
Then in your HTML assign the result of getData(); to a variable:
$data = getData();
And then loop on the $data variable:
foreach ($data as $row) { ?>
<td>
<?php echo $row['username']; ?>
</td>
<?php } ?>
Class PHP
<?php
class product extends db {
function viewCat(){
$dbcon = new db();
$connn = $dbcon->dbcon();
try {
$stmt = $connn->prepare("SELECT * FROM `cat`");
$resultcat = $stmt->execute();
return $resultcat;
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
?>
the view
<?php
$menu = new product();
$resultmenux = $menu->viewCat();
foreach ($resultcatx as $row) {
print_r($row);
}
?>
the error i get is
Warning: Invalid argument supplied for foreach()
in your class file it should be, as I commented you are not fetching the data
$stmt = $connn->prepare("SELECT * FROM `cat`");
$stmt->execute();
$resultcat = $stml->fetchAll(PDO::FETCH_ASSOC); // this line was missing
return $resultcat;
and in view file as answered by shankhan
$resultmenux = $menu->viewCat();
foreach ($resultmenux as $row) {
print_r($row);
}
It should be like this:
$resultmenux = $menu->viewCat();
foreach ($resultmenux as $row) {
print_r($row);
}
I have myself in a unique situation here and I am not sure if this is the correct way to go about it; I am open to suggestions.
I have a function in which it grabs all of the table names in a database and stores them into an array. Next newly parsed items ($id) are passed against this table name array and any matches are unset from this array. This leaves me with the leftovers which are items that have been discontinued.
Code below:
function itemDiscontinued($dbh, $id, $detail) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
$key = array_search($id, $tableList);
unset($tableList[$key]);
print_r($tableList);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
The problem is that the array $tablelist keeps recreating itself due to the function being in a foreach loop (Parsing process). I only require one instance of it to work with once it is created. I apologise before hand if the problem is a bit hard to understand.
Yea, it's really hard to understand. Maybe you'll try this:
function itemDiscontinued($dbh, $id, $detail) {
static $tables = array();
if (!$tables) {
$tables = getTableList($dbh);
}
$key = array_search($id, $tables);
unset($tables[$key]);
print_r($tables);
}
function getTableList($dbh) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
return $tableList;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
how about an array_push with an extra parameter
function itemDiscontinued($dbh, $id, $detail, $outputArray) {
try {
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
array_push($outputArray, $row[0]);
}
$key = array_search($id, $outputArray);
unset($outputArray[$key]);
return $outputArray; // use this for subsequent run on the foreach statment
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
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);
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.