PHP making a table extracting data out of sql database using pdo - php

I have a question about how I need to make a table with data from a database created in phpmyadmin using the pdo method. The connection to the database works and I got my data from a table in an array. But I need to make a table based on the data out of the table using a foreach loop.
<?php
include('connect.php');
try
{
$sql = 'select * from joke';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$output = 'There is a problem: '.$e->getMessage();
echo $output;
exit();
}
$aOrders = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$aOrders[] = $row;
}
var_dump($aOrders);
echo '<table>';
foreach($aOrders as $key => $value)
{
echo '<tr><td>'.$aOrders['id'].'</td><td>'.$aOrders['joketext'].'</td><td>'.$aOrders['jokeclou'].'</td><td>'.$aOrders['jokedate'].'</td></tr>';
};
echo '</table>';
?>
the 'id', 'joketext', 'jokeclou' and 'jokedate' are fields in my table and I want them to print it into a table.

In your foreach() you are trying to access the $aOrders array
echo '<tr><td>'.$aOrders['id'] ...
where you need to get the values in your => $values of foreach($aOrders as $key => $value)
echo '<tr><td>'.$value['id'].'</td><td>'.$value['joketext'].'</td><td>'.$value['jokec‌​lou'].'</td><td>'.$value['jokedate'].'</td></tr>';

Related

Error is Trying to get property 'id' of non-object, but seems object has

I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -
try{
///try to connect with database
$conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo "error";
}
$mysqlcode="SELECT * FROM users";
$ret=$conn->query($mysqlcode);
foreach($ret as $ret1)
print $ret1->id;
in the browser,
showing this error:
Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44
In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.
I have checked your code. Everything is fine. Just do this.
foreach($ret as $ret1)
print $ret1['id'];
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code
$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);
if ($ret->num_rows > 0) {
// output data of each row
while($row = $ret->fetch_assoc()) {
echo "id: " . $ret["id"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
that'll work fine.
Before trying to use Object Oriented PHP, is much easier to understand Procedural. Take a look at the code below.
First, connect to database:
<?php
//Store log in info into variables
$servername = 'localhost';
$serveruser = 'youruser';
$serverpassword = 'yourpassword';
$serverdatabase = 'yourdatabase';
// Create connection
$conn = mysqli_connect( $servername, $serveruser, $serverpassword, $serverdatabase );
if ( !$conn ) {echo "Connection Fail" . mysqli_connect_error();}
//else {echo "Connected to database $serverdatabase";}
?>
Then, call the information from your database and your table and store it into an associative array $data
$sql = "SELECT * FROM `table`";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASOCC);
mysqli_free_result($result);
Now you can use the array to print the results with print_r
echo '<pre>'; print_r($data); echo '</pre>';}
Now you are ready to use foreach depending on your table columns,for example if you have ID column then
<?php foreach ($data as $value){
echo $value['id]."<br>";
} ?>
It will print out all the IDs. Hope this helps.

PDO Results to array

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.

Import JSON in MySQL DB from Import.io

I'm trying to import data from a JSON feed using PHP into a MySQL database.
I have the code below but am not getting anywhere with it.
I keep just getting Connected to Database but nothing is being pulled in from the JSON data.
The JSON data is being created from a feed using import.io.
Any help appreciated
JSON data here
<?php
$data = file_get_contents('https://query.import.io/store/connector/e18543ae-48d1-47d3-9dc7-c3d55cab2951/_query?_user=363ec2db-fb95-413f-9a20-3fe89acbf061&_apikey=HOXvwSMX4HlmqH123i5HeELV6BwKq%2BFRInTzXc4nfl5VtP0pJyChxMT9AEiu1Ozi0vWZmUB%2BKcSsxHz2ElHNAg%3D%3D&format=JSON&input/webpage/url=http%3A%2F%2Fsports.yahoo.com%2Fgolf%2Fpga%2Fleaderboard');
$array = json_decode($data, true);
$rows = array();
$index = 0;
foreach($array['results'] as $mydata)
{
print_r($mydata);
echo "<br>";
foreach($mydata as $key => $value)
{
print_r ($key);
print_r ($value);
echo $index;
echo "<br><br>";
$rows[] = "('" . $value . "')";
}
echo "<br>";
$index++;
}
echo "<br><br><br>";
print_r ($rows);
$values = implode(",", $rows);
echo "<br><br><br>";
print_r ($values);
$hostname = 'localhost'; // write the rest of your query
$username = 'username';
$password = 'password';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($values)");
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
First of here we have to fetch every row and then do another loop to fetch every value contained in that row, in this way we will obtain a 2D Array containing the data to format to put after in the db.
$i = 0;
foreach($array['results'] as $result){
foreach ($result as $key => $value)
$rows[$i][] = "'" . $value . "'";
$i++;
}
Then, here we format the data in order to fit our query that will be executed for every row fetched before.
try{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
foreach ($rows as $row) {
$row = implode(",",$row); //making a string from an array with each item separated by comma
$query = "INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($row)<br>";
$count = $dbh->exec($query);
}
$dbh = null;// close the database connection
}catch(PDOException $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;
} ?>

Two Dimensional arrays and both indexes

I have data coming from a query and loading it into a 2 dimensional array inside a loop.
I have the below code but when it prints out the array the index is missing.
How do I load a 2 dimensional aray with the first index being the $id value and second index being the $UserEmail and then how would I loop through the array to pull out each index ($id, $UserEmail)?
//the query
$query = "select id, UserEmail from User";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$ue = $row['UserEmail'];
$id = $row['id'];
if (strpos($ue,','))
{
$UserArrayEmail = explode(',',$ue);
foreach ($UserEmailArray as $u)
{
$ArrayTerm[$id][] = $u;
}
}
}
//looping through the array and getting value from $id and $UserEmail
foreach( $ArrayTerm as $ArrayT ) {
print_r($ArrayT);
foreach( $ArrayT as $value ) {
echo $value . "<br/>";
}
}
Please help.
mysql_connect() is deprecated your solution should use PDO instead.
This is how it could be done with PDO and will fix the indexes:
//fetch array from query
try {
$dbh = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
} catch (PDOException $e) {
// db error handling
}
$sth = $dbh->prepare("select id, UserEmail from user");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
while($row = $sth->fetch())) {
$emails = $row['UserEmail'];
$id = $row['id'];
if (strpos($emails,',')) {
$UserEmailArray = explode(',',$emails);
foreach ($UserEmailArray as $email) {
$ArrayT[$id][] = $email;
}
}
}
//repeat the same but with PDO data with other loops
}
Additionally, storing a list of data (in your case emails) in a single db column is not great for db normalization.
You have no type safety (VARCHAR can containanything), no referential integrity, no way of actually processing the data with the db (in SELECTs, JOINs etc).
For the db, the list of email addresses is just a bunch of random characters.
The relational database model has a simple rule: one attribute, one value. So if you have multiple values, you have multiple rows. That's what you should fix first. You'll need another table named "user_email_addresses" or something.
With this new table it could be something like:
function html_escape($raw) {
return htmlentities($raw, ENT_COMPAT , 'utf-8');
}
function log_exceptions($exception) {
echo $exception->getMessage(), '<br />', $exception->getTraceAsString();
}
set_exception_handler('log_exceptions');
$database = new PDO( 'mysql:host=localhost;dbname=DB', 'USER', 'PASS', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
$user_emails = array();
$emails = $database->query('
SELECT user_id , email
FROM user_email_addresses');
foreach ($emails as $email)
$user_emails[ $email['user_id'] ][] = $email['email_address'];
//address list
foreach ($user_emails as $user_id => $email_addresses) {
echo 'User: ' . html_escape($user_id) . '<br />';
foreach ($email_addresses as $email_address)
echo html_escape($email_address) . '<br />';
echo '<br />';

Categories