Hey, I was following through a tutorial and was trying to simplify it to my needs. I cant get anything to work.. if unsure, some debugging tips would be great!
Here is the class.php file:
class MySQL{
public static function connect($set_host, $set_username, $set_password, $set_database){
mysql_connect("$set_host", "$set_username", "$set_password")or die("cannot connect");
mysql_select_db("$set_database")or die("cannot select DB");
}
}
class Posts {
public $id;
public $title;
function __construct($_id, $_title){
$this->id = $_id;
$this->title = $_title;
}
}
class Generate {
function queryPosts(){
$query = mysql_query("SELECT * FROM posts ORDER BY id DESC");
$postArray = array();
while ($row = mysql_fetch_assoc($query)){
$posts = new Posts($row["id"], $row['title']);
array_push($postArray, $posts);
}
return $postArray;
}
}
and here is the index:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>dev</title>
</head>
<body>
<?php
include ("class.php");
MySQL::connect('localhost', 'test', 'pass', 'table');
$blog = Generate();
foreach ($blog as $post)
{
echo $post->title . "<br/>";
}
?>
</body>
</html>
I really cant get anything to generate with this method. The table/data is there, and I can display them in a procedural manner.. however I am trying to get into oop methods of doing this. Knowing me it's probably a really silly syntax error. Many thanks!
You're not using the new keyword, and then you're trying to iterate on $blog which is an object. You need to call the object's method, queryPosts, and iterate over it's results.
...
$blog = new Generate();
$posts = $blog->queryPosts();
foreach ($posts as $post) {
...
You should be instantiating Generate with new:
$blog = new Generate;
foreach($blog->queryPosts() as $postArray){
}
Another thing why are you putting " before and after the variable. It should be:
mysql_connect($set_host, $set_username, $set_password) or die("...");
As you may already know, #David's answer solves the problem quite well, however, since you said you were following a tutorial, I want to make you some recomendations so you don't go down into PHP's dark path.
You should consider putting different classes in different files
Having a Class to connect directly to the database is not that good, try to connect to the database on the queryPosts method and not in the index.php file
For starting purpouses, implementing data access like this will get you around the problem, but if you start working on more professionally oriented apps, consider using a ORM framework for data access, like Propel or Doctrine
Hope I can help!
Related
I've got two files, like these two:
<?php
session_start();
class test{
public function login($code){
$app = JFactory::getApplication('site');
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(array('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('code') . " = " . $db->quote($code));
$db->setQuery($query);//execute query
$results = $db->loadObjectList();//get results
if ($results[0] != null) {
$this->createSession($results[0]);
header("refresh:2;url=second_file.php");
}
return json_encode($results);
}
public function createSession($LoginInfo){
$_SESSION['userId']=$LoginInfo->id;
}
}
?>
and another php file like this:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<?php
echo $_SESSION['userId'];
?>
</body>
</html>
In the second page seems like that there is no information inside the session and i'm unable to get "userId" parameter.
PS: the first class php file is called by another php file where there is something like this:
require_once('test.class.php');
$mainframe = new test
if ($_GET['code']!=null) echo $mainframe->login($_GET['code']);
Where am I doing wrong? thanks.
PPS: All those file are hosted inside altervista.org and there is Joomla CMS installed.
I have a problem. I writed OOP in php, but it does not work. It gives me blank result. I putted screenshots of my code and result of that code above. Please analyse these codes and help me, how I can solve it. By the way my php version is 5.3. I can upgrade or downgrade it if it is important. Thanks.
index.php
<?php include('class_library.php'); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OOP ilk dersim)</title>
</head>
<body>
<?php
$phpders = new adam();
$padisah = new adam();
//----------
$phpders -> set_ad('NurlanXp 1');
$padisah -> set_ad('NurlanXp 2');
//------------
echo "PhpDersden gelen: ".$phpders -> get_ad;
echo "<br>Padisahdan gelen: ".$padisah -> get_ad;
?>
</body>
</html>
class_library.php
<?php
class adam{
var $ad;
function set_ad($yeni_ad){
$this -> ad = $yeni_ad;
}
function get_ad(){
return $this -> ad;
}
}
?>
index.php, class_library.php and the result of the code. Screenshots.
All documents in the same folder.
You seems using $padisah -> get_ad but your adam class doesn't have any getter metod so you have to use like
$padisah -> get_ad();
You can find working example on https://eval.in/591811
In Turkish: get_ad kısmının sonunda parantez açıp, kapatırsan sorun çözülür. Adam class'ının içerisinde getter metodu yok. Yukarıda verdiğim linkte sonundaki parantezle sorunun çözüldüğünü görebilirsin.
this is Your class:
<?php
class adam {
private $ad;
public function get_ad() {
return $this->ad;
}
public function set_ad($ad) {
$this->ad = $ad;
return $this;
}
}
and inside of code:
$phpders = new adam();
$padishah = new adam();
$phpders->set_ad('NurlanXP 1');
$padishah->set_ad('NurlanXP 2');
and usage of get_ad:
echo 'phpdersden gelen: '.$phpders->get_ad().'<br/>';
echo 'padishahdan gelen: '.$padishah->get_ad().'<br/>';
(After solving the issue mentioned by "num8er" - calling method with () ...)
Try to give an absolute include path
<?php include('/complete/path/to/class_library.php'); ?>
or set an appropriate include path set_include_path() before. You can use $_SERVER['DOCUMENT_ROOT'] as a base to build a path.
I usually use Smarty template engine, so i separate database quesries and other logic from HTML template files, then assign received in PHP variable into Smarty via their function $smarty->assign('variableName', 'variableValue'); then display correct template file with HTML markup, and then i can use within that template my assigned variables.
But how correctly it will be done with .php file tempaltes, without Smarty?
For example, i use that construction:
_handlers/Handler_Show.php
$arData = $db->getAll('SELECT .....');
include_once '_template/home.php';
_template/home.php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item) { ?>
<h2><?=$item['title']?></h2>
<?php } ?>
...
</body>
</html>
It's work. But i heard that it's not the best idea to do that.
So is this approach correct? Or maybe there's other way to organize it?
Give me advice, pelase.
Including templates in such a manner like in your example is not best idea because of template code is executed in the same namespace in which it is included. In your case template has access to database connection and other variables which should be separated from view.
In order to avoid this you can create class Template:
Template.php
<?php
class Template
{
private $tplPath;
private $tplData = array();
public function __construct($tplPath)
{
$this->tplPath = $tplPath;
}
public function __set($varName, $value)
{
$this->tplData[$varName] = $value;
}
public function render()
{
extract($this->tplData);
ob_start();
require($this->tplPath);
return ob_get_clean();
}
}
_handlers/Handler_Show.php
<?php
// some code, including Template class file, connecting to db etc..
$tpl = new Template('_template/home.php');
$tpl->arData = $db->getAll('SELECT .....');
echo $tpl->render();
_template/home.php
<?php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item): ?>
<h2><?=$item['title']?></h2>
<?php endforeach; ?>
...
</body>
</html>
As of now template hasn't access to global namespace. Of course it is still possible to use global keyword,
or access template object private data (using $this variable), but this is much better solution than
including templates directly.
You can look at existing template system source code, for example plates.
I am a PHP beginner and trying to write PHP classes that work with HTML and MySql.
I am facing the following problem,
I have created a class called DatabaseManager that contains the function get_value. This function simply returns a value. In another file, I am calling this function on a button click using java script. But the link doesn't seem to work between the two files....Can someone help me?
thank you.
Here's my file that contains the PHP class.
<!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">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<?php
class DatabaseManager {
private $value=1;
public function get_value ()
{
return value;
}
}
/php>
</body>
</html>
and here's the other file that calls it.
<html>
<head>
<?php include("DatabaseManager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
The name of the file that contains the function get_value is DatabaseManager.php
DO Like this
In Databasemanager.php
<?php
class DatabaseManager {
private $value = 1;
public function get_value() {
return $this->value;
}
}
?>
In another PHP file
<html>
<head>
<?php include("Databasemanager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
A few things:
in DatabaseManager.php remove all HTML. You're including the file elsewhere, you don't need or want duplicated HTML tags.
Remove the # in your MySQL section. This suppresses any errors you are having.
Switch to PDO or MySQLi. They are safer (if used properly)
Your closing php tag is wrong in the database file. You have /php> it should be ?>
Your class does absolutely nothing as-is.
There are multiple things here that you're douing wrong.
You don't need the html code in the first example.
You close the php wrong /php> should generate an error, it should be ?>
When your instantiating your DatabaseManager class you've left out the parentheses which means that the constructor will never get called, this should also generate an error.
You're probably trying to use alert in javascript which in this case you're not doing.
It should look something like this instead:
<?php
class DatabaseManager {
private $value = 1;
function getValue() {
return $this->value;
}
}
?>
And in your html (still php, but the one containing the html-markup) file:
<html>
<head>
<script type="text/javascript">
function connect() {
alert("
<?php
include "nameofDBManagerClassFile.php"
$dbm = new DatabaseManager();
echo "the value is " . $dbm->getValue();
?>
");
}
</script>
</head>
<body>
</body>
</html>
It could also be that you think that the php-code that is inside of the javascript function will not be executed untill you call the JS function connect() this is not so. PHP code is executed on the server and thus will be called when a user requests that webpage, the javascript on the other hand is clientside and will be executed in the users browser. I highly recommend that you read up on both php and JavaScript.
You do it wrong way, to output something in your JavaScript function connect() make this :
function connect() {
alert("
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
");
}
because php code is executed apart from your on click event.
Actually it's unclear what you wish to get, but you misunderstand the basics.
[edited to clarify users question how to output something to the screen]
I think the easiest way is to use require i another file.
require('login.php');
function get_value()
{
return get_value;
}
I have several functions in a class that return saveHTML(). After I echo more than one function in the class saveHTML(), it repeats some of the HTML. I initially solved this by doing saveHTML($node) but that doesn't seem to be an option now.
I didn't know saveHTML($domnode) was only available in PHP 5.3.6 and I have no control over the server I uploaded the files to so now I have to make it compatible with PHP 5.2.
For simplicity's sake it and only to show my problem it looks similar to this:
<?php
class HTML
{
private $dom;
function __construct($dom)
{
$this->dom = $dom;
}
public function create_paragraph()
{
$p = $this->dom->createElement('p','Text 1.');
$this->dom->appendChild($p);
return $this->dom->saveHTML();
}
public function create_paragraph2()
{
$p = $this->dom->createElement('p','Text 2.');
$this->dom->appendChild($p);
return $this->dom->saveHTML();
}
}
$dom = new DOMDocument;
$html = new HTML($dom);
?>
<html>
<body>
<?php
echo $html->create_paragraph();
echo $html->create_paragraph2();
?>
</body>
</html>
Outputs:
<html>
<body>
<p>Text 1.</p>
<p>Text 1.</p><p>Text 2.</p>
</body>
I have an idea why it's happening but I have no idea how to not make it repeat without saveHTML($domnode). How can I make it work properly with PHP 5.2?
Here's an example of what I want to be able to do:
http://codepad.viper-7.com/o61DdJ
What I do, is just save the node as XML. There are a few differences in the syntax, but it's good enough for most uses:
return $dom->saveXml($node);
You have return $this->dom->saveHTML(); twice in your class ( as far as I know you don't have to return it inside the class anywhere unless it is a private function.
If you take return $this->dom->saveHTML(); out of createparagraph() it will echo without returning. It's a DOM thing as far as I know but am new to this like you.