Jump to content
Larry Ullman's Book Forums

David John

Members
  • Posts

    41
  • Joined

  • Last visited

Posts posted by David John

  1. Well, it is now outputting the JSON(.php page) correctly, but I am getting this message on my HTML: "TypeError: (name of variable) is undefined"

     

    This question is more about js than PHP, but since it's germane to the original post, I'd like to ask it here. What's the correct way to run a while...loop with PDO? The error message I'm getting in the console could be from my js or my PHP.

    $sql = "SELECT Table1.state_id, Table1.address, Table1.city, Table1.state, Table1.zip FROM Table1 INNER JOIN States ON Table1.state_id = States.state_id WHERE Table1.state_id=:id GROUP BY Table1.city ORDER BY Table1.city";
    
    $host = "localhost";
    $user = "me";
    $pass = "mypassword";
    $databasename = "my_db";
    try {
    $dbh = new PDO("mysql:host=$host;dbname=$databasename", $user, $pass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(":id", $_GET[id]);
    $stmt->execute();
    $city = $stmt->fetchAll(PDO::FETCH_OBJ);
    
    $dbh = null;
    echo '{"items":'. json_encode($city) .'}';
    } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
    

     

    And here's part of my js:

    $.getJSON(URL + 'mysite.php?id='+id, displayCity);
    });
    function displayCity(data) {
    var city = data.item;
    console.log(city);
    
    $('#actionList').append('<li><a href="mydetails.html?id=' + city.state_id + '">' +
    '<div class="city" style="color:rgb(102,102,102); font-size:1.0em;">' + city.city + '</div>' +
    '<div class="church" style="font-size:0.75em;">' + city.church + '</div>' +
    '<div class="church" style="font-size:0.75em;">' + city.address + '</div>' +
    '<div class="church" style="font-size:0.75em;">' + city.city + '</div>' +
    '<div class="city" style="font-size:0.75em;">' + city.state + '</div>' +
    '<div class="zip" style="font-size:0.75em;">' + city.zip + '</div>' +
    '</a></li>');
    $('#actionList').listview('refresh');
    }
    

  2. I'm using PHP Data Objects on my project, and I ran into some difficulty with the WHERE clause.

    Here's an example of my code:

    $state = $_GET['state'];
    $sql = "SELECT id, address, city, state, zip, phone, website, FROM Table01 WHERE 'state'=:state ORDER BY city ASC";
    $host = "localhost";
    $user = "me";
    $pass = "mypassword";
    $databasename = "my_db";
    try {
    $dbh = new PDO("mysql:host=$host;dbname=$databasename", $user, $pass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->query($sql);
    $stmt->bindParam("state", $_GET['state']);
    $cities = $stmt->fetchAll(PDO::FETCH_OBJ);
    $dbh = null;
    echo '{"items":'. json_encode($cities) .'}';
    } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
    

    When I run it, I get nothing in the Firefox console. But when the "WHERE" clause is taken out, it outputs everything from the database. What am I doing wrong?

  3. Thank you, HartleySan.

     

    Here's another thing I was wondering:

     

    In my PHP above, when the user clicks the link, he/she goes to http://mysite.com?address= ' . $row->address . '

     

    Is it possible to pass in a PHP variable to js? (In other words, can $row->address be grabbed and used in a js variable?)

    var city_details = document.getElementById("php variable will go here").value;
    ajax.open("GET","ajax2.php?state="+city_details,true);
    

     

    Hopefully, that question is not too ambiguous.

  4. Hi, Dave.

     

    That was a great suggestion! It was outputting in the console, so I made one small change in the js. Instead of this:

    ajaxDisplay.value = ajax.responseText;
    

    I switched it to this:

    ajaxDisplay.innerHTML = ajax.responseText;
    

    And now it works!

    Thanks again for the idea.

     

    I'd also like to thank Larry for not only the "Modern Javascript" book, but the PHP books as well. I've learned a lot from them.

  5. Happy New Year!

     

    Here's my scenario: I need to return database values from a PHP script using AJAX to an HTML page, and for some reason it's not working.

     

    The js code:

    <script>
    function getXMLHttpRequestObject() {
    var ajax = null;
    if(window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
    ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
    }
    return ajax;
    }
    function showLocation() {
    var ajax = getXMLHttpRequestObject();
    ajax.onreadystatechange = function() {
    if (ajax.readyState == 4) {
    if ( ( ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304 )) {
    var ajaxDisplay = document.getElementById("uslocations");
    ajaxDisplay.value = ajax.responseText;
    }
    }
    }
    var state_lookup = document.getElementById("state_lookup").value;
    ajax.open("GET","ajax2.php?state="+state_lookup,true);
    ajax.send(null);
    };
    </script>
    

    The HTML:

    <div data-role="page" id="something">
    <div data-role="header">
     <a href="#page" data-icon="arrow-l" data-iconpos="left">Back</a>
    <h1>Find a City</h1>
    </div>
    <div data-role="content">
    <form>
    <select id="state_lookup" onchange="showLocation()">
    <option value="">Select a state:</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    </select>
    </form>
    
    <div id="uslocations">
    Here is the placeholder for content.
    </div>
    <div data-role="footer">
    </div>
    </div>
    

     

    And finally, the PHP:

    <?php
    require ('Connections/oopConnect.php');
    $state = $_GET['state'];
    $q = "SELECT schedule_id, state_id, address, city, state, zip FROM dbTable WHERE state = '$state' ORDER BY city ASC";
    $r = $mysqli->query($q);
    $num = $r->num_rows;
    if($num > 0 ) {
    while ($row = $r->fetch_object()) {
    echo '
    <div class="headline"> ' . $row->state . '</div><br><br>
    <ul data-role="listview"><br>
    <li><a href="http://mysite.com?address= ' . $row->address . ' ">
    <div class="address">' . $row->address . ' </div>
    <div class="city1"> ' . $row->city . ' </div>
     <div class="state"> ' . $row->state . ' </div>
    <div class="zip"> ' . $row->zip . '</div>
    <br>
    </li>
    </ul></a>
    ';
    }
    } else {
    echo '<p>Nothing to see here.';
    }
    ?>
    

     

    Is there a syntactical issue with what I am doing? I tested the PHP, and it is properly returning data, but I am not getting the AJAX to work properly. Any help would be appreciated.

  6. Quick update:

    I'm able to get the form to work now, but the values are not updating in the database. Here's an example of my code:

     

    require('includes/utilities.inc.php');

     

    $q = 'SELECT id, city, state, zip FROM address WHERE id=:id';

    $stmt = $pdo->prepare($q);

    $r = $stmt->execute(array(':id' => $_GET['id']));

     

    if($r) {

    $stmt->setFetchMode(PDO::FETCH_CLASS, 'Data');

    $info = $stmt->fetch();

    }

    if ($info) {

    $idInfo = $info->getId();

    $cityInfo = $info->getCity();

    $stateInfo = $info->getState();

    $zipInfo = $info->getZip();

     

    }

    //create a new form

    set_include_path(get_include_path() . PATH_SEPARATOR . '/my/path/');

    require('HTML/QuickForm2.php');

    $form = new HTML_QuickForm2('editPageForm');

    $form->addDataSource(new HTML_QuickForm2_DataSource_Array(array('id' => $idInfo, 'city' => $cityInfo, 'state' => $stateInfo, 'zip' => $zipInfo,)));

    //add city

    $city = $form->addElement('text', 'city');

    $city->setLabel('City');

    $city->addFilter('strip_tags');

    $city->addRule('required', 'Please enter a city.');

    //add state

    $state = $form->addElement('text', 'state');

    $state->setLabel('State');

    $state->addFilter('strip_tags');

    $state->addRule('required', 'Please enter the state.');

     

    //add zip

    $zip = $form->addElement('text', 'zip');

    $zip->setLabel('Zip Code');

    $zip->addFilter('trim');

    $zip->addRule('required', 'Please enter the zip code.');

     

     

    $submit = $form->addElement('submit', 'submit', array('value'=>'Edit'));

     

     

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    if ($form->validate()) {

    $q = 'UPDATE address SET city=:city, state=:state, zip=:zip WHERE id=:id';

    $stmt = $pdo->prepare($q);

    $r = $stmt->execute(array(':id' => $idInfo, ':city' => $cityInfo, ':state' => $stateInfo, ':zip' => $zipInfo, ));

    if ($r) {

    $form->toggleFrozen(true);

    $form->removeChild($submit);

    }

    }

    }

    //display login

    include('includes/header.inc.php');

    include('views/edit_page.php');

    include('includes/footer.inc.php');

    ?>

  7. From the book:

     

     

    To explain what happens in detail, is that $form is an object holding several HTML elements in an array. The object must have a method called __toString() that let you use echo on an object. The __toString() method is a magic method like __construct(), and it will be called each time you try to print info from an object. An alternative approach would be to explicitly have a method that would let you echo out the form.

     

    As a simple explanation, I wrote this super simple class for you. If you try to run this, you'll see that you can print the list using both "echo $list" and "echo list->printList();". Functionally, these methods are equal to each other. All printList() does is to call __toString().

    <?php
    
    class HtmlList
    {
    
    private $list = array();
    
    /**
    * Adds elements to the list
    */
    public function add( $element )
    {
    $this->list[] = $element;
    }
    
    // I am called using $list->printList()
    public function printList()
    {
    return $this->__toString(); // Here we call __toString()
    }
    
    // I am called using echo $list
    public function __toString()
    {
    $out = "";
    
    // Add
    foreach ( $this->list as $element )
    {
    $out .= "<li>{$element}</li>";
    }
    return $out.'<br />';
    }
    
    }
    
    $list = new HtmlList();
    $list->add("First list element");
    $list->add("And a new one");
    $list->add("After two comes three");
    
    // Print the list
    echo $list;
    
    // Also print the list
    echo $list->printList();
    

     

    Hope that helps you to understand. The HTML_QuickForm2 class is obviously a lot more advanced than this example, but it works exactly the same way as the code above.

     

    Hi, Antonio.

     

    Thank you. I appreciate your taking the time to show me an example of __toString.

     

    Check out this example: http://pear.php.net/...m2.tutorial.php

    It uses the addDataSource() method to assign default values to form elements. That's what you want.

     

    Thanks, Larry. That's exactly how I went about it. The database entries are outputting correctly, but I keep getting this error message when I try to submit:

    Call to a member function isSubmitted() on a non-object in /****/views/edit_page.php on line 9

     

    I'll keep at it.

  8. Hi,

     

    The more I learn about and use OOP, the more I like it. One of the "Review and Pursue" exercises is implementing an edit page feature, and I would like to know how to go about it. Here's what I am doing (which is not entirely correct):

     

    //create a new form

    set_include_path(get_include_path() . PATH_SEPARATOR . '/my/path');

    require('HTML/QuickForm2.php');

    $form = new HTML_QuickForm2('editPageForm');

    //add something

    $something = $form->addElement('text', 'something');

    $something->setLabel('Something');

    $something->addFilter('strip_tags');

     

    //add anotherThing

    $anotherThing = $form->addElement('text', 'anotherThing');

    $anotherThing->setLabel('AnotherThing');

    $anotherThing->addFilter('strip_tags');

     

    $submit = $form->addElement('submit', 'submit', array('value'=>'Edit This Page'));

     

    //get page from database

    $q = 'SELECT id, something, anotherThing FROM database WHERE id=:id';

    $stmt = $pdo->prepare($q);

    $r = $stmt->execute(array(':id' => $_GET['id']));

     

    //if OK, fetch record

    if ($r) {

    $stmt->setFetchMode(PDO::FETCH_CLASS, 'Class');

    $schedule = $stmt->fetch();

    //confirm it exists

    if($schedule) {

    $q = 'UPDATE database SET something=:something, anotherThing=:anotherThing WHERE id=:id LIMIT 1';

    $stmt = $pdo->prepare($q);

    $r = $stmt->execute(array(':something' => $something->getValue(), ':anotherThing' => $anotherThing->getValue()));

    } else {

    throw new Exception('An invalid page ID was provided.');

    }

    } else {

    throw new Exception('An invalid page ID was provided.');

    }

     

    Not sure how to properly approach this one, but it's not retrieving the records in the input textbox. Any advice would be greatly appreciated :)

×
×
  • Create New...