0

Here's my code:

<form action="" method="post">
        <fieldset>
            Date 1: <input type="text" name="date1">
            Date 2: <input type="text" name="date2">
        </fieldset>
            <button type="submit" name="Search">
    </form>

    <?php
    try {
        $db = new PDO('mysql:host=localhost;dbname=db;charset=utf8', 'user', 'pass');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (Exception $e) {
        echo "DB is down";
        exit; 
    }

    try {
        $results = $db->query("SELECT * FROM instructor WHERE date_hired BETWEEN ? AND ?"); 
    } catch (Exception $e) {
        echo "No data found";
        exit;
    }

    echo "<pre>";
    var_dump($results->fetchAll(PDO::FETCH_ASSOC));

    ?> 

How would I change the PHP code to use the form that I have created to take parameters?

I want to be able to enter 2 dates into the form, so it goes into the query, then output the results.

1
  • 1
    You tagged mysqli, but you didn't actually use the mysqli functions. Just so you know where look for the documentation, you're using the PDO abstraction layer, and can read about it at: php.net/manual/en/class.pdo.php Commented Nov 22, 2013 at 0:48

2 Answers 2

2

Change this line:

$results = $db->query("SELECT * FROM instructor WHERE date_hired BETWEEN ? AND ?");

to

$results = $db->prepare("SELECT * FROM instructor WHERE date_hired BETWEEN ? AND ?");
$results->execute(array($_POST['date1'], $_POST['date2']));

Also, here's a great link to get you started:

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Sign up to request clarification or add additional context in comments.

2 Comments

That's immeasurably better.
Thanks for the link. Been looking for something like this. I'm getting some errors but i'll check the page and get back to here
1

When executing statements with placeholders you must give the binding data:

$sth = $db->prepare("SELECT * FROM ... BETWEEN ? AND ?");
$results = $sth->execute(array($start, $end));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.