I'm working on calling scripts from the database if they match a function that's included.
Right here is what I'm using now:
3 Functions to Call Page Content:
public function ViewPageDetails() {
global $db;
$query = <<<SQL
SELECT title,body
FROM inv_pages
WHERE id = :getid
SQL;
$resource = $db->db->prepare( $query );
$resource->execute( array (
':getid' => $_GET['id'],
));
foreach($resource as $row){
$this->title = $row['title'];
$this->body = $row['body'];
}
}
public function ViewPageTitle() {
self::ViewPageDetails();
return $this->title;
}
public function ViewPageBody() {
self::ViewPageDetails();
if( is_callable($this->body) )
$this->body();
else {
echo $this->body;
}
}
I thought that that would work to call the function, but instead throws the error:
Fatal error: Call to undefined method pages::body()
Now a function I do have that would work on the flip side is
public function testcall() {
global $db;
$query = <<<SQL
SELECT body
FROM inv_pages
WHERE id = :getid
SQL;
$resource = $db->db->prepare( $query );
$resource->execute( array (
':getid' => $_GET['id'],
));
foreach($resource as $row){
if( is_callable($row['body']) )
$row['body']();
else {
echo $row['body'];
}
}
}
So $this->body() is an illegal method, but $row['body']() is perfectly fine to call. If anyone knows a way to use $this->body() instead of $row['body']() any input would be appreciated. If you need clarification please ask. I think I put the issue in pretty well however.
Related
Ok this should be fairly simple.
I have a table which contains content of 3 different textboxes the method inside my class should get the content to insert into textboxes.
Example TextBoxes (TextArea) where content should be entered.
My Method
public function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$data[] = array('Low' => $box['boxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $data;
}//function
Here is my table (image below) so data / content from table should get inserted into the textboxes.
So when I do a test on content.php where I call the class method as such:
require_once('../classes/class.content.php');
$boxes = new Contents();
$boxes->LoadBoxes();
var_dump($boxes);
I get the following back:
Problem
As can be seen the array keys get returned however the data from database is not matched to array keys or returned by the method...I am stumped and have no idea what I am doing wrong here?
Any suggestions where I am going wrong? Could it be that I am not connecting to database correctly?
However if it was a database connection error I believe I would have received an error
Please keep in mind im a student and still learning.
UPDATE
Connection Schema
class Db {
private static $instance = NULL;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!isset(self::$instance)) {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
self::$instance = new PDO('mysql:host=localhost;dbname=beta', 'root', '', $pdo_options);
}
return self::$instance;
}
}
UPDATE 2
I just did the following on a test.php page which returned correct results.
require('connection.php');
function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$box[] = array('Low' => $box['BoxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $box;
}//function
print_r(LoadBoxes());
?>
2 issues primary issues;
You're returning $data from the class but not populating a variable with the returned array.
You are var dumping the object itself.
This should work;
require_once('../classes/class.content.php');
$boxes = new Contents();
$data = $boxes->LoadBoxes();
var_dump($data);
I'm trying to retrieve data from my Wordpress database using an Angular factory. Using ng-click="updateCommentsById(v.id.videoId)" I call the following function:
$scope.updateCommentsById = function(id) {
commentRepository.query(({videoId: id}), function (data) {
$scope.comments = data;
});
}
That corresponds to the following factory definition:
angular.module("app")
.factory("commentRepository",
function($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php/:videoId",
{
videoId:"#id"
});
});
The problem is how to get the videoId parameter into my PHP function inside get_comments.php:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
echo $id;
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
echo wp_json_encode($result);
}
}
get_comments_by_id(videoId);
EDIT:
Turns out the get_results() method doesn't allow variables inside SQL statements, I should use prepare() (safer anyway) instead. I also changed the request URL. The new code becomes:
angular.module("app")
.factory("commentRepository",
function ($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php?video_id=:videoId");
});
and PHP:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
var_dump($id);
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->prepare("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
var_dump($result);
$result_array = array();
if($result){
foreach($result_array as $r){
$result_array[] = $r;
}
}
var_dump($result_array);
echo json_encode($result_array);
}
}
get_comments_by_id($_GET["video_id"]);
However the var_dumps show that the id gets passed correctly, only the prepare() doesn't actually execute anything. Should I wrap that in a get_results?
You could extract it from the URI:
//$args is an array of every part separated by `/` (ignoring the query string)
$args = explode('/',strtok(trim($_SERVER['REQUEST_URI'],'/'),'?'));
//the last element is the video id
$video_id = end($args);
Live demo
Got it to work using the answers (including those now removed) and comments. The function inside my Angular controller code:
$scope.updateCommentsById = function(id) {
commentRepository.query(({videoId: id}), function (data) {
$scope.comments = data;
});
}
Repository:
angular.module("app")
.factory("commentRepository",
function ($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php?video_id=:videoId");
});
get_comments.php:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$sql = $wpdb->prepare("SELECT * FROM `analyser_posts` WHERE `video_id` = '$id'", OBJECT);
$result = $wpdb->get_results($sql);
echo json_encode($result);
}
}
get_comments_by_id($_GET["video_id"]);
this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.
I'm trying to implement these two functions in a separate file functions.php and call it in index.php
function is_field($column, $table, $requested) {
$is_field_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($column, $table, $requested) {
$get_content_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$get_content_result = $mysqli->query($get_content_query);
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content_content = $get_content_row["content"];
$get_content_result->close();
return $content;
}
I have tried it over and over again and I have no idea why it wont work. The first one is returning 1 for valid or 0 for invalid. The second retrieves the content from a specific cell in the MySQL table. Any help would be much appreciated.
You're using $mysqli inside the function, but you never pass the MySQLi resource itself. Consider writing your function like this:
function is_field($mysqli, $column, $table, $requested) {
Or, create a class that takes a MySQLi resource and reference it with $this->mysqli inside your function.
Also, code like this may be another issue:
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
You're not checking whether $is_field_result is false; therefore, the next statement causes a fatal error, because a property can't be fetched from something that's not an object.
if (($is_field_result = $mysqli->query($is_field_query)) === false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
It turns out the reason it was not working was I needed to add an extra field into the function to accept the passing of $mysqli from the connection.
function is_field($mysqli, $column, $table, $requested) {
$is_field_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($is_field_result = $mysqli->query($is_field_query)) == false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($mysqli, $column, $table, $requested) {
$get_content_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($get_content_result = $mysqli->query($get_content_query)) == false) {
die($mysqli->error);
}
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content = $get_content_row["content"];
$get_content_result->close();
return $get_content;
}
Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.