Jump to content

bluethundr

Members
  • Posts

    34
  • Joined

  • Last visited

    Never

Posts posted by bluethundr

  1. Hello,

     

    I am trying to get the hang of php using some examples that I found in a book. I've been making progress lately, but one thing has me a bit stumped.

     

     

    In an HTML form that I am echoing through PHP I would like to embed smaller chunks of php in the code like so:

     

    echo '<br /><br />
            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            <label for="subject">Subject of email:</label><br />
            <input id="subject" name="subject" type="text" value="<?php echo $subject;?>"><br />
            <label for="elvismail">Body of email:</label><br />
            <textarea id="elvismail" name="elvismail" rows="8" cols="40">"<?php echo $text;?>"       </textarea><br />
            <input type="submit" name="Submit" value="Submit" />
            </form>';
    

     

     

    If I do embed the smaller chunks of php in the form the way I've just shown you the script instantly breaks and the web page shows only a white screen of death.

     

    And I see this in the web server logs

    [sat Jun 30 19:12:54 2012] [notice] child pid 7769 exit signal Segmentation fault (11)
    

     

    If I remove the smaller bits of php as I show here the web page starts working again

     

    echo '<br /><br />
            <form method="post" action="sendemail.php">
            <label for="subject">Subject of email:</label><br />
            <input id="subject" name="subject" type="text"><br />
            <label for="elvismail">Body of email:</label><br />
            <textarea id="elvismail" name="elvismail" rows="8" cols="40"></textarea><br />
            <input type="submit" name="Submit" value="Submit" />
            </form>';
    

     

    Here, I'll show the entire script so you can get a better sense of what it does

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Make Me Elvis - Send Email</title>
      <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
      <img src="blankface.jpg" width="161" height="350" alt="" style="float:right" />
      <img name="elvislogo" src="elvislogo.gif" width="229" height="32" border="0" alt="Make Me Elvis" />
      <p><strong>Private:</strong> For Elmer's use ONLY<br /><br 
      Write and send an email to mailing list members.</p>
    
    <?php
    
      error_reporting(E_ALL);
      ini_set('display_errors', 'On');
    
       if (isset($_POST['Submit'])) {
      
         $from = 'bluethundr@mydomain.com';
         $subject = $_POST['subject'];
         $text = $_POST['elvismail'];
         $output_form = "false";
       
         if (empty($subject) && empty($text)) {
         echo 'You forgot the email subject and body.<br />';
         $output_form = 'true';  
      
        }
      
      
         if (empty($subject) && !empty($text)) {
         echo 'You forgot the email subject.<br />';
         $output_form="true";
      
        }
      
        if ((!empty($subject)) && empty($text)) {
      
        echo 'You forgot the email body text.<br />';
        $output_form="true";
        
      
        }
        
    }  else { 
    
          $output_form = 'true';
          
       }
    
      
      
       if ($output_form == 'true') {
       
    
      echo '<br /><br />
            <form method="post" action="sendemail.php">
            <label for="subject">Subject of email:</label><br />
            <input id="subject" name="subject" type="text"><br />
            <label for="elvismail">Body of email:</label><br />
            <textarea id="elvismail" name="elvismail" rows="8" cols="40"></textarea><br />
            <input type="submit" name="Submit" value="Submit" />
            </form>';
            
      
      } else {
    
      $dbc = mysqli_connect('127.0.0.1', 'admin', 'secret
    
    ', 'elvis_store')
        or die('Error connecting to MySQL server.');
    
      $query = "SELECT * FROM email_list";
      $result = mysqli_query($dbc, $query)
        or die('Error querying database.');
    
      while ($row = mysqli_fetch_array($result)){
        $to = $row['email'];
        $first_name = $row['first_name'];
        $last_name = $row['last_name'];
        $msg = "Dear $first_name $last_name,\n$text";
        mail($to, $subject, $msg, 'From:' . $from);
        echo 'Email sent to: ' . $to . '<br />';
      } 
    
      mysqli_close($dbc);
      
    }  
      
      
    ?>
    
    </body>
    </html>
    

     

    I was hoping that someone might be out there that could understand this problem and point out where I'm going wrong.

     

    Thanks!

  2. I wrote an application in PHP that intends to authenticate users against a MySQL database.

     

    If you surf to localhost/login.html you see the login page. I created an authentication database and added a user to it. When I try to sign in as the user I added to the database instead of logging into the application the user is immediatly shunted to the logout page saying that the user cannot login  :shrug::

     

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                          "http://www.w3.org/TR/html401/loose.dtd">
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <title>Login</title>
    </head>
    <body>
    <h1>Application Login Page</h1>
    <form method="POST" action="logincheck.php">
    <table>
      <tr>
        <td>Enter your username:</td>
        <td><input type="text" size="10" name="loginUsername"></td>
      </tr>
      <tr>
        <td>Enter your password:</td>
        <td><input type="password" size="10" name="loginPassword"></td>
      </tr>
    </table>
    <p><input type="submit" value="Log in">
    </form>
    </body>
    </html>
    

     

    There is an include file with the user authentication and session authentication functions

     

    <?php
    
    function authenticateUser($connection, $username, $password)
    {
      // Test the username and password parameters
      if (!isset($username) || !isset($password))
        return false;
    
      // Create a digest of the password collected from
      // the challenge
      $password_digest = md5(trim($password));
    
      // Formulate the SQL find the user
      $query = "SELECT password FROM users WHERE user_name = '{$username}'
                AND password = '{$password_digest}'";
    
      // Execute the query
      if (!$result = @ mysql_query ($query, $connection))
        showerror();
    
      // exactly one row? then we have found the user
      if (mysql_num_rows($result) != 1)
        return false;
      else
        return true;
    }
    
    // Connects to a session and checks that the user has
    // authenticated and that the remote IP address matches
    // the address used to create the session.
    function sessionAuthenticate()
    {
      // Check if the user hasn't logged in
      if (!isset($_SESSION["loginUsername"]))
      {
        // The request does not identify a session
        $_SESSION["message"] = "You are not authorized to access the URL 
                                {$_SERVER["REQUEST_URI"]}";
    
        header("Location: logout.php");
        exit;
      }
    
      // Check if the request is from a different IP address to previously
      if (!isset($_SESSION["loginIP"]) || 
         ($_SESSION["loginIP"] != $_SERVER["REMOTE_ADDR"]))
      {
        // The request did not originate from the machine
        // that was used to create the session.
        // THIS IS POSSIBLY A SESSION HIJACK ATTEMPT
    
        $_SESSION["message"] = "You are not authorized to access the URL 
                                {$_SERVER["REQUEST_URI"]} from the address 
                                {$_SERVER["REMOTE_ADDR"]}";
    
        header("Location: logout.php");
        exit;
      }
    }
    
    ?>
    

     

    Then if a user CAN authenticate they are supposed to land at the home page of the application:

     

    
    
    <?php
    
    require "authentication.inc"; 
    require_once "HTML/Template/ITX.php";
    
    session_start();
    
    // Connect to an authenticated session or relocate to logout.php
    sessionAuthenticate();
    
    $template = new HTML_Template_ITX("./templates");
    $template->loadTemplatefile("home.tpl", true, true);
    
    $template->setVariable("USERNAME", $_SESSION["loginUsername"]);
    $template->parseCurrentBlock();
    $template->show();
    ?>
    

     

    This file uses a template file to display it's contents:

     

    
    
    <?php
    
    require "authentication.inc"; 
    require_once "HTML/Template/ITX.php";
    
    session_start();
    
    // Connect to an authenticated session or relocate to logout.php
    sessionAuthenticate();
    
    $template = new HTML_Template_ITX("./templates");
    $template->loadTemplatefile("home.tpl", true, true);
    
    $template->setVariable("USERNAME", $_SESSION["loginUsername"]);
    $template->parseCurrentBlock();
    $template->show();
    ?>
    

     

    If the user selects the logout page this is what they see. And as I mentioned users are unable to login so they automatically end up here instead of the home page.

     

    <?php
      require_once "HTML/Template/ITX.php";
      session_start();
    
      $message = "";
    
      // An authenticated user has logged out -- be polite and thank them for
      // using your application.
      if (isset($_SESSION["loginUsername"]))
        $message .= "Thanks {$_SESSION["loginUsername"]} for
                     using the Application.";
    
      // Some script, possibly the setup script, may have set up a 
      // logout message
      if (isset($_SESSION["message"]))
      {
        $message .= $_SESSION["message"];
        unset($_SESSION["message"]);
      }
    
      // Destroy the session.
      session_destroy();
    
      // Display the page (including the message)
      $template = new HTML_Template_ITX("./templates");
      $template->loadTemplatefile("logout.tpl", true, true);
      $template->setVariable("MESSAGE", $message);
      $template->parseCurrentBlock();
      $template->show();
    ?>
    

     

    Logout uses a template file also:

     

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                          "http://www.w3.org/TR/html401/loose.dtd">
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <title>Logout</title>
    </head>
    <body>
      <h1>Application Logout Page</h1>
      {MESSAGE}
      <p>Click <a href="login.html">here</a> to log in.
    </body>
    </html>
    

     

    the database is _extremely_ simple by design:

     

    mysql> use authentication;
    Database changed
    
    mysql> SHOW TABLES;
    +--------------------------+
    | Tables_in_authentication |
    +--------------------------+
    | users                    |
    +--------------------------+
    1 row in set (0.00 sec)
    
    > CREATE TABLE users (
    -> user_name char(50) NOT NULL,
    -> password char(32) NOT NULL,
    -> PRIMARY KEY (user_name),
    -> ) type=MyISAM;
    
    

     

    and I added a user to test the app

     

    
    mysql> SELECT * FROM users;
    +------------+----------+
    | user_name  | password |
    +------------+----------+
    | bluethundr | secretpass |
    +------------+----------+
    1 row in set (0.00 sec)
    
    

     

    but all the user ever sees is this message even tho the correct user name and password are entered:

     

    Application Logout Page
    Could not connect to the application as 'bluethundr'
    Click here to log in. 
    

     

    :'( :'( :'( :'( :'( :'( :'(

     

    Can anyone slap me upside the head with the clue-by-four on this one?

     

     

     

     

  3. Weird. When I pasted in the debugging code the page worked as it should have and forwarded the user to logout page as it should have and everything displayed. No errors were shown.

     

    But I am having a new problem with this mini - application I am trying to write. Users cannot login. When they try to they are automatically sent to a page telling them they are not "authorized". But this is a database access problem and I think I will ask that question in the mysql forum.

     

    Also I didn't seem to get any response on the "which books to read" question. Did I ask this question in the wrong forum? Is there another forum that I should have asked it in?

     

    Thanks!

  4. hey guys,

     

    I wrote a simple script that is meant to display a home page that relies on a template file. For some reason this isn't working. I was hoping you could help me determine why home.php does not display.

     

    Also I wanted to find out which books you felt were best to learn both PHP and MySQL separately. Ideally I would like to treat both topics as separate endeavors before I try to combine them. Which books helped you be the most successful at understanding both?

     

    Here are the scripts

     

    home.php

    <?php
    require "authentication.inc"; 
    require_once "HTML/Template/ITX.php";
    
    session_start();
    
    // Connect to an authenticated session or relocate to logout.php
    sessionAuthenticate();
    
    $template = new HTML_Template_ITX("./templates");
    $template->loadTemplatefile("home.tpl", true, true);
    
    $template->setVariable("USERNAME", $_SESSION["loginUsername"]);
    $template->parseCurrentBlock();
    $template->show();
    ?>
    

     

    home.tpl

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                          "http://www.w3.org/TR/html401/loose.dtd">
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <title>Home</title>
    </head>
    <body>
      <h1>Welcome to the application</h1>
      You are logged on as {USERNAME}
      <p><a href="password.php">Change Password</a>
      <p><a href="logout.php">Logout</a>
    </body>
    </html>
    

     

    [attachment deleted by admin]

  5. Hello again. I am doing yet another example from the O'Reilly book "PHP and MySQL" that isn't rendering.

     

    I have removed all of the error suppressing '@' symbols in the script and my php.ini file has the following set:

     

    error_reporting = E_ALL
    display_errors = 1
    

     

    Other scripts work and are able to access my MySQL database. My phpinfo().php script looks to be okay. But this script for some reason renders as blank.

     

    <?php
    require 'db.inc';
    require_once "HTML/Template/ITX.php";
    
    function formerror(&$template, $message, &$errors)
    {
      $errors = true;
      $template->setCurrentBlock("error");
      $template->setVariable("ERROR", $message);
      $template->parseCurrentBlock("error");
    }
    
    if (!($connection =  mysql_connect("localhost", "thatguy", "yahright?")))
       die("Could not connect to database");
    
    $firstname = mysqlclean($_POST, "firstname", 50, $connection);
    $surname = mysqlclean($_POST, "surname", 50, $connection);
    $phone = mysqlclean($_POST, "phone", 20, $connection);
    
    $template = new HTML_Template_ITX("./templates");
    $template->loadTemplatefile("example.8-10.tpl", true, true);
    
    $errors = false;
    
    if (empty($firstname))
      formerror($template, "The first name field cannot be blank.", $errors);
    
    if (empty($surname))
      formerror($template, "The surname field cannot be blank.", $errors);
    
    if (empty($phone))
      formerror($template, "The phone field cannot be blank", $errors);
    
    // Now the script has finished the validation, show any errors
    if ($errors)
    {
      $template->show();
      exit;
    }
    
    // If we made it here, then the data is valid
    if (!mysql_select_db("telephone", $connection))
      showerror();
    
    // Lock the table
    $query = "LOCK TABLES phonebook WRITE";
    if (!( mysql_query ($query, $connection)))
       showerror();
    
    // Find the maximum phonebook_id value that's in use
    $query = "SELECT max(phonebook_id) FROM phonebook";
    if (!($result =  mysql_query ($query, $connection)))
       showerror();
    
    $row = mysql_fetch_array($result);
    
    // Set the new value for the primary key
    $phonebook_id = $row["max(phonebook_id)"] + 1;
    
    // Insert the new phonebook entry
    $query = "INSERT INTO phonebook VALUES
              ({$phonebook_id}, '{$surname}', '{$firstname}', '{$phone}')";
    if (!(@ mysql_query ($query, $connection)))
       showerror();
    
    // Unlock the table
    $query = "UNLOCK TABLES";
    if (!( mysql_query ($query, $connection)))
       showerror();
    
    // Show the phonebook receipt
    header("Location: example.8-5.php?status=T&phonebook_id={$phonebook_id}");
    ?>
    

  6. Thanks, I added the missing equal sign.  ;) But for some reason this code is still not rendering.

     

    example.8-12.php

    <?php
    require 'db.inc';
    require_once "HTML/Template/ITX.php";
    
    function formerror(&$template, $message, &$errors)
    {
      $errors = true;
      $template->setCurrentBlock("error");
      $template->setVariable("ERROR", $message);
      $template->parseCurrentBlock("error");
    }
    
    if (!($connection =  mysql_connect("localhost", "thatguy", "yahright?")))
       die("Could not connect to database");
    
    $phonebook_id = mysqlclean($_POST, "phonebook_id", 5, $connection);
    $firstname = mysqlclean($_POST, "firstname", 50, $connection);
    $surname = mysqlclean($_POST, "surname", 50, $connection);
    $phone = mysqlclean($_POST, "phone", 20, $connection);
    
    $template = new HTML_Template_ITX("./templates");
    $template->loadTemplatefile("example.8-10.tpl", true, true);
    
    $errors = false;
    
    if (empty($firstname))
      formerror($template, "The first name field cannot be blank.", $errors);
    
    if (empty($surname))
      formerror($template, "The surname field cannot be blank.", $errors);
    
    if (empty($phone))
      formerror($template, "The phone field cannot be blank", $errors);
    
    // Now the script has finished the validation, show any errors
    if ($errors)
    {
      $template->show();
      exit;
    }
    
    // If we made it here, then the data is valid
    if (!mysql_select_db("telephone", $connection))
      showerror();
    
    // Update the phonebook entry
    $query = "UPDATE phonebook SET surname = '{$surname}',
             firstname = '{$firstname}',
             phone = '{$phone}'
             WHERE phonebook_id = {$phonebook_id}";
    
    if (!( mysql_query ($query, $connection)))
       showerror();
    
    // Show the phonebook receipt
    header("Location: example.8-5.php?status=T&phonebook_id={$phonebook_id}");
    ?>
    

  7. OK, thanks and duly noted.  8)

     

    The code has been changed to the following with NO change to the result.  :shrug:

     

    Still no detailed error and with the same cryptic error message.

     

    example.8-4.php

    <?php
    require "db.inc";
    
    // Test for user input
    if (!empty($_GET["surname"]) &&
        !empty($_GET["firstname"]) &&
        !empty($_GET["phone"]))
    {
      if (!($connection =  mysql_connect("localhost", "thatguy", "yahright?")))
         die("Could not connect to database");
    
      $surname = mysqlclean($_GET, "surname", 50, $connection);
      $firstname = mysqlclean($_GET, "firstname", 50, $connection);
      $phone = mysqlclean($_GET, "phone", 20, $connection);
    
      if (!mysql_select_db("telephone", $connection))
         showerror();
    
      // Insert the new phonebook entry
      $query = "INSERT INTO phonebook VALUES
                (NULL, '{$surname}', '{$firstname}', '{$phone}')";
    
      if (mysql_query ($query, $connection))
      {
        header("Location: example.8-5.php?status=T&" .
               "phonebook_id=". mysql_insert_id($connection));
        exit;
      } else {
            // the query failed, do some basic error reporting -
           echo mysql_error();
      }
    } // if empty()
    
    header("Location: example.8-5.php?status=F");
    ?>
    

  8. I am attempting to follow along in an example in a book ("PHP and MySQL" by O'Reilly, ISBN-13: 978-0-596-000543-1).

     

    The example's point is to add info from a web form to a database while preventing a reload of the webpage from duplicating the item in that database and assigning the item a unique primary key with the auto_increment feature of MySQL.

     

    There is a main php script (example.8-4.php) that calls a second (example.8-5.php) and uses a third template file living in ./templates in the webroot (example.8-6.tpl).

     

    I have the directives:

     

    error_reporting E_ALL
    display_errors = 1

     

    set in my php.ini file. I have also removed the error suppression ('@') from the mysql commands in an effort to determine the exact error. However all that happens when I access the example.8-4.php script, is I get an error page displayed that shows me message 'A database error occurred.' It seems that new eyes are needed at this point and any help rendered would be appreciated.

     

    example.8-4.php

    <?php
    require "db.inc";
    
    // Test for user input
    if (!empty($_GET["surname"]) &&
        !empty($_GET["firstname"]) &&
        !empty($_GET["phone"]))
    {
      if (!($connection =  mysql_connect("localhost", "thatguy", "yahright?")))
         die("Could not connect to database");
    
      $surname = mysqlclean($_GET, "surname", 50, $connection);
      $firstname = mysqlclean($_GET, "firstname", 50, $connection);
      $phone = mysqlclean($_GET, "phone", 20, $connection);
    
      if (!mysql_select_db("telephone", $connection))
         showerror();
    
      // Insert the new phonebook entry
      $query = "INSERT INTO phonebook VALUES
                (NULL, '{$surname}', '{$firstname}', '{$phone}')";
    
      if (@mysql_query ($query, $connection))
      {
        header("Location: example.8-5.php?status=T&" .
               "phonebook_id=". mysql_insert_id($connection));
        exit;
      }
    } // if empty()
    
    header("Location: example.8-5.php?status=F");
    ?>
    

     

    example.8-5.php

    <?php
    require "db.inc";
    require_once "HTML/Template/ITX.php";
    
    if (!($connection =  mysql_connect("localhost", "thatguy", "yahright?")))
       die("Could not connect to database");
    
    $status = mysqlclean($_GET, "status", 1, $connection);
    
    $template = new HTML_Template_ITX("./templates");
    $template->loadTemplatefile("example.8-6.tpl", true, true);
    
    switch ($status)
    {
      case "T":
        $phonebook_id = mysqlclean($_GET, "phonebook_id", 5, $connection);
    
        if (!empty($phonebook_id))
        {
          if (!mysql_select_db("telephone", $connection))
             showerror();
    
          $query = "SELECT * FROM phonebook WHERE 
                    phonebook_id = {$phonebook_id}";
    
          if (!($result = @mysql_query ($query, $connection)))
            showerror();
    
          $row = @ mysql_fetch_array($result);
    
          $template->setCurrentBlock("success");
          $template->setVariable("SURNAME", $row["surname"]);
          $template->setVariable("FIRSTNAME", $row["firstname"]);
          $template->setVariable("PHONE", $row["phone"]);
          $template->parseCurrentBlock();
          break;
        }
    
      case "F":
        $template->setCurrentBlock("failure");
        $template->setVariable("MESSAGE", "A database error occurred.");
        $template->parseCurrentBlock();
        break;
    
      default:
        $template->setCurrentBlock("failure");
        $template->setVariable("MESSAGE", "You arrived here unexpectedly.");
        $template->parseCurrentBlock();
        break;
    }
    
    $template->show();
    ?>
    

     

    example.8-6.tpl inside of ./templates

    <!DOCTYPE HTML PUBLIC
                     "-//W3C//DTD HTML 4.01 Transitional//EN"
                     "http://www.w3.org/TR/html401/loose.dtd">
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <title>Phonebook Entry Receipt</title>
    </head>
    <body>
    <!-- BEGIN success -->
    <h1>Added a Phonebook Entry</h1>
    <table>
    <tr>
      <td>Surname:
      <td>{SURNAME}
    </tr>
    <tr>
      <td>First name:
      <td>{FIRSTNAME}
    </tr>
    <tr>
      <td>Phone number:
      <td>{PHONE}
    </tr>
    </table>
    <!-- END success -->
    <!-- BEGIN failure -->
    <h1>{MESSAGE}</h1>
    <!-- END failure -->
    </body>
    </html>
    

     

    All of this is accessing a VERY simple database called 'telephone' and consists of this one easy table:

     

    CREATE TABLE phonebook ( phonebook_id int(6) NOT NULL auto_increment, surname CHAR(50) NOT NULL, firstname CHAR(50) NOT NULL, phone CHAR(20) NOT NULL, PRIMARY_KEY (phonebook_id) ) type=MyISAM;
    

     

     

  9. Thanks! I ran your version of the code and this is what I got…

     

    SELECT * FROM winery WHERE region_id = Error 1064 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
    

     

    I posted a copy of the database here so you could try it yourself. It's an example database from the publisher of the book I'm reading containing no vital information.

     

    http://rapidshare.com/files/310384292/winestore.sql.html

     

    MD5: E16368D7CCBABCDC9FAFC9AF70BBAD57

  10. awesome tip trying it on the command line! this trick will come in very handy.

     

    I checked the syntax errors, got rid of them.

     

    but now it's reporting an SQL error and I can't seem to find it. would you mind having a look?

     

    this is the error I get when I load the page now...

     

    Error 1064 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 2
    

     

    I checked line 2 and the whole file and I can't find the SQL error.  :shrug:

     

    Thanks

  11. Hey Guys

     

     

    Thanks for your consistent and excellent help. I am really trying to master PHP connecting to MySQL. Every once in a while tho I run into a script that mysteriously refuses to be useful and I could use some help. That's why I have come to this board again, it's excellent.

     

    That said.. I wrote a very simple script that is meant to access a template and render information from am MySQL database.

     

     

    It should be noted that:

     

    error_reporting E_ALL

    display_errors = 1

     

    is set in my php.ini file.

     

    Here is the code. For some strange reason the page it renders is completely blank.

    example.7-5.php

    <?php
         require_once "HTML/Template/IT.php";
         require 'db.inc';
         
         if (!($connection = @ mysql_connect($hostname, $username, $password)))
             die("Cannot connect");
             
         if (!(mysql_select_db($databaseName, $connection)))
            showerror();
         
         if (!$regionresult = @ mysql_query ("SELECT * FROM region LIMIT 10", 
                                              $connection)))
            showerror();
            
            
         $template = NEW HTML_TEMPLATE_IT("./templates");
         $template->loadTemplatefile("example.7-4.tpl",true, true);
         
         while ($regionrow = mysql_fetch_array($regionresult));
         {
             $template->setCurrentBlock("REGION");
             $template->setVariable("REGIONNAME", $regionrow["region_name"]]);
             
              if(!($wineryresult = 
                  @ mysql_query ("SELECT * FROM winery
                                  WHERE region_id = {$regionrow["$region_id"]}",
                                  $connection)))
                                  
                  showerror();
                  
               while ($wineryrow = mysql_fetch_array($wineryresult))
               {
                   $template->setCurrentBlock("WINERY");
                   $template->setVariable("WINERYNAME", $wineryrow["winery_name"]);
                   $tempalte->parseCurrentBlock();
                   
               }
               $template->setCurrentBlock("REGION");
               $template->parseCurrentBlock();
         }
         $template->show();
    ?>
    

     

    This code accesses a db include file that has all the login information:

     

    db.inc

    <?php
       // This file is the same as example 6-7, but includes mysqlclean() and shellclean() 
    
       $hostName = "localhost";
       $databaseName = "winestore";
       $username = "thatguy";
       $password = "shhhh";   
    
       function showerror()
       {
          die("Error " . mysql_errno() . " : " . mysql_error());
       }
    
       function mysqlclean($array, $index, $maxlength, $connection)
       {
         if (isset($array["{$index}"]))
         {
            $input = substr($array["{$index}"], 0, $maxlength);
            $input = mysql_real_escape_string($input, $connection);
            return ($input);
         }
         return NULL;
       }
    
       function shellclean($array, $index, $maxlength)
       {
         if (isset($array["{$index}"]))
         {
           $input = substr($array["{$index}"], 0, $maxlength);
           $input = EscapeShellArg($input);
           return ($input);
         }
         return NULL;
       }
    ?>
    

     

    this is the simple template file living in the ./templates directory one directory down from my html docs directory

     

    example.7-4.tpl

    <!DOCTYPE HTML PUBLIC
                   "-//W3C//DTD HTML 4.01 Transitional//EN"
                   "http://www.w3.org/TR/html401/loose.dtd">
    <html>
    <head>
         <meta http-equiv="Content Type" content="text/html; charset-iso-8859-1">
         <title>Regions and Wineries</title>
    <body>
    <ul>
    <!-- BEGIN REGION -->
    <li>Region: {REGIONNAME}
    <ul>
    <! -- BEGIN WINERY -->
    <li>{WINERYNAME}.
    <! -- END WINERY -- >
    </ul>
    <! -- END REGION -- >
    </ul>
    </body>
    </html>
    

     

    And for some reason the page, even tho errors are turned on turn up blank. Any thoughts?  :wtf:

     

  12. Well I just fixed this problem with the help of spox on #php on freenode.

     

     

    The mac install of MySQL does not conform to all the "usual" locations you are used to on a linux install. The most important things you have to change in your php.ini file are where the sock lives.

     

    On linux any reference to mysqld.sock in your ini file should point to /var/run/mysqld/mysqld.sock

    On the mac you need to change those references to /opt/local/var/run/mysql5/mysqld.sock

     

    But the most important thing in my case in solving this problem was adding the line mysql.default_socket = /tmp/mysql.sock (which was missing in my ini file) and resetting mysqli.default_socket to mysqli.default_socket = /tmp/mysql.sock.

     

    This was the source of the WIN after struggling for a week. THANKS SPOX!!!

     

  13. these are the permissions on my my.cnf which lives in /private/etc on the mac

     

    mazdayasna:etc bluethundr$ ls -la my.cnf
    -rw-r--r--  1 root  wheel  10 Nov 10 14:10 my.cnf
    

     

    also I've noticed that it is empty, except for the statement [mysqld]

     

    I tried to add the large packets directive in my.cnf

     

    max_allowed_packet=32M
    

     

    but then mysql wouldn't launch. so I removed it, and it started launching again. I think this is when php stopped being able to connect.

     

    I noticed when I installed mysql on my mac, unlike my linux boxen the my.cnf is curiously empty.

  14. Hi

     

    I have php 5.3.0 installed on my snow leopard mac. mysql 5.1 is installed and running. everything is local. I can log into mysql from the command line but for some reason even tho I am feeding my php scripts the correct login and they used to work they can no longer connect to my local mysql install.

     

    I could use some help troubleshooting this.

     

    Specifically this line used to work:

     

    if (!($connection = @ mysql_connect("localhost","user","shhhhh")))
              die("Could not connect");
    

     

    now this script jumps right to the die line.

     

    I'm honestly not sure what changed here.

    :shrug:

    help!

     

  15. I'm using PEAR on the mac. mac Apache is running

     

    Apache

    mazdayasna:5.10.0 bluethundr$ sudo apachectl -S
    [Thu Nov 12 00:59:32 2009] [warn] module ssl_module is already loaded, skipping
    VirtualHost configuration:
    Syntax OK
    

     

    PEAR

    mazdayasna:5.10.0 bluethundr$ pear list
    Installed packages, channel pear.php.net:
    =========================================
    Package          Version State
    Archive_Tar      1.3.3   stable
    Auth_SASL        1.0.3   stable
    Console_Getopt   1.2.3   stable
    DB               1.7.13  stable
    Date             1.4.7   stable
    HTML_Template_IT 1.2.1   stable
    Mail             1.1.14  stable
    Net_SMTP         1.3.3   stable
    Net_Socket       1.0.9   stable
    PEAR             1.9.0   stable
    Structures_Graph 1.0.3   stable
    XML_Util         1.2.1   stable
    

     

    This is where IT.php seemed to be hiding on my system. Running Mac OS X 10.6.1 "Snow Leopard".

     

    mazdayasna:5.10.0 bluethundr$ locate IT.php
    /usr/lib/php/HTML/Template/IT.php
    

     

     

     

  16. hey guys

     

      I have a php script that won't render in firefox. I am using the local apache install on my mac with mysql locally installed.

     

    I have error_reporting E_ALL set in my php.ini file. Other scripts that live in the proper apache directory either just work or E_ALL displays the error.

     

    I am working with the platypus book from O'Reilly. The script is trying to use templates to populate an html page. I have a templates directory just below the web root on my mac where I put the example.7-3.tpl file.

     

    here's the code

     

    example.7-2.tpl

     

    <!DOCTYPE HTML PUBLIC
                        "-//W3C//DTD HTML 4.01 Transitional//EN"
                        "http://www.w3.org/TR/html401/loose.dtd">
                        
    <html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
       <title>Customer Details</title>
    <body>
    <table>
    <tr><th>Name<th>Address<th>City<th>State<th>Zipcode
    <!-- BEGIN CUSTOMER -->
    <tr><td>{FIRSTNAME} {SURNAME}<td>{ADDRESS}
        <td>{CITY}<td>{STATE}<td>{ZIPCODE}
    <!-- END CUSTOMER -->
    </table>
    </body>
    </html>
    

     

    And this is the actual code I am trying to get to work.

     

    example.7-3.php

    <?php
         require_once "/usr/lib/php/HTML/Template/IT.php";
         include "db.inc";
         
         
         // Connect to the MySQL server
         if (!connection = @ mysql_connect($hostname, $username, $password)))
            die("Cannot connect");
            
         if (!(mysql_select_db($databseName, $connection)))
             showerror();
         
         
         // Run the query on the connection
         if (!($result = @ mysql_query ("SELECT * FROM customer LIMIT 50",
                                         $connection)))
            showerror();
            
         // Create a new template, and specify that template files are
         // in the subdirectory "templates"
         $template = new HTML_Template_IT("./templates");
         
         // Load the customer template file
         $template->loadTempltefile("example.7-2.tpl", true, true);
         
         while ($row = mysql_fetch_array($result))
         {
            // Work with the customer block
            $template->setCurrentBlock("CUSTOMER");
            
            
            // Assign the row data to the template placeholders
            $template->setVariable("FIRSTNAME", $row["firstname"]);
            $template->setVariable("SURNAME", $row["surname"]);
            $template->setVariable("ADDRESSS", $row["address"]);
            $template->setVariable("CITY", $row["city"]);
            $template->setVariable("STATE", $row["state"]);
            $template->setVariable("ZIPCODE", $row["zipcode"]);
            
            
            // Parse the current block
            $template->parseCurrentBlock();
            
          }
          
          
          // Output the webpage
          $template->show();
    ?>
    

     

     

    Thanks!!!

  17. This script is trying to access a MySQL database

     

    but it keeps failing at line 82, and I can't find the problem with the code.

     

    This is the error I get:

    Warning: mysql_select_db() expects parameter 2 to be resource, null given in /Library/WebServer/Documents/example.6-14.php on line 82
    Error 0 : 

     

    and this is the line that keeps producing the error:

     

        if (!mysql_select_db($databaseName, $connection))
            showerror();
    

     

     

    <!DOCTYPE HTML PUBLIC
                   "-//W3C// DTD HTML  4.01  Transitional//EN"
                   "http://www.w3.org/TR/html401/loose.dtd">
                   
                   
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <title>Exploring Wines in a Region</title>
    </head>
    
    
    <body bgcolor="white">
    <?php
          require 'db.inc';
          
          
          // Show all wines in a region in a <table>
          function displayWinesList($connection,
                                    $query,
                                    $regionName)
                                    
          
          {
          
               // Run the query on the server
               if (!($result = @ mysql_query ($query, $connection)))
                    showerror();
                    
               // Find out how many rows are available
               $rowsFound = @ mysql_num_rows($result);
               
               
              // If the query has results
              if ($rowsFound > 0)
              {
              
                   // ... print out a header
                   print "Wines of $regionName<br>";
                   
                   
                   // and start a <table>
                   print "\n<table>\n<tr>" .
                         "\n\t<th>Wine ID</th>" .
                         "\n\t<th>Wine Name</th>" .
                         "\n\t<th>Year</th>"  .
                         "\n\t<th>Winery</th>" .
                         "\n\t<th>Description</th>\n</tr>" ;
                         
                   // Fetch each of the query rows
                   while ($row = @ mysql_fetch_array($result))
                   { 
                   
                      // Print one row of results 
                      print "\n<tr>\n\t<td>{$row["wine_id"]}</td>" .
                            "\n\t<td>{$row["wine_name"]}</td>" .
                            "\n\t<td>{$row["year"]}</td>" .
                            "\n\t<td>{$row["winery_name"]}</td>" .
                            "\n\t<td>{$row["description"]}<td>\n</tr>";
                            
                   } // end while loop body
                   
                   
                   // Finish the table
                   print "\n</table>";
           }  // end if $rowsFound in body
           
           // Report how many rows were found
           
          print "{$rowsFound} records found matching your criteria</br>";
          
       } // end of function
       
       // Connect to the MySQL server
       if (!($connetion = @ mysql_connect($hostName, $username, $password)))
            die("Could not connect");
            
        // Secure the user parameter $regionName
        $regionName = mysqlclean($_GET, "regionName", 30, $connection);
        
        
        if (!mysql_select_db($databaseName, $connection))
            showerror();
        
       
       
       // Start a query ...
       $query = "SELECT wine_id, wine_name, description, year, winery_name
                 FROM   winery, region, wine
                 WHERE  winery.region_id = region.region_id
                 AND    wine.winery_id = winery.winery_id";
                 
        // ... then, if the user has specified a region, add the regionName
        // as an AND clause
        if (isset($regionName) && $regionName !="All")
           $query .= " AND region_name = \"{regionName}\"";
           
           
        // ... and then complete the query
        $query .= " ORDER BY wine_name ";
        
        // run the query and show the results
        displayWinesList($connection, $query, $regionName);
        
        
        ?>
        </body>
        </html>
    

     

    and this is the db.inc script, there's not much to it

     

    <?php
       // This file is the same as example 6-7, but includes mysqlclean() and shellclean() 
    
       $hostName = "localhost";
       $databaseName = "winestore";
       $username = "like-i'd-tell-you";
       $password = "shhhh";
    
       function showerror()
       {
          die("Error " . mysql_errno() . " : " . mysql_error());
       }
    
       function mysqlclean($array, $index, $maxlength, $connection)
       {
         if (isset($array["{$index}"]))
         {
            $input = substr($array["{$index}"], 0, $maxlength);
            $input = mysql_real_escape_string($input, $connection);
            return ($input);
         }
         return NULL;
       }
    
       function shellclean($array, $index, $maxlength)
       {
         if (isset($array["{$index}"]))
         {
           $input = substr($array["{$index}"], 0, $maxlength);
           $input = EscapeShellArg($input);
           return ($input);
         }
         return NULL;
       }
    ?>
    

     

    Thanks for your help

     

  18.    while ($row = @ mysql_fetch_row($result))
           { 
              
              while ($row = @ mysql_fetch_row($result)) {
    
    

     

    Ouch!

     

    Why are you doing this?

     

    Cool! thanks! That was it. Just a simple script to access a MySQL db and generate html based on output to html. Unless I am misunderstanding your question. So the real "why" is that I am just wrapping my head around this stuff.

     

    Cheers!

  19. Hi guys,

     

    I am writing a simple php script to access a MySQL database to retrieve info from some tables and format them with html. Simple right? Well for some reason there is a bug in the code where all it does is print '<r>' over and over again in an infinite loop. I have stared at this code till my eyes bled. Can I get some assistance?

    <!DOCTYPE HTML PUBLIC 
                        "-//W3C/DTD HTML 4.01 Transitional//EN"
                        "http://www.w3.org/TR/html401/loose.dtd">
    <html>
    <head>
         <meta http-equiv="Content-Type" content="text/html"; charset=iso-8859-1">
         <title>Wines</title>
    </head>
    <body>
    <?php
        require 'db.inc';
        
        
        
        // Show the wines in the HTML <table>
        function displayWines($result)
        {
        
        
           print "<h1>Our Wines</h1>\n";
           
           // Start a table, with column header
           print "\n<table>\n<tr>\n"  .
                 "\n\t<th>Wine ID</th>" .
                 "\n\t<th>Wine Name</th>" .
                 "\n\t<th>Type</th>" .
                 "\n\t<th>Year</th>" .
                 "\n\t<th>Winery ID</th>" .
                 "\n\t<th>Description</th>" .
                 "\n</tr>";
                 
                 
           // Until there are no rows in the result set, fetch a row into
           // the $row array and ...
           while ($row = @ mysql_fetch_row($result))
           { 
              
              while ($row = @ mysql_fetch_row($result))
              {
                 // ... start a TABLE row ...
                 print "\n<tr>";
                 
                 // ... and print out each of the attributes in that row as a 
                 // separate TD (Table Data).
                 foreach($row as $data)
                       print "\n\t<td> {$data} </td>";
                       
                 // Finish the row
                 print "\n<\tr>";
              }
             
             // Then, finish the table
             print "\n</table>\n";
         }
         
         
       } 
       
       $query = "SELECT * FROM wine";
       
       // Connect to the MySQL server
       if (!($connection = @ mysql_connect($hostname, $username, $password)))
            die("Cannot connect");
            
       if (!(mysql_select_db($databaseName, $connection)))
           showerror();
           
       // Run the query on the connection
       if (!($result = @ mysql_query ($query, $connection)))
           showerror();
           
       // Display the results
       displayWines($result);
       ?>
       </body>
       </html>
            
    

     

     

    There is an .inc file that has all the login information for the db that appears to be working.

     

     

    Thanks!

     

     

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.