Basic text not displaying

Okay, I’ve been through Learnable’s PHP/MySQL class with Kevin Yank twice. This is my first attempt applying my new skills to an actual site. It’s going okay so far, but my first trial to get database information to display on the page isn’t going well.

My goal is to allow the client to updates their announcements and schedule in-house. I haven’t started on the CMS portion yet, I’m just entering a couple test lines of data via PHPMyAdmin for now. When I try to get the announcement in the database to come up on the site, it’s just blank. My test line for database connection comes up, but that’s it.

Most people here could likely get this entire request done in an afternoon, but I’m coming from just doing front-end development. Please let me know what I missed in spelling or whatever so I can quit pulling my hair out. Thanks.

connect.php:

<?php
$link = mysqli_connect('localhost', 'sulluser', 'password');
if (!$link)
{
	$error = 'Unable to connect to the database server.';
	include 'error.php';
	exit();
}

if (!mysqli_set_charset($link, 'utf8'))
{
	$output = 'Unable to set database connection encoding.';
	include 'error.php';
	exit();
}

if (!mysqli_select_db($link, 'sullSite12'))
{
	$error = 'Unable to locate the joke database.';
	include 'error.php';
	exit();
}

$output = 'Yes, it is connected.';
include 'index.php';
?>

magicquotes.php:

<?php
if (get_magic_quotes_gpc())
{
	function stripslashes_deep($value)
	{
		$value = is_array($value) ?
				array_map('stripslashes_deep', $value) :
				stripslashes($value);

		return $value;
	}

	$_POST = array_map('stripslashes_deep', $_POST);
	$_GET = array_map('stripslashes_deep', $_GET);
	$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
	$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
?>

helpers.php:

<?php

function html($text)
{
	return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

function htmlout($text)
{
	echo html($text);
}

?>

announce.php:

<?php
include 'assets/includes/connect.php';
include 'assets/includes/magicquotes.php';

//Read the announcements
$sql = 'SELECT id, eventday, event FROM announcement';
$eventitem = mysqli_query($link, $sql);

//If something went wrong
if(!$eventitem)
{
	$error = 'Could not get announcement information.';
	include 'index.php';
	exit();
}

//Get information and store it in variable announcements
while ($row = mysqli_fetch_array($eventitem))
{
	$announcements[] = array('id' => $row['id'], 'date' => $row['eventday'], 'text' => $row['event']);
}

include 'index.php';
exit();

?>

index.php (go about 3/4 down for relevant sections):

<?php include_once 'assets/includes/connect.php'; ?>
<?php include 'assets/includes/helpers.php'; ?>
<!doctype html>
<html lang="en"><!-- InstanceBegin template="/Templates/mainp.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<meta charset="utf-8">
        <!-- InstanceBeginEditable name="doctitle" -->
        <title>Sully Christian Grade</title>
        <!-- InstanceEndEditable -->
        <script src="assets/js/jquery-1.5.min.js"></script>
        <!-- InstanceBeginEditable name="head" -->
		<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>
        <script type="text/javascript" src="http://malsup.github.com/jquery.cycle.all.js"></script>
        <script type="text/javascript">
			$('#picslideshow').cycle({
				fx: 'fade',
				speed: 900,
				timeout: 4000,
				pause: 1,
				random: 1
			});
		</script>
        <meta name="google-site-verification" content="m6fPzAV80csLHBOv4R7AVDtD1MgrQLZkSL3Crjn_CO4" />
        <meta name="description" content="Sully Christian Grade School is located in south central Iowa. Our students receive Christ-centered education with a student teacher ratio of 8:1.">
        <!-- InstanceEndEditable -->

<link href="assets/scs20.css" rel="stylesheet" type="text/css">
<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>

    <!--[if lt IE 8]>
        	<link href="http://www.sullychristian.org/assets/oldie.css" rel="stylesheet" type="text/css">
    <![endif]-->
<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css">
</head>

<body>
  <div id="masterpage">
    	<div id="header">
        	<img src="assets/images/site/banner-150.jpg" alt="Sully Christian Grade School" width="1024" height="150">
  </div>
        <div class="navBlack"></div>
      	<div id="nav">
        <ul id="MenuBar1" class="MenuBarHorizontal">
                <li id="home"><a href="index.php" class="navborder" title="Home">Home</a></li>
                <li id="about"><a href="#" title="About" class="MenuBarItemSubmenu navborder">About</a>
                    <ul>
                        <li><a href="about/mission.php" title="Mission Statement">Mission Statement</a></li>
                        <li><a href="about/quickfacts.php" title="Quick Facts">Quick Facts</a></li>
                        <li><a href="about/faculty.php" title="Faculty">Faculty</a></li>
                        <li><a href="about/board.php" title="Board">Board</a></li>
                        <li><a href="about/committees.php" title="Committees">Committees</a></li>
                        <li><a href="about/history.php" title="History">History</a></li>
                  </ul>
                </li>
                <li id="academics"><a href="#" class="MenuBarItemSubmenu navborder">Academics</a>
                  <ul>
                  	<li><a href="academics/classrooms.php" title="Classrooms">Classroooms</a></li>
                    <li><a href="academics/itbs.php" title="ITBS Scores">ITBS Scores</a></li>
                    <li><a href="academics/iacore.php" title="Iowa Core">Iowa Core</a></li>
                  </ul>
                </li>
                <li id="calendars"><a class="MenuBarItemSubmenu navborder" href="#">Calendars</a>
                  <ul>
                  	<li><a href="calendar.php" title="Main Calendar">Main Calendar</a></li>
                    <li><a href="assets/pdf/calendars/academiccalendar.pdf" title="Academic Calendar" class="external">Academic</a></li>
                    <li><a href="assets/pdf/calendars/schoolcalendar.pdf" title="School Calendar" class="external">School</a></li>
                    <li><a href="assets/pdf/calendars/lunch.pdf" title="Lunch" class="external">Lunch</a></li>
                    <li><a href="assets/pdf/calendars/sportsschedule.pdf" title="Athletic" class="external">Athletic</a></li>
                </ul>
              </li>
              <li id="news"><a href="#" class="MenuBarItemSubmenu navborder">News</a>
                 <ul>
                   <li><a href="assets/pdf/newsletter/scsnewsletter/scsnewsletter.pdf" title="SCS Newsletter" class="external">SCS Newsletter</a></li>
                   <li><a href="assets/pdf/newsletter/bitspieces/bitspieces.pdf" title="Bits 'n Pieces" class="external">Bits 'n Pieces</a></li>
                   <li><a href="newsletter.php" title="News">Newsletter Archives</a></li>
                 </ul>
              </li>
              <li id="athletics"><a href="#" title="Warrior Athletics" class="MenuBarItemSubmenu navborder">Warrior Athletics</a>
              	  <ul>
                  	<li><a href="athletics/athletics.php" title="Warrior Athletics">Athletics</a></li>
                  	<li><a href="assets/pdf/forms/physicalform.pdf" title="Physical Form" class="external">Physical Form</a></li>
                    <li><a href="assets/pdf/calendars/sportsschedule.pdf" title="Schedule" class="external">Schedule</a></li>
                    <li><a href="athletics/scores.php" title="Scores">Scores</a></li>
                    <li><a href="athletics/directions.php" title="Directions">Directions</a></li>
                  </ul>
                </li>
                <li id="parents"><a href="#" class="MenuBarItemSubmenu navborder">Parents</a>
                  <ul>
                  	<li><a href="assets/pdf/newsevents/parenthandbook.pdf" title="Parent Handbook" class="external">Parent Handbook</a></li>
                    <li><a href="assets/pdf/newsevents/supplylist.pdf" title="School Supply List" class="external">School Supply List</a></li>
                    <li><a href="parents/trip.php" title="TRIP">TRIP</a></li>
                    <li><a href="parents/tuitionhelp.php" title="Tuition Assistance">Tuition Assistance</a></li>
                    <li><a href="https://rodlanapps.com/cgi-bin/WAV/acntview.cgi#ec1ARgw69U54eHh4" title="Lunch Account" class="external">Lunch Account</a></li>
                    <li><a href="assets/pdf/ReducedLunchApplication.pdf" title="Free or Reduced Lunch Application" class="external">Free &amp; Reduced Lunch Application</a></li>
                    <li><a href="https://schoolalerts.iowa.gov/10194-School_Alerts/index.jsp" title="School Alerts" class="external">School Alerts</a></li>
                  </ul>
                </li>
                <li id="donate"><a href="#" class="MenuBarItemSubmenu navborder">Donate</a>
                  <ul>
                    <li><a href="donate/logsto.php" title="LOG/STO">LOG/STO</a></li>
                    <li><a href="donate/scholarships.php" title="Scholarships">Scholarships</a></li>
                    <li><a href="donate/endowment.php" title="Endowment">Endowment</a></li>
                    <li><a href="donate/support.php" title="Matching Gift Employers">Matching Gift Employers</a></li>
                  </ul>
                </li>
                <li id="fundraising"><a href="fundraising.php" title="Fundraising" class="navborder">Fundraising</a></li>
                <li id="links"><a href="links.php" title="Links" class="navborder">Links</a></li>
                <li id="contact"><a href="#" title="Contact" class="navborderend">Contact</a>
                  <ul>
                  	<li><a href="contact/contact.php" title="School Contact">School</a></li>
                    <li><a href="http://maps.google.com/maps?q=12629+S+92nd+Ave+E,+Sully,+IA&hl=en&sll=37.0625,-95.677068&sspn=41.767874,71.455078&z=16" title="School Map" class="external">Find Us</a></li>
                    <li><a href="contact/staffdirectory.php" title="School Directory">School Directory</a></li>
                    <li><a href="contact/employment.php" title="Employment">Employment</a></li>
                  </ul>
                </li>
        </ul>
        </div>
        <div class="navBlack"></div>
      <div id="main">
          <div id="maincontent">
              <div id="pageContent">
              	<!-- InstanceBeginEditable name="Content" -->
      			<div id="picslideshow">
                	<img src="assets/images/index/index01.jpg" alt="Sully Christian School" width="540" height="270" class="start">
                    <img src="assets/images/index/index02.jpg" alt="School Entrance" width="540" height="270">
                    <img src="assets/images/index/index03.jpg" alt="School Entrance" width="540" height="270">
                    <img src="assets/images/index/index04.jpg" alt="School Hall" width="540" height="270">
                    <img src="assets/images/index/index05.jpg" alt="Classroom" width="540" height="270">
                    <img src="assets/images/index/index06.jpg" alt="Computer Lab" width="540" height="270">
                    <img src="assets/images/index/index07.jpg" alt="High Jump" width="540" height="270">
                    <img src="assets/images/index/index08.jpg" alt="Two Boys" width="540" height="270">
                    <img src="assets/images/index/index09.jpg" alt="Basketball Court" width="540" height="270">
                    <img src="assets/images/index/index10.jpg" alt="Playground" width="540" height="270">
                </div> <!-- End slideshow -->
      <div id="greeting">
      <p>Welcome to Sully Christian School!  Our school is a place where God's Word serves as the foundation to empower students to follow the Master Teacher, Jesus Christ, and enables our teachers to fulfill our school's commitment to help nurture students in excellence and truth for their Creator.</p>
      <p>Students are encouraged and challenged to work to their full potential as they develop their God-given talents to serve as God's disciples in His Kingdom.</p>
      <p>Thanks for visiting our website.  Stay a while and explore to learn more about our school.<br>
        <span class="rightalign">-Karen Hackert, Head Teacher</span></p>
      </div>
      <div id="theme"> <img src="assets/images/theme.jpg" width="145" height="75" alt="Power Up!">This year's theme, &quot;Power Up,&quot; is centered around Philippians 4:13 <span class="italics">&quot;I can do all things through Christ who strengthens me.&quot;</span><br>
      Our song for 2011-12 is: <a href="http://youtu.be/rPR3zj0PtKM" title="Faith by Hillsong" class="external"><span class="italics">Faith</span> by Hillsong</a>      </div>
      <div id="indexnews">
      	<h2>Announcements</h2>
        <?php echo $error; ?>
        <?php foreach ($announcements as $event): ?>
            <p>
                <?php htmlout($announcement['date']); ?>
                <?php htmlout($event['text']); ?>
            </p>
        <?php endforeach; ?>
        <?php echo $output; ?>
</div>
      <!-- InstanceEndEditable -->
              </div> <!-- end pagecontent -->
              <div id="rightside">
              	<div id="infoBox">
                	<h3>Quick Links</h3>
                    <ul class="quicklink">
                        <li><a href="index.php" title="Home">Home</a></li>
                        <li><a href="calendar.php" title="School Calendar">School Calendar</a></li>
                        <li><a href="https://rodlanapps.com/cgi-bin/WAV/acntview.cgi#ec1ARgw69U54eHh4" title="School Lunch Account" class="external">School Lunch Account</a></li>
                        <li><a href="parents/trip.php" title="TRIP">TRIP</a></li>
                        <li><a href="newsletter.php" title="Newsletters">Newsletters</a></li>
                        <li><a href="http://www.schoolnet8.com/site.phtml?station=SSUI4&station2=SCSI4" title="Weather Station" class="external">Weather Station</a></li>
                        <li><a href="https://schoolalerts.iowa.gov/10194-School_Alerts/index.jsp" title="School Alerts" class="external">School Alerts</a></li>
                        <li><a href="https://picasaweb.google.com/sullychristian05" title="Recent Event Pictures" class="external">Recent Event Pictures</a></li>
                    </ul>
                    <h3>Upcoming Events</h3>
                    <ul>
                        <li>March 23: 1:30 Dismissal -End of 3rd Quarter</li>
                        <li>March 28: 2:30 Dismissal -Parent Teacher Conferences</li>
                        <li>March 29: Parent Teacher Conferences PM</li>
                        <li>March 30: No School</li>
                        <li>April 5: No School -In-service</li>
                        <li>April 6: No School -Good Friday</li>
                    </ul>
              <h3>Contact Information</h3>
              <p>12629 S 92nd Ave E<br />
              Sully, IA 50251</p>
              <p>Phone: 641-594-4180<br>
                Fax: 641-594-3799
              </p>
              <p>Email: <a href="mailto:lloftus@sullychristian.org" title="Mail Sully Christian">lloftus@sullychristian.org</a></p>
              <div id="cse-search-form" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
  google.load('search', '1', {language : 'en'});
  google.setOnLoadCallback(function() {
    var customSearchControl = new google.search.CustomSearchControl('008298257734023449732:eesga3goiha');
    customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
    var options = new google.search.DrawOptions();
    options.enableSearchboxOnly("http://www.google.com/cse?cx=008298257734023449732:eesga3goiha", null, true);
    customSearchControl.draw('cse-search-form', options);
  }, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
<style type="text/css">
  input.gsc-input {
    border-color: #a52a2a;
  }
  input.gsc-search-button {
    border-color: #666666;
    background-color: #CECECE;
  }
</style>

              	</div> <!-- End infobox -->
              </div> <!-- End rightside -->
          </div> <!-- End maincontent -->
      </div> <!-- End main -->
<div id="footer">Sully Christian Grade School &nbsp;|&nbsp; 12629 S 92nd Ave E &nbsp;|&nbsp; Sully, IA 50251 &nbsp;|&nbsp; 641-594-4180</div>
</div> <!-- End masterpage -->
<script src="assets/js/links.js"></script>
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"", imgRight:""});
</script>
<!--<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1841699-24']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>-->
</body>
<!-- InstanceEnd --></html>

Have you
var
_dump($eventitem)
[COLOR=#000000][FONT=monospace][SIZE=3][FONT=trebuchet ms]to see what is being returned? Have you using PHPMyAdmin run your SELECT query to see if it returns any results.

Check these first and then well go from there.

Regards,
Steve[/FONT][/SIZE][/FONT][/COLOR]

I’m not familiar with the “var_dump” item, so I may have done it wrong. I put it in as “var_dump($eventitem);”, “var_dump($announcements);”, and “var_dump($event[‘text’]);” in my index file and received NULL. Running the select statement in PHPMyAdmin produced the results I was looking for, date and text just as I expected.

Hi vmtech,

Your first two examples of var_dump(); is how one normally uses it, the var_dump($event[‘somethin’]); will return a value but you would normally var_dump($event) and it would tell you that it is an array and show the values (if any exist).

The null values mean that the variables are not being set. Your query (run from PHP using the mysqli) is not returning the data. You have to check if the query string is actually a string and you have to ensure that any variables you are quoting out in that string also have values; otherwise the query will not return results.

The var_dump($variable); will provide verbose output of the contents of a variable. The Mysqli query should return and array so normally var_dump($results); should return something that looks like this:


$results = array('colour' => 'blue', 'Vegatation' => 'trees', 'Animal' => 'Bird');
var_dump($results);
/* Outputs */
array(3) { ["colour"]=> string(4) "blue" ["Vegatation"]=> string(5) "trees" ["Animal"]=> string(4) "Bird" }

Your query should return an array similar, only the key names will be the column names defined in the query.

To troubleshoot, I recommend starting a very simple PHP page that you setup the mysqli connection and try to run the SELECT and then run var_dump($results); Get the query working there first before you do everything else you are attempting in your scripts.

Steve

Thanks, that makes sense. Time for more testing and debugging.

If you don’t have this at the beginning of your PHP file it may help if your config doesn’t already have them set.


# DEVELOPMENT + DEBUGGING
error_reporting(E_ALL);
ini_set('display_errors', true);

I’m working on a test page with the suggestions given, but unfortunately I’m not gaining ground.

On my test page I don’t link to the script the script (announce.php) that has the code retrieving information from the database, just like I did in class. However, I then get errors of undefined variables on every line with a variable. If I add an include announce.php line, the undefined variable errors don’t come up, just the attached screen shot.

The two files, test.php and announce.php are below. None of the others have changed since my original post. Thanks for the help so far. I’m sure that it’s something minor I’m missing, but I don’t see what it is. Test and announce are both in the same directory on the server.

test.php:

<?php # DEVELOPMENT + DEBUGGING
error_reporting(E_ALL);
ini_set('display_errors', true); ?>

<?php include 'assets/includes/helpers.php'; ?>
<?php include 'announce.php'; ?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Test Page</title>
    </head>

    <body>
        <h1>Test Announcements</h1>
        <?php echo $error; ?>
        <?php var_dump($events); ?>
        <?php foreach ($events as $event): ?>
        <p>
            <?php htmlout($event['event']); ?>
        </p>
        <?php endforeach; ?>
    </body>
</html>

announce.php

<?php
include 'assets/includes/connect.php';
include 'assets/includes/magicquotes.php';

$result = mysqli_query($link, 'SELECT event FROM announcement');
if(!$result)
{
	$error = 'Error getting events: ' . mysqli_error($link);
	include 'test.php';
	exit();
}
while($row = mysqli_fetch_array($result))
{
	$events[] = $row['event'];
}
include 'test.php';
?>

Hi vmtech,
Here is what I notice:

  1. Notice that your are doing a ‘circular include’ where announce.php is including test.php and test.php is including announce.php. You should only have announce.php including test.php and instead of using include you should use require_once(‘test.php’);
  2. I think that you are not getting any reading in var_dump($events) as you are not really including the database file that contains this global variable.
  3. You should initialize your variables before you use them, so for example before your
    while($row = mysqli_fetch_array($result)) { $events[] = $row['event'];
    you should do this instead

    $events = array(); while($row = mysqli_fetch_array($result)) { $events[] = $row['event'];
    If you still get nothing when you output var-dump(events) then you are not getting anything back in your mysqli_fetch_array() so you will need to ensure that this is returning results. Inside the while loop put a var_dump($row) ; statement.

Regards,
Steve

Sorry for the delay, other work and life came up. I made the changes and tests suggested, but I’m still not seeing a changes.

I put the var_dump statement in the announce.php page and it does produce the array with the expected results when I go directly to announce.php in my browser on my test server. Unfortunately, going to test.php, the page that is supposed to show the results, I only get undefined variable errors.

This is half of two parts that will be showing database contents. I did the other section just to see if I missed something, but I get the same results as this one with undefined variable errors. The new coding for the pages is below. Thanks again for the help.

announce.php

<?php
include 'assets/includes/connect.php';
include 'assets/includes/magicquotes.php';

$result = mysqli_query($link, 'SELECT eventtext FROM announcement');
if(!$result)
{
	$error = 'Error getting events from database.';
	include 'error.php';
	exit();
}
$events = array();
while($row = mysqli_fetch_array($result))
{
	var_dump($row);
	$events[] = $row['eventtext'];
}
include 'test.php';
?>

test.php

<?php # DEVELOPMENT + DEBUGGING
error_reporting(E_ALL);
ini_set('display_errors', true); ?>

<?php include 'assets/includes/helpers.php'; ?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Test Page</title>
    </head>

    <body>
        <h1>Test Announcements</h1>
        <?php //echo $error; ?>
        <?php var_dump($events); ?>
        <?php foreach ($events as $event): ?>
            <p>
                <?php echo($event); ?>
            </p>
        <?php endforeach; ?>
    </body>
</html>

Unfortunately, still no success with this. I’m still at the last post with code and no progress on the other parts. Unfortunately, I may have to outsource a very basic PHP script.

Hi vmtech,

Are you sure that test.php is including?

Here is an alternative way of doing what you are trying to do, you are free to use this if you want:

PDO Factory Class:

 
<?php 
class DbFactory{
  private static $factory;
  public static function getFactory(){
      if (!self::$factory){
        self::$factory = new DbFactory();
        return self::$factory;
      } else {
        throw new exception('DbFactory could not return database instance.');
      }
  }
  private $db;
  public function getConnection(){
      if (!$db)
           $db = new PDO("mysql:host=localhost;dbname=db_name", "your_user", "your_password");
      return $db;
  }
}

 ?>
 

You would need to replace db_name with your database name, your_user with your username and your_password with your password.

Then in your test.php you do the following:

 
<?php 
# DEVELOPMENT + DEBUGGING  
error_reporting(E_ALL);  
ini_set('display_errors', true);
# Includes
require_once( 'assets/includes/helpers.php'); 
# The class shown above stored in a separate file in the includes folder
 require_once('assets/includes/DbFactory.php'); 
# Get instance of PDO connector to your database
$o_Db = DbFactory::getFactory()->getConnection(); 
?> 
<!doctype html> 
<html> 
    <head> 
        <meta charset="utf-8"> 
        <title>Test Page</title> 
    </head> 
     
    <body> 
        <h1>Test Announcements</h1> 
         <?php //echo $error; ?> 
          <?php
                $fields = 'eventtext';
                $table_name = 'announcement';
                $results = GetData($o_Db, $table_name, $fields);
                foreach($results as $array){
                  foreach($array as $event){
                     echo "<p> $event </p>";
                  }
               } 
           ?>
 
    </body> 
</html>
<?php
function GetData(PDO $o_Db, $table_name,$fields){
  if(!$o_Db || !$table_name || !fields){
    throw new exception('GetData(PDO $o_Db, string $table_name, array or string $fields. You 
    did not pass one of the variables');
  }
  if(is_array($fields)){
    $fields_count = count($fields);
    $i = 1;
    $sql_fields = null;
    foreach($fields as $value){
      if($i < $fields_count){
        $sql_fields .= "$value, ";
      } else {
        $sql_fields .= "$value";
      }
      $i++;
    }
  } else {
    $sql_fields = htmlentities($fields);
  }
  $table_name = htmlentities($table_name);

  $sql = "SELECT $sql_fields FROM $table_name";
  echo $sql;
  $stmt = $o_Db->prepare($sql);
  $stmt->execute();
  return $stmt->fetchAll(PDO::FETCH_ASSOC); 
  }
?>

Try and see if you can work with this?

You can also pass the GetData function fields formatted like:

  • $fields = ‘fieldname’; then pass it like GetData($o_Db, $table_name, $fields);
  • $fields = array(‘field1’, ‘field2’, ‘field3’); then pass it like GetData($o_Db, $table_name, $fields);
  • $fields = ‘field1, field2, field3’; then pass it like GetData($o_Db, $table_name, $fields);

Regards,
Steve

The debugging line came up with a few complaints, but it FINALLY displayed the database information as it should. Thank you very much for the help, it looks like I can keep going, for now at least.

Sorry to bring up old threads, but I’m having trouble with this DbFactory now on the active site. It was just now uploaded to the site’s server, so this project has been well dragged out to say the least.

The page produces this error:
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in e:\websites\1414\sullychristian.org\assets\includes\DbFactory.php on line 3

Other than the server connection information, I have not changed anything from the code given a few months ago in the code above. This is also the only time I’ve worked with DbFactory, so please help when possible.

Hi vmtech,

What version of PHP is your Active Site? If it is PHP 4 then this error will be thrown.

I thought of that, but it’s on 5.

Hi

Can you let us know what echo PHP_VERSION; returns?

Steve

Well, I set it up on PHP MySQL 5 server, but the echo came back with 4.4.6.

That’s why then… I don’t know if you can upgrade this to a version 5.3.x but if possible you should. PHP 4 (as you likely know) is a dinosaur that you should avoid like a Rex ;D

It’s on a generic, cheap, hosted system, but I’ll see what I can do. Thanks.

After finally finding the correct person at the host, getting the upgrade went well. Now everything is running, but it’s coming up with two variable errors. One is that db is undefined in line 14 of DbFactory.php and the other is fields on line 5 of getschedule.php. My login also is isn’t working, but I’m getting to it yet.

From what I see, both of the variables are declared. They haven’t changed from my testing model, so I’m not sure where to look. The scripts are posted below, so maybe you can see something. This site is now up at: http://www.sullychristian.org/calendar.php, everything is up except the index. I’m testing the PHP site before removing html.

DbFactory.php


<?php
class DbFactory{
  private static $factory;
  public static function getFactory(){
      if (!self::$factory){
        self::$factory = new DbFactory();
        return self::$factory;
      } else {
        throw new exception('DbFactory could not return database instance.');
      }
  }
  private $db;
  public function getConnection(){
      if (!$db)
           $db = new PDO("mysql:host=216.51.232.202;dbname=db1569", "user", "password");
      return $db;
  }
}
?>

getschedule.php


<?php
$o_Db = DbFactory::getFactory()->getConnection();

function GetSchedule(PDO $o_Db, $table_name, $fields){
  if(!$o_Db || !$table_name || !fields){
    throw new exception('GetData(PDO $o_Db, string $table_name, array or string $fields. You did not pass one of the variables');
  }
  if(is_array($fields)){
    $fields_count = count($fields);
    $i = 1;
    $sql_fields = null;
    foreach($fields as $value){
      if($i < $fields_count){
        $sql_fields .= "$value, ";
      } else {
        $sql_fields .= "$value";
      }
      $i++;
    }
  } else {
    $sql_fields = htmlentities($fields);
  }
  $table_name = htmlentities($table_name);

  $sql = "SELECT datetext FROM schedule";
  $stmt = $o_Db->prepare($sql);
  $stmt->execute();
  return $stmt->fetchAll(PDO::FETCH_ASSOC);
  }
?>