Jump to content

travisco87

Members
  • Posts

    35
  • Joined

  • Last visited

Posts posted by travisco87

  1. FOUND IT!!! ok so the issue was with my calling statement with PDO::fetchColumn. I did a little more research and found that this is what you need to use to count elements in MySQL. 

     

     

    Instead of this

    //Next grab the list of used tags BLOG_POST_TAGS TABLE HAS TWO FILEDS blog_post_id and tag_id
    $stmt2 = $DBH->query("SELECT count(*) FROM blog_post_tags WHERE tag_id = " . $tagId);
    $stmt2->execute();
    $tagCount = $stmt2->fetchColumn();
    

    I used this and it fixed my issue.

                    $tagCount = $DBH->query("SELECT count(*) FROM blog_post_tags WHERE tag_id = " . $tagId)->fetchColumn();
    

    Thank you guys for all your help, I learned a couple new features such as validator.w3.org and about using PDO statements. Keep it up! 

  2. Ok looking over both sources I found that the live server stops and does not load the rest of the page. I ran it through the validation site and think I found the error.

     

    • Line 127, column 74: Element input not allowed as child of element ul in this context. (Suppressing further errors from this subtree.)
      								<input id="newsbutton" type="submit" name="Submit" value="Signup">

     

    This is the section directly above it. 

  3. I have been working on a blog program with a tag system. When I add tags and ask to display them to a certain webpage they all appear on my WAMP environment but not my live server. Any thoughts as to why this might be? Here is the code needed to display the tags. I am not sure if maybe live servers have restrictions that might be stopping it from displaying. 

     

    This is on the main page to display the tags.

    				<div class="widget">
    		<?php
    				
    				echo '<h2>Tags</h2>';
    				echo '<ul>';
    				getTagCount($DBH);
    				echo '</ul>';
    		?>
    			</div>
    

    Next here is the function from the includes file.

    function getTagCount($DBH) {
        
        //Make the connection and grab all the tag's TAG TABLE HAS TWO FIELDS id and name
                $stmt = $DBH->query("SELECT * FROM tags");
                $stmt->execute();
                $result = array();
                $result = $stmt->fetchAll();
                //For each row pulled do the following
                foreach ($result as $row){
                    //set the tagId and tagName to the id and name fields from the tags table
                    $tagId = $row['id'];
                    $tagName = ucfirst($row['name']);
                    
                    //Next grab the list of used tags BLOG_POST_TAGS TABLE HAS TWO FILEDS blog_post_id and tag_id
                    $stmt2 = $DBH->query("SELECT count(*) FROM blog_post_tags WHERE tag_id = " . $tagId);
                    $stmt2->execute();
                    $tagCount = $stmt2->fetchColumn();
                    
                    //Print the following list 
                    echo '<li><a href="blog_tags.php?tagId=' . $tagId . '"title="' . $tagName . '">' . $tagName . '(' . $tagCount . ')</a></li></form>';
                    
                //End of loop - start again
                }
                
    }
    

    The "tags" database is structured like so 

    id, name

     

    The "blog_post_tags" is structured like so,

     

    blog_post_id, tag_id

     

     

     

    On the WAMP server it returns all of tags while the live server only returns the first one. Any suggestions on what is going on? If you need any other info please let me know. 

     

     

  4. I am trying to write a program that sends out a newsletter but I am lost at returning an array of emails. This is what I have

    <?php
    require("../PHPMailer/class.phpmailer.php");
    include 'includes.php';
            $mail = new PHPMailer;
            $subject = $_POST['subject'];
            $text = $_POST['newsletterBody'];
            $unsubscribe = "<br /><br /><br /><br />If you would no longer like to receive these emails, please <a href='removeemail.php'>Click Here</a> to unsubscribe.";
            $mail->IsSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'localhost';  // Specify main and backup server
            $mail->Port = '465';
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = '****EMAIL ADDRESS****';                            // SMTP username
            $mail->Password = '****EMAIL PASSWORD*****';
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = 'ssl';                            // Enable encryption, 'ssl' also accepted
    
            $mail->From = '****EMAIL ADDRESS****';
            $mail->FromName = '****NAME****';
            
            $mail->AddAddress('****EMAIL ADDRESS****', '****NAME****');
            
            $email = getEmail("", $DBH);
            
            
            foreach ($email as $newEmail)
                    {
                        $addEmail = $newEmail['email_addr'];
                        $mail->AddAddress($addEmail);
                        $DBH = null;
                    }
            
    
            $mail->AddReplyTo('****EMAIL ADDRESS****', '****NAME****');
        
            $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
            $mail->IsHTML(true);                                  // Set email format to HTML
    
            $mail->Subject = $subject;
            $mail->Body    = $text . "<br /><br /><br /> To unsubscribe to this email please  <a href='www.raven-consult.com/newsletter_remove.php'>Click Here</a>";
            $mail->AltBody = $text;
    
            if(!$mail->Send()) {
               echo 'Message could not be sent.';
               echo 'Mailer Error: ' . $mail->ErrorInfo;
               exit;
            }
            
            
            echo "Message has been sent <a href='newsletter.php'>Return back</a>";
    
    ?>
    

    This is the portion of the includes file that you need to know. 

    function getEmail($inId, $DBH)
        {
            if (!empty($inId))
            {
                $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId");
                $blogstmt->bindParam(":userId", $inId);
                $blogstmt->execute();
                $postArray = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
            }
            else
            {
                $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails");
                $blogstmt->execute();
                $postArray = array();
            
            $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
            foreach($results as $row){
                $myPost = new nlEmails($row['id'], $row['email_addr'], $DBH);
                array_push($postArray, $myPost);
            }
            }
        
            
            
            return $postArray;
            $DBH = null;
        }
     
    class nlEmails {
        public $id;
        public $email;
        
        function __construct($inId=null, $inEmail=null, $DBH)
        {
            if(!empty($inId))
            {
                $this->id = $inId;
            }
            if(!empty($inEmail))
            {
            $this->email = $inEmail;
            }
        }
    }
    

    When I try and submit the newsletter to be sent out all I get back is this error. 

     

    "Cannot use object of type nlEmails as array ......"

     

     

  5. Nothing is being returned. Why? 

    <?php
    error_reporting(E_ALL);
    ini_set("display_errors", 1);
    require("../PHPMailer/class.phpmailer.php");
    include 'includes.php';
            $mail = new PHPMailer;
            $subject = $_POST['subject'];
            $text = $_POST['newsletterBody'];
            $mail->IsSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'localhost';  // Specify main and backup server
            $mail->Port = '465';
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = '**EMAIL_USERNAME**';                            // SMTP username
            $mail->Password = '**EMAIL_PASSWORD**';
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = 'ssl';                            // Enable encryption, 'ssl' also accepted
    
            $mail->From = '**EMAIL_ADDRESS**';
            $mail->FromName = '**EMAIL_NAME';
            
        
            $email = getEmail("62", $DBH);
            
            
            foreach ($email as $newEmail)
                    {
                        $addEmail = $newEmail->email;
                        $mail->AddAddress($addEmail);
                        $DBH = null;
                        $addEmail = "";
                    }
            
    
            $mail->AddReplyTo('**EMAIL_REPLY_TO**', '**EMAIL_REPLY_TO_NAME**');
        
            $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
            $mail->IsHTML(true);                                  // Set email format to HTML
    
            $mail->Subject = $subject;
            $mail->Body    = $text;
            $mail->AltBody = $text;
    
            if(!$mail->Send()) {
               echo 'Message could not be sent.';
               echo 'Mailer Error: ' . $mail->ErrorInfo;
               exit;
            }
            
                $insertSql = "INSERT INTO newsletter_log (date, title, body) VALUES (?,?,?)";
                $insertParams = array(time(), $subject, $text);
                $newsletterAdd = $DBH->prepare($insertSql);
                $newsletterAdd->execute($insertParams)
            
            echo 'Message has been sent <a href='newsletter.php'>Return back</a>";
    
    ?>
    

    This is the include section that you need

    function getEmail($inId, $DBH)
        {
            if (!empty($inId))
            {
                $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId");
                $blogstmt->bindParam(":userId", $inId);
                $blogstmt->execute();
            }
            else
            {
                $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails");
                $blogstmt->execute();
            }
        
            $postArray = array();
            
            $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
            foreach($results as $row){
                $myPost = new nlEmails($row["id"], $row['email'], $DBH);
                array_push($postArray, $myPost);
            }
            
            return $postArray;
            $DBH = null;
        }
     
    class nlEmails {
        public $id;
        public $email;
        
        function __construct($inId=null, $inEmail=null, $DBH)
        {
            if(!empty($inId))
            {
                $this->id = $inId;
            }
            if(!empty($inEmail))
            {
            $this->email = $inEmail;
            }
        }
    }
    

    The database is created with the newsletter_emails "id", "first_name", "last_name", "email_addr". Thanks! 

  6. I am working on building a newsletter with PHP. I have gotten everything to work but the pulling of the email address. 

     

    First is the sendnl.php file 

    <?php
    require("../PHPMailer/class.phpmailer.php");
    include 'includes.php';
    
            $mail = new PHPMailer;
            $subject = $_POST['subject'];
            $text = $_POST['newsletterBody'];
            $mail->IsSMTP();                                      
            $mail->Host = 'localhost';  
            $mail->Port = '465';
            $mail->SMTPAuth = true;                               
            $mail->Username = '******USERNAME';          
            $mail->Password = '*****PASSWORD';
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = 'ssl';                           
    
            $mail->From = '***EMAIL';
            $mail->FromName = '****FROMNAME';
            
        
            $email = getEmail("73", $DBH);
            
            foreach ($email as $nlEmail)
            {
                $addEmail = $nlEmail->email;
                $mail->AddAddress($addEmail);
                $DBH = null;
                $addEmail = "";
            }
            
    
            $mail->AddReplyTo('******EMAIL', '*****EMAILNAME');
        
            $mail->WordWrap = 50;                                 
            $mail->IsHTML(true);                                  
    
            $mail->Subject = $subject;
            $mail->Body    = $text;
            $mail->AltBody = $text;
    
            if(!$mail->Send()) {
               echo 'Message could not be sent.';
               echo 'Mailer Error: ' . $mail->ErrorInfo;
               exit;
            }
    
            echo 'Message has been sent';
    
    ?>
    

    Next is part of the includes file going over the function and class

    
    function getEmail($inId, $DBH)
        {
            if (!empty($inId))
            {
                $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId");
                $blogstmt->bindParam(":userId", $inId, PDO::PARAM_STR, 6);
                $blogstmt->execute();
            }
            else
            {
                $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails");
                $blogstmt->execute();
            }
        
            $postArray = array();
            
            $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
            foreach($results as $row){
                $myPost = new nlEmails($row["id"], $row['email'], $DBH);
                array_push($postArray, $myPost);
            }
            
            return $postArray;
            $DBH = null;
        }
     
    class nlEmails {
        public $id;
        public $email;
        
        function __construct($inId=null, $inEmail=null, $DBH)
        {
            if(!empty($inId))
            {
                $this->id = $inId;
            }
            if(!empty($inEmail))
            {
            $this->email = $inEmail;
            }
        }
    }
    

    It gives me an Unidentified index error message for the "id" and "email" used in the getEmail function.

    Thanks for any help or pointers. 

  7. Hello all! I am trying to send mail using the "Mail.php" function but I cant figure out whats going wrong. The insert function works in the database but not the sending mail function. Please let point me in the right direction, thanks for your help in advance! 

    <?php
        if(isset($_POST)){
    //If the post is not empty, continue
            if(!empty($_POST)) {
                include_once 'includes.php';
                require_once 'Mail.php';
                $from = "Name <email@foobar.com>";
                $subject = $_POST['subject'];
                $text = $_POST['newsletterBody'];
                $host = "host";
                $port = "port";
                $username = "EMAILUSERNAME";
                $password = "EMAILPASSWORD";
                echo "Subject: " . $subject;
                echo "<br />Body: " . $text;
                echo "<br />Host: " . $host;
                echo "<br />Port: " . $port . "<br />";
                $sql = 'INSERT INTO newsletter_log (date,title,body) VALUES (:time,:subject,:body)';
                $params = array(
                            ':subject' => $subject,
                            ':body' => $text,
                            ':time' => time());
                $poststmt = $DBH->prepare($sql);
                $poststmt->execute($params);
                if($poststmt)
                {
                    echo "Saved to the database.";
                    
                }
                else {
                    echo "Not saved.";
                }
                $sqlSubUsers = 'SELECT * FROM test_newsletter WHERE newsletter_id = 1';
                $newsletterStmt = $DBH->prepare($sqlSubUsers);
                $newsletterStmt->execute();
                $userIds = $newsletterStmt->fetch(PDO::FETCH_ASSOC);
                echo $userIds;
                foreach ($userIds as $row){
                    $getUserEmailSql = 'SELECT email_addr FROM newsletter_emails WHERE id =' . $row['people_id'];
                    $getUserEmailStmt = $DBH->prepare($getUserEmailSql);
                    $getUserEmailStmt->execute();
                    $userEmail = "<" . $getUserEmailStmt->fetch(PDO::FETCH_COLUMN,0) . ">";
                    $userEmail->closeCursor();
                    $html = "<html><body>" . $text . "</html></body>";
                    $headers = array ('From' => $from,
                                  'To' => $userEmail,
                                  'Subject' => $subject);
                    $smtp = Mail::factory('smtp',
                                      array ('host' => $host,
                                             'port' => $port,
                                             'username' => $username,
                                             'password' => $password));        
                $mail = $smtp->send($to, $headers, $html);
                echo $userEmail;
                if (PEAR::isError($mail)) {
                    echo("<p>" . $mail->getMessage() . "</p>");
                } else {
                    echo("<p>Message successfully sent!</p>");
                }
            }
         echo 'Newsletter Sent.';
    } else {
            echo '<h3>No newsletter was sent.</h3>';
        }
    }
    ?>
    

    I have removed the emails, host, port, username and password along with in other information I did not think I should send over. 

  8. When creating the HTML file should I create it as conditional? What I mean by that is I also use the same layout almost when they submit the work order. Would I check for submission, if nothing is submitted insert the "placeholders"? Then if there is something submitted replace the placeholders with values instead? I am still trying to learn as I go, thank you so much for your insight. I will clean this up. 

  9. Hi All,

     

    I started learning PHP a couple years ago and decided to build a work order system for fun. I have been working on this but for some reason the 'post' does not seem to translate over into the next page. Here is my code below

     

     

     

    wo_view.php

    <?php
        require_once('authorize.php');
    ?>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd"
    >
    <html lang="en">
    <head>
        <title>Admin Page</title>
        <link rel="stylesheet" type="text/css" href="css/adminmenu.css" />
        <!-- Add jQuery library -->
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    
    </head>
    <body>
        
    <?php
    include_once 'nav-menu.php'
    ?>
    <h2 style="text-align: center;">Work Order Information</h2>
    
    <div id="woTable">
    	    <fieldset>
    <?php
        include 'includes.php';
        
        if(isset($_POST['submit'])) {
            if(!empty($_POST)) {
            $wo_info = array(
                    "first_name"=>Trim(stripcslashes($_POST['first_name'])),
                    "last_name"=>Trim(stripcslashes($_POST['last_name'])),
                    "phone_number"=>Trim(stripcslashes($_POST['phone_number'])),
                    "email_addr"=>Trim(stripcslashes($_POST['email_addr'])),
                    "strt_addr"=>Trim(stripcslashes($_POST['strt_addr'])),
                    "strt_addr2"=>Trim(stripcslashes($_POST['strt_addr2'])),
                    "city"=>Trim(stripcslashes($_POST['city'])),
                    "state"=>Trim(stripcslashes($_POST['state'])),
                    "zip"=>Trim(stripcslashes($_POST['zip'])),
                    "service_type"=>Trim(stripcslashes($_POST['service_type'])),
                    "service_date"=>$_POST['inputDate'],
                    "service_time"=>Trim(stripcslashes($_POST['service_time'])),
                    "service_notes"=>Trim(stripcslashes($_POST['service_notes'])),
                    "wo_id"=>Trim(stripcslashes($_POST['wo_id'])),
                    "wo_status"=>Trim(stripcslashes($_POST['wo_status']))
            );
            $sql = 'UPDATE workorderstbl SET first_name = :first_name, last_name = :last_name, phone_number = :phone_number,  email_addr = :email_addr, strt_addr = :strt_addr, strt_addr2 = :strt_addr2, city = :city, state = :state, zip = :zip, service_type = :service_type, service_notes = :service_notes, wo_status = :wo_status WHERE wo_id = :wo_id LIMIT 1';
            
            $params = array(
                    ':first_name'=>$wo_info['first_name'],
                    ':last_name'=>$wo_info['last_name'],
                    ':phone_number'=>$wo_info['phone_number'],
                    ':email_addr'=>$wo_info['email_addr'],
                    ':strt_addr'=>$wo_info['strt_addr'],
                    ':strt_addr2'=>$wo_info['strt_addr2'],
                    ':city'=>$wo_info['city'],
                    ':state'=>$wo_info['state'],
                    ':zip'=>$wo_info['zip'],
                    ':service_type'=>$wo_info['service_type'],
                    ':service_notes'=>$wo_info['service_notes'],
                    ':service_date'=>$wo_info['service_date'],
                    ':service_time'=>$wo_info['service_time'],
                    ':wo_id'=>$wo_info['wo_id'],
                    ':wo_status' =>$wo_info['wo_status']
                );
                $stmt = $DBH->prepare($sql);
                $stmt->execute($params);
                
                redirect('wo_view.php?id=' . $_POST['wo_id']);
            } else {
                 echo "\nPDO::errorInfo();\n";
                print_r($DBH->errorInfo());
            }
            
        } else {
        
            $postviewsql = "SELECT * FROM workorderstbl WHERE wo_id = :wo_id LIMIT 1";
        
            $poststmt = $DBH->prepare($postviewsql);
            $poststmt->bindParam(':wo_id', $_GET['id'], PDO::PARAM_STR, 5);
            $poststmt->execute();
        
        
            if(!($poststmt->rowCount())) {
                echo 'Work Order #' . $_GET['id'] . ' not found BOOM';
                $DBH = null;
            } else {
                $row = $poststmt->fetch(PDO::FETCH_ASSOC);
                echo "<legend>Contact Info</legend>";
                echo "<a href='adminworkorders.php' style='float: left;'>Go Back to All Service Request</a><a href='wo_edit.php?id=" . $row['wo_id'] . "&sd=" . $row['service_date'] . "' style='float: right;'>Edit Service Request</a><br /><br />";
                echo "Service Request: <strong>" . $row['wo_id'] . "</strong>&nbsp&nbsp&nbsp&nbsp Created On: <strong>" . date('F j<\s\up>S</\s\up>, Y', $row['date_posted']). "</strong>&nbsp&nbsp&nbsp&nbsp Service Request Status: <strong>" . $row['wo_status'] . "</strong><br />";
                echo "Name: <strong>" . $row['first_name'] . " " . $row['last_name'] . "</strong><br />";
                echo "Phone Number: <strong>" . $row['phone_number'] . "</strong>&nbsp&nbsp&nbsp&nbsp Email Address: <strong>" . $row['email_addr'] . "</strong>";
                echo "</fieldset><fieldset><legend>Address</legend>";
                echo "<strong>" . $row['strt_addr'] . " " . $row['strt_addr2'] . "</br>";
                echo $row['city'] . " " . $row['state'] . ", " . $row['zip'] . "</strong><br />";
                echo "</fieldset><fieldset><legend>Service Information:</legend>";
                echo "Service Type: <strong>" . $row['service_type'] . "</strong>&nbsp&nbsp&nbsp&nbsp Request Date: <strong>" . date('m-d-Y',$row['request_date']) . "</strong>&nbsp&nbsp&nbsp&nbsp Requested Time Frame: <strong>" . $row['request_time'] . "</strong><br />";
                echo "Service Date: <strong>" . $row['service_date'] . "</strong><br />";
                echo "Service Notes: <br /><strong>" . nl2br($row['service_notes']) . "</strong><br /><br />";
                $DBH = null;
        }
        }
    
    ?>
            </fieldset>
    </div>
    </body>
    </html>
    

    wo_edit.php

    <?php
        require_once('authorize.php');
    ?>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd"
    >
    <html lang="en">
    <head>
        <title>Admin Page</title>
        <link rel="stylesheet" media="screen" type="text/css" href="css/datepicker.css" />
        <link rel="stylesheet" href="css/datepicker.css" type="text/css" />
        <link rel="stylesheet" media="screen" type="text/css" href="css/layout.css" />
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/datepicker.js"></script>
        <script type="text/javascript" src="js/eye.js"></script>
        <script type="text/javascript" src="js/utils.js"></script>
        <script type="text/javascript" src="js/layout.js?ver=1.0.2"></script>
    <script>
            $(document).ready(function() {
                $('#inputDate').val("<?php echo date('m/d/Y', $_GET['sd']) ?>");
            });
            
            
        </script>
    </head>
    <body>
        
    <?php
    include_once 'nav-menu.php'
    ?>
    
    <h2 style="text-align: center;">Work Order Information</h2>
    
    <div id="woInfo">
    	    <fieldset>
    <?php
        include 'includes.php';
        
        $postviewsql = "SELECT * FROM workorderstbl WHERE wo_id = :wo_id LIMIT 1";
        
        $poststmt = $DBH->prepare($postviewsql);
        $poststmt->bindParam(':wo_id', $_GET['id'], PDO::PARAM_STR, 5);
        $poststmt->execute();
        
        
        if(!($poststmt->rowCount())) {
            echo 'Work Order #' . $_GET['id'] . ' not found';
            $DBH = null;
        }
        else
        {
            $row = $poststmt->fetch(PDO::FETCH_ASSOC);
            echo "<legend>Contact Info</legend>";
            echo "<form id='wo_edit' action='wo_view.php' method='post'>";
            echo "<a href='wo_view.php?id=" . $row['wo_id'] . "' style='float: left;'>Back to Service Request</a><br /><br />";
            echo "<label for='wo_id'>Service Request: <strong><span id='wo_id'>" . $row['wo_id'] . "</span></strong>&nbsp&nbsp&nbsp&nbsp Created On: <strong>" . date('F j<\s\up>S</\s\up>, Y', $row['date_posted']). "</strong>&nbsp&nbsp&nbsp&nbsp Service Request Status: <select id='wo_status'><option value='" . $row['wo_status'] . "'>--" . $row['wo_status'] . "--</optino><option value='New'>New</option><option value='Scheduled'>Scheduled</option><option value='Pending'>Pending</option><option value='Closed'>Complete</option></select><br />";
            echo "First Name: <input type='text' id='first_name' value='" . $row['first_name'] . "' />&nbsp&nbsp&nbsp&nbsp Last Name: <input type='text' id='last_name' value='" . $row['last_name'] . "' /><br />";
            echo "Phone Number: <input type='tel' id='phone_number' value='" . $row['phone_number'] . "' />&nbsp&nbsp&nbsp&nbsp Email Address: <input type='email' id='email_addr' value='" . $row['email_addr'] . "' /></strong>";
            echo "</fieldset><fieldset><legend>Address</legend>";
            echo "Address Line 1: <input type='text' id='strt_addr' value='" . $row['strt_addr'] . "' /> Address Line 1: <input type='text' id='strt_addr2' value='" . $row['strt_addr2'] . "' /></br>";
            echo "City: <input type='text' id='city' value='" . $row['city'] . "' /> State: <input type='text' id='state' value=' " . $row['state'] . "' /> Zip-Code: <input type='number' id='zip' value='" . $row['zip'] . "' /></strong><br />";
            echo "</fieldset><fieldset><legend>Service Information:</legend>";
            echo "Service Type: <select id='service_type'> <option value='" . $row['service_type'] . "'>--"  . $row['service_type'] . "--</option><option value='Install'>Install</option><option value='Service Call'>Service Call</option><option value='Repair'>Repair</option></select>&nbsp&nbsp&nbsp&nbsp Request Date: <strong>" . date('m-d-Y',$row['request_date']) . "</strong>&nbsp&nbsp&nbsp&nbsp Requested Time Frame: <strong>" . $row['request_time'] . "</strong><br />";
            echo "<label for='inputDate'>Service Date:</label><input class='inputDate' id='inputDate' name='inputDate' /><label id='closeOnSelect' style='display: none;'><input type='checkbox' checked='checked' /> Close on selection</label>&nbsp&nbsp&nbsp&nbsp Service Time: <input type='time' value='" . $row['service_time'] . "' />";
            echo "Service Notes:<br /><textarea id='service_notes' style='width: 100%;'>" . nl2br($row['service_notes']) . "</textarea><br />";
            echo "<input type='submit' value='Update' /></form>";
            $DBH = null;
        }
    ?>
            </fieldset>
    </div>
    </body>
    </html>
    

    I have been trying to fix this for the past couple days. I might be looking to hard at it, any help would be appreciated. Thank you! 

  10. So I have found a slider I would like to use in a program but I cannot figure out a certain issue with accessing the information from an array.

     

    Here is the code 

    (jQuery) is used FYI with a "slide pips" plugin.

    <script>
        $(document).ready(function(){
            
            var emotions = ['Confused', 'Annoyed', 'Angry', 'Concerned', 'Sad', 'Sarcastic', 'Joking', 'Playful', 'Romantic', 'Grateful', 'Awesome', 'Happy', 'Neutral']
            
            
            
                $('#defaultslide').slider({ 
                    max: 13,
                    min: 1,
                    value: 7,
                    slide: function(e,ui) {
                        $('#currentval').html(ui.value);
                    }
                }).slider('pips', {
                first: 'label',
                last: 'label',
                rest: 'label',
                labels: ['Confused', '<br />Annoyed', 'Angry', '<br />Concerned', 'Sad', '<br />Sarcastic', 'Joking', '<br />Playful', 'Romantic', '<br />Grateful', 'Awesome', '<br />Happy', 'Neutral'],
                prefix: '',
                suffix: ''
            });
        });
    </script>
    

    What I want to happen is when the slider moves, the #currentval would need to take the value of the slider and access the array of "emotions" and display the correct string with the value. I tried this

    slide: function() {
         $('#currentval').html(emotion[value -1]);
    }
    

    But this did not work. I have tried a couple other variations but nothing is working. What do I need to make the #currentval reference the "emotions" array according to the value of the slider? 

  11. Hello All,

     

    I am doing a tutorial on username availability using AJAX for immediate username validation. I have made it from the tutorial but decided to use PDO instead of the old "mysql" statements just FYI, I do not think it play's into the issue but might. 

     

    I keep getting this error from my Chrome console 

    Uncaught TypeError: Object [object global] has no method 'addEvent'
    

    I researched the error and made sure MooTools is up and running on my index page but this did not solve my issue. Any help would be much appreciated, here is my code

     

     

     

    index.php

    <html>
        <head>
            <title>Username Availability</title>
            <link rel="stylesheet" type="text/css" href="style/style.css">
            <script type="text/javascript" src="js/main.js"></script>
            <script src="//ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js"></script>
        </head>
    
    <body>
    <div id="container">
        <div id="content">
            <fieldset>
                <form method="post" action="js/json.php" id="signup">
                    
                    <ul class="form">
                        <li>
                            <label for="user_name">Username</label>
                            <input type="text" name="user_name" id="user_name" />
                        </li>
                        <li><input type="submit" value="Sign Up Now!" /></li>
                    </ul>
                </form>
            </fieldset>
        </div>
    </div>
        
    </body>
    
    </html>
    

    main.js

    window.addEvent('domready', function() {
        alert('The DOM is ready!');
        $('user_name').addEvent('keyup', function(){
            new Request.JSON({
                url: "json.php",
                onSuccess: function(response){
                    if (response.action == 'success') {
                        $('user_name').removeClass('error');
                        $('user_name').addClass('success');
                        
                    } else {
                        $('user_name').removeClass('success');
                        $('user_name').addClass('error');
                    }
                }
            }).get($('signup'));
        });
    });
    

    json.php

    <?php
    
        $config['db'] = array(
            'host'          => 'localhost',
            'username'      => 'username',
            'password'      => 'password',
            'dbname'        => 'database'
        );
    
        try {
            $DBH = new PDO('mysql:host=' . $config['db']['host']. ';dbname=' .$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
            $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $DBH->exec('SET CHARACTER SET utf8');
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
        
        $result = null;
        
        $user_name = mysql_real_escape_string($_POST['user_name']);
        
        $stmt = $DBH->prepare("SELECT user_name FROM ajax_users WHERE user_name = :user_name");
        $stmt->bindParam(':user_name', $user_name);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result == 0){
            
            $result['action'] = 'success';
            
        } else {
            
            $result['action'] = 'error';
        }
        
        $result['user_name'] = $_POST['user_name'];
        
        echo json_encode($result);
        
    ?>
    

    style.css

    input.success{
        border: 3px solid #9ad81f;
    }
    
    input.error{
        border: 3px solid #b92929;
    }
    

    The database is called "stuff" and it has a table called "ajax_users". 

     

    If something turned off? I am not sure where to go with this one. Thanks for the help in advance 

  12. SO i changed the code above to this

    function GetTaggedBlogPosts($postTags, $DBH)
    {
        
        $stmt = $DBH->prepare(" SELECT  blog_post.id,
                                        blog_post.title,
                                        blog_post.post,
                                        blog_post.author_id,
                                        blog_post.date_posted
                                FROM blog_post
                                LEFT JOIN (blog_post_tags) ON (blog_post.id = blog_post_tags.blog_post_id)
                                WHERE blog_post_tags.tag_id = :postTagId");
        $stmt->bindParam(":postTagId", $postTags, PDO::PARAM_INT);
        $stmt->execute();
    
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $postArray = array();
        
        foreach($result as $row){
            $myPost = new BlogPost($row["id"], $row['title'], $row['post'], $row['author_id'], $row['date_posted'], $DBH);
            array_push($postArray, $myPost);
        }
        return $postArray;
    }
    

    And it works great! Thank you so much! 

  13. I have been working on a code for a blog from scratch and now I have gotten the code to not throw errors but it is also not returning results.

     

     

    In this blog post I have created tags that can be attached to each blog post for easy reference. I have created a count of the tags on the right hand side which gives the name and a count for how many blog post use that tag. It is a link that you can click and the next step that I am having an issue with is just showing those blog post associated with that tag. I have written the code and as of right now is throwing no errors so I cannot look up how to fix it even though I have been working on it for hours. 

     

    Here is the call that I am using once you click the link to pull up the results.

     

    blog_tags.php

    <?php
    		include "includes.php";   
    						
    		
    		$blogPosts = GetTaggedBlogPosts($_GET['tagId'], $DBH);
    
                    foreach ($blogPosts as $post)
                    {
                        echo "<div class='post'>";
                        echo "<h2>" . $post->title . "</h2>";
    		    $body = substr($post->post, 0, 300);
    		    echo "<p>" . nl2br($body) . "... <a href='post_view.php?id=" . $post->id . "'>View Full Post</a><br /></p>";
                        echo "<span class='footer'><strong>Posted By:</strong> " . $post->author . " <strong>Posted On:</strong> " . $post->datePosted . " <strong>Tags:</strong> " . $post->tags . "</span><br />";
                        echo "</div>";
                    }
    		
    ?>	
    

    Next is the function for displaying the link and counting the tags

    includes.php

    function getTagCount($DBH) {
        
        //Make the connection and grab all the tag's TAG TABLE HAS TWO FIELDS id and name
                $stmt = $DBH->query("SELECT * FROM tags");
                $stmt->execute();
                
                //For each row pulled do the following
                foreach ($stmt->fetchAll() as $row){
                    //set the tagId and tagName to the id and name fields from the tags table
                    $tagId = $row['id'];
                    $tagName = ucfirst($row['name']);
                    
                    //Next grab the list of used tags BLOG_POST_TAGS TABLE HAS TWO FILEDS blog_post_id and tag_id
                    $stmt2 = $DBH->query("SELECT count(*) FROM blog_post_tags WHERE tag_id = " . $tagId);
                    $stmt2->execute();
                    $tagCount = $stmt2->fetchColumn();
                    
                    //Print the following list 
                    echo '<li><a href="blog_tags.php?tagId=' . $tagId . '"title="' . $tagName . '">' . $tagName . '(' . $tagCount . ')</a></li></form>';
                //End of loop - start again
                }
                
    }
    

    This next part is the function used to pull and display the blog post.

    includes.php

    function GetTaggedBlogPosts($postTags, $DBH)
    {
        
        $stmt = $DBH->prepare("SELECT blog_post_id FROM blog_post_tags WHERE tag_id = :postTagId");
        $stmt->bindParam(":postTagId", $postTags, PDO::PARAM_INT);
        $stmt->execute();
        
        if(!empty($stmt))
        {
            $blogstmt = $DBH->prepare("SELECT * FROM blog_post WHERE id = :blog_id ORDER BY id DESC");
            $blogstmt->bindParam(":blog_id", $stmt, PDO::PARAM_INT);
            $blogstmt->execute();
        }
        else
        {
            echo "Something went wrong....Please contact the administrator so that we can fix this issue.";
        }
        
        $postArray = array();
        
        $result = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
        foreach($result as $row){
            $myPost = new BlogPost($row["id"], $row['title'], $row['post'], $row['author_id'], $row['date_posted'], $DBH);
            array_push($postArray, $myPost);
        }
        return $postArray;
    }
    

    Any ideas why it is not displaying? 

  14. The problem is when I run it it gives me this error 

    
    ( ! ) Notice: Undefined index: tagId in C:\wamp\www\Rachel\blog_tags.php on line 78
    Call Stack
    #	Time	Memory	Function	Location
    1	0.0003	683256	{main}( )	..\blog_tags.php:0
    I apologize about there does not seem to be any post with that related tag.
    ( ! ) Notice: Undefined variable: blogstmt in C:\wamp\www\Rachel\includes.php on line 93
    Call Stack
    #	Time	Memory	Function	Location
    1	0.0003	683256	{main}( )	..\blog_tags.php:0
    2	0.0022	771608	GetTaggedBlogPosts( )	..\blog_tags.php:78
    
    ( ! ) Fatal error: Call to a member function fetchAll() on a non-object in C:\wamp\www\Rachel\includes.php on line 93
    Call Stack
    #	Time	Memory	Function	Location
    1	0.0003	683256	{main}( )	..\blog_tags.php:0
    2	0.0022	771608	GetTaggedBlogPosts( )	..\blog_tags.php:78
    

    I do not understand how it is getting the undefined index. I thought I was passing the url get method to this value, where am I going wrong?

  15. Hello All! 

     

    I am having an issue with requesting some information for certain blog post. I have written a blog in PHP and have come accross an issue when trying to look up certain articles with certain "Tags". Right now the system pulls up and counts the tag's correctly but when I am trying to click the name of the tag to view post only related to that tag, it keeps giving me trouble. Here is the code I have been using for sending and getting the information. First is the function I am using to count the tags and create a link to use

    function getTagCount($DBH) {
        
        //Make the connection and grab all the tag's TAG TABLE HAS TWO FIELDS id and name
                $stmt = $DBH->query("SELECT * FROM tags");
                $stmt->execute();
                
                //For each row pulled do the following
                foreach ($stmt->fetchAll() as $row){
                    //set the tagId and tagName to the id and name fields from the tags table
                    $tagId = $row['id'];
                    $tagName = ucfirst($row['name']);
                    
                    //Next grab the list of used tags BLOG_POST_TAGS TABLE HAS TWO FILEDS blog_post_id and tag_id
                    $stmt2 = $DBH->query("SELECT count(*) FROM blog_post_tags WHERE tag_id = " . $tagId);
                    $stmt2->execute();
                    $tagCount = $stmt2->fetchColumn();
                    
                    //Print the following list 
                    echo '<li><a href="blog_tags.php?=tagId=' . $tagId . '"title="' . $tagName . '">' . $tagName . '(' . $tagCount . ')</a></li></form>';
                //End of loop - start again
                }
                
    }
    

    Now here is the code I am using on the page it is being directed too(blog_tags.php)

    <?php
    		include "includes.php";   
    						
    
    				
    		$blogPosts = GetTaggedBlogPosts($_GET['tagId'],$DBH);
    
                    foreach ($blogPosts as $post)
                    {
                        echo "<div class='post'>";
                        echo "<h2>" . $post->title . "</h2>";
    		    $body = substr($post->post, 0, 300);
    		    echo "<p>" . nl2br($body) . "... <a href='post_view.php?id=" . $post->id . "'>View Full Post</a><br /></p>";
                        echo "<span class='footer'><strong>Posted By:</strong> " . $post->author . " <strong>Posted On:</strong> " . $post->datePosted . " <strong>Tags:</strong> " . $post->tags . "</span><br />";
                        echo "</div>";
                    }
    		
    ?>
    
    

    Here is also the function I am using

    function GetTaggedBlogPosts($postTags, $DBH)
    {
        if (!empty($postTags))
        {
            $postTagsIDsql = "SELECT blog_post_id FROM blog_post_tags WHERE tag_id = :postTagID";
            $postTagIDparam = array(
                ':postTagID' => $postTags
            );
            $postTagIDstmt = $DBH->prepare($postTagsIDsql);
            $postTagIDstmt->execute($postTagIDparam);
            
            
            $blogstmt = $DBH->prepare("SELECT * FROM blog_post WHERE id = :blog_id ORDER BY id DESC");
            $blogstmt->bindParam(":blog_id", $postTagsIDstmt, PDO::PARAM_INT);
            $blogstmt->execute();
            
        }
        else
        {
            echo 'I apologize about there does not seem to be any post with that related tag.';
        }
        $postArray = array();
        
        $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
        foreach($results as $row){
            $myPost = new BlogPost($row["id"], $row['title'], $row['post'], $row['author_id'], $row['date_posted'], $DBH);
            array_push($postArray, $myPost);
        }
            return $postArray;
    }
    

    I am just looking for a point in the right direction and to point out where my break down is happening. Thanks in advanced for your time, learning PHP on my own has been a chore but you all have helped make learning it so much easier. 

  16. I am writing a function to grab and count how many times a certain value is used in a table but get this error,

    Fatal error: Call to a member function query() on a non-object in C:\wamp\www\Rachels\includes.php on line 61
    

    I have tried looking up the error and found that it sometimes occurs when a variable is out of scope. I am passing my connection through the scope so I do not think that is the issue. My code is as follows 

    function getTagCount($inTagId=null, $inTagName=null, $DBH) {
        
        //Make the connection and grab all the tag's TAG TABLE HAS TWO FIELDS id and name
                $stmt = $DBH->query("SELECT * FROM tags");
                $stmt->execute();
                
                //For each row pulled do the following
                foreach ($stmt->fetchAll() as $row){
                    //set the tagId and tagName to the id and name fields from the tags table
                    $tagId = $row['id'];
                    $tagName = $row['name'];
                    
                    //Next grab the list of used tags BLOG_POST_TAGS TABLE HAS TWO FILEDS blog_post_id and tag_id
                    $stmt2 = $DBH->query("SELECT * FROM blog_post_tags");
                    $stmt2->execute();
                    $blogTagList = array();
                    $blogTagList = $stmt2->fetchAll();
                    $tagCount = array_count_values($blogTagList);
                    //Print the following list 
                    echo '<li><a href="popular_tags.php?=' . $tagId . '" title="' . $tagName . '">' . $tagName . '(' . $tagCount[$tagId] . ')</a></li>';
                //End of loop - start again
                }
                
    }
    
×
×
  • 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.