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

PHP PHP & Databases with PDO PDO Queries & Results Working With Results

2 Answers

Codin - Codesmite
Codin - Codesmite
8,600 Points
<?php

function db() {
  static $db = null;
  if (null === $db)
    $db = new PDO(...);
  return $db;
}

?>

:)

Your PDO connection details inplace of "..."

I would also reccomend storing your connection details outside of your websites root folder inside a config file for extra security.

Good explination here using sqli, but can easily be adapted using the same method for PDO: https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17

Mayur Pande
Mayur Pande
Courses Plus Student 11,711 Points

Hi, thanks for the answer, but I am still confused how to set up routing with the slim framework. I get how to make the connection to the database and retrieve results. For example I have a portfolio page where the url is /portfolio and I have items on there that I want to link to another template. So when I click a link item it will take me to another page (template using twig) that would have the url /portfolio/id where the id is obtained from mysql. I have done this so far using procedural code ;

This is my index.php file

<?php

require __DIR__ . '/vendor/autoload.php';
date_default_timezone_set ( "Europe/London" );

\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();

$app = new \Slim\Slim( array(
  'view' => new \Slim\Views\Twig()
));

$view = $app->view();
$view->parserOptions = array(
    'debug' => true,

);

$view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

//what happens here is what will run with our object
$app->get('/', function() use($app){
  $app->render('about.twig');
});

 //portfolio page
$app->get('/portfolio', function() use($app){
  $app->render('portfolio.twig');
})->name('portfolio');

$app->get('/portfolio/:id', function ($id) use ($app) {
    // include out mysql connection code and make the connection
    $db = mysqli_connect('localhost', 'root', 'ihatefuckingpasswords187', 'tom_db');


    // query the database
    $rs = mysqli_query($db, "SELECT * FROM documentaries WHERE id=$id" );
    echo '<pre>', print_r($rs), '</pre>';
    // convert the record set into an associative array so we can work with it easily
    $data = mysqli_fetch_assoc($rs);
    echo '<pre>', print_r($data), '</pre>';

    $app->render('portfolioitem.twig', array(
            'data' => $data
        )
    );
});

$app->get('/contact', function() use($app){
  $app->render('contact.twig');
})->name('contact');

$app->run();

?>

This is my main.twig file;

<!DOCTYPE html>
<html>
  <head>
    {% block head %}
      <meta charset="utf-8">
      <title>Tom Turner - Director of Photography</title>
      <link rel="stylesheet" href="css/normalize.css">
      <link href='https://fonts.googleapis.com/css?family=Changa+One|Open+Sans:400,400italic,700,700italic,800' rel='stylesheet' type='text/css'>
      <link rel="stylesheet" href="css/main.css">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      <script type="text/javascript" src="js/jquery.mixitup.min.js"></script>
      <script type="text/javascript" src="js/main.js"></script>
      <script type="text/javascript" src="js/responsivemenu.js"></script>

    {% endblock head %}
  </head>

  <body>
    <header>
      <a href="index.html" id="logo">
        <h1>Tom Turner</h1>
        <h2>Director of Photography</h2>
      </a>
      <nav>
        {% block nav %}
          <ul>
            <li><a href="{{ baseUrl() }}" class="selected">About</a></li>
            <li><a href="{{ siteUrl('/portfolio') }}">Portfolio</a></li>
            <li><a href="{{ siteUrl('/clients') }}">Clients</a></li>
            <li><a href="{{ siteUrl('/teaching') }}">Teaching</a></li>
            <li><a href="{{ siteUrl('/contact') }}">Contact</a></li>
          </ul>
        {% endblock nav %}
      </nav>
    </header>

    <div id="wrapper">

      {% block content %}
      {% endblock content %}

    </div>

     <footer class="main-footer">
       {% block footer %}


        <div id="footer-notes">
          <p>Tom Turner - Director of Photography</p>
          <p>&copy; Tom Turner - All Rights Reserved</p>
        </div>
       <div id="mayur">
          <p>&copy; 2015 Website by <a href="https//:www.mayurpande.com">Mayur Pande</a></p>

        </div>

        <div class="social-media">
          <ul>

              <li><a href="mailto:tom@allritesreversed.co.uk"><img src="img/mail_circle.png" alt="Email Logo" /></a></li>
              <li><a href="https://www.facebook.com/tom.turner.397501?fref=ts"><img src="img/fbcircle.png" alt="Facebook Logo" /></a></li>
              <li><a href="https://vimeo.com/user6107855"><img src="img/vimeo_circle.png" alt="Vimeo Logo" /></a></li>
              <li><a href="https://twitter.com/intent/tweet?screen_name=mayurpandeuk"><img src="img/twitter_circle.png" alt="Twitter Logo" /></a></li>

            </ul>
          </div>
       {% endblock footer %}
      </footer>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      <script type="text/javascript" src="js/jquery.mixitup.min.js"></script>
      <script type="text/javascript" src="js/main.js"></script>
      <script type="text/javascript" src="js/responsivemenu.js"></script>

  </body>
</html>

This is my porfolio.twig file;

{% extends 'main.twig' %}

{% block nav %}
     <ul>
        <li><a href="{{ baseUrl() }}" >About</a></li>
        <li><a href="{{ siteUrl('/portfolio') }}" class="selected">Portfolio</a></li>
        <li><a href="{{ siteUrl('/clients') }}">Clients</a></li>
        <li><a href="{{ siteUrl('/teaching') }}">Teaching</a></li>
        <li><a href="{{ siteUrl('/contact') }}">Contact</a></li>
     </ul>
 {% endblock nav %}

{% block content %}

      <section>
        <div class="showreel-container">
         <iframe src="https://player.vimeo.com/video/148640837?title=0&byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
        </div>
      </section>

      <section>

        <div id="controls" id="Controls">

            <button class="filter" data-filter="all">All</button>
            <button class="filter" data-filter=".documentaries">Documentary</button>
            <button class="filter" data-filter=".commercial">Commercial</button>
            <button class="filter" data-filter=".charity">Charity/NGO/Commisions</button>
            <button class="filter" data-filter=".music">Music</button>
            <button class="filter" data-filter=".drama">Drama</button>

        </div>

      <div id="Container" class="container">

          <div class="mix documentaries" data-myorder="1"><a href="{{ siteUrl('/portfolio/{{ data.id }}') }}""><img src="img/numbers-01" alt="Image one"/></a></div>
          <div class="mix commercial" data-myorder="2"><a href=""><img src="img/numbers-02" alt="Image two"/></a></div>
          <div class="mix commerical" data-myorder="3"><a href=""><img src="img/numbers-06" alt="Image six"/></a></div>
          <div class="mix charity" data-myorder="4"><a href=""><img src="img/numbers-09" alt="Image nine"/></a></div>
          <div class="mix music" data-myorder="5"><a href=""><img src="img/numbers-12" alt="Image twelve"/></a></div>
          <div class="mix drama" data-myorder="6"><a href=""><img src="img/numbers-01" alt="Image one"/></a></div>
          <div class="mix music" data-myorder="5"><a href=""><img src="img/numbers-12" alt="Image twelve"/></a></div>
          <div class="mix charity" data-myorder="5"><a href=""><img src="img/numbers-12" alt="Image twelve"/></a></div>

          <div class="gap"></div>
          <div class="gap"></div>

        </div>


      </section>

{% endblock content %}

and finally this is my portfolioitem.twig file;

{% extends 'main.twig' %}

{% block nav %}
     <ul>
        <li><a href="{{ baseUrl() }}" >About</a></li>
        <li><a href="{{ siteUrl('/portfolio') }}" class="selected">Portfolio</a></li>
        <li><a href="{{ siteUrl('/clients') }}">Clients</a></li>
        <li><a href="{{ siteUrl('/teaching') }}">Teaching</a></li>
        <li><a href="{{ siteUrl('/contact') }}">Contact</a></li>
     </ul>
 {% endblock nav %}
{% block content %}



  <section>
    <h2>This is a test</h2>
  </section>

{% endblock content %}

However when I run these it seems not to work when I click one of the links. However if I manually put the id number in the browser (/portfolio/1) it renders the porfolio.twig file however my stylesheet is not applied to it. I have no idea where I have gone wrong.

Codin - Codesmite
Codin - Codesmite
8,600 Points

Ah, I unfotunately do not have enough experience with slim to answer this. Hopefully another member has a solution.

If not it is well worth asking at www.stackoverflow.com, there is a community of very knowledgable programmers over there, I find the community a little more blunt and maybe less friendly, but you are sure to get a good answer if you tag your question with the relevant tags (PHP, Slim, PDO) etc

If you do get a good answer definately post it here so others can benifet from the answer :)

Mayur Pande
PLUS
Mayur Pande
Courses Plus Student 11,711 Points

Ashley Skilton thanks anyway, managed to get it sorted doing it without slim. I ended up asking at stack even there someone was having difficulty helping me! I agree with you as well their community can be very blunt sometimes.