Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
David Luc
2,169 PointsInserting MySQL table outputs into multidimensional array (Simple PHP Application)
Hello,
In the Build a Simple PHP Application under Listing Inventory Items => Nesting Arrays Within Arrays, the values for each T-Shirt are entered statically. I was wondering if it is possible to use the PDO command fetch_assoc in order to insert the data dynamically using SQL? Some form of this code is what I am referring to:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM animals";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$result = $stmt->fetch(PDO::FETCH_ASSOC);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Any help would be greatly appreciated. Also, keep up the good work with all the new content, very informative.
1 Answer
Randy Hoyt
Treehouse Guest TeacherIt absolutely would be possible. That's actually the next PHP course we're working on, using PHP and MySQL. I'll walk through moving the Shirts 4 Mike product catalog from a static array to a MySQL database.
David Luc
2,169 PointsDavid Luc
2,169 PointsThank you for your prompt reply Randy. Just out of curiosity, when will that course be coming out?
Randy Hoyt
Treehouse Guest TeacherRandy Hoyt
Treehouse Guest TeacherI'm not sure of the schedule. Let me see what I can find out.
David Luc
2,169 PointsDavid Luc
2,169 PointsThank you, your feedback is much appreciated. Being able to perform this function is key, as you can't really make the website dynamic without this type of functionality. I've been breaking my head trying to integrate some version of that code into products.php, but it just hasn't worked out. Really hope the course comes out soon.