I am relatively new to php. I have a function to get all subjects by tableName. I also have a function where I am trying to get all pages where the subject_id (from pages table) matches the subject tables id.
Here are the error's and output:
PDOStatement Object ( [queryString] => SELECT * FROM subjects ORDER BY id ASC )
Array ( [0] => Array ( [id] => 1 [0] => 1 [menu_name] => About Us [1] => About Us [position] => 1 [2] => 1 [visible] => 1 [3] => 1 ) [1] => Array ( [id] => 2 [0] => 2 [menu_name] => Products [1] => Products [position] => 2 etc etc...
Notice: Undefined index: id in /Users/aaronhappe/Sites/php/CMS/includes/db.php on line 39
Fatal error: Call to a member function rowCount() on a non-object in /Users/aaronhappe/Sites/php/CMS/includes/db.php on line 41
And here is the code:
<?php
// controller file
include '../admin-head-includes.php';
$subjects = getAll('subjects', $conn);
$subjectId = $subjects->fetchAll();
print_r($subjects);
echo "<br>";
echo "<br>";
print_r($subjectId);
$pages = getAllLinkedId('pages', $subjectId, $conn);
view('manage-content', array(
'subjects' => $subjects,
'pages' => $pages,
));
// from my db functions file
function getAllLinkedId($tableName, $tableName2, $conn) {
try {
$result = $conn->query("SELECT * FROM $tableName WHERE subject_id = {$tableName2['id']} ORDER BY id ASC");
return ($result->rowCount() > 0)
? $result
: false;
} catch (Exception $e) {
return false;
}
<!-- standard functions file -->
<?php function view($path, $data = null) {
if ($data) {
extract($data);
}
$path = $path . '.views.php';
include "views/$path";
}?>
If I pass $subjects[0] into my getAllLinkedId function, it solves the problem of the Array wrapping other arrays. However, what I am wanting is to spit out, for each subject, the corresponding page. Not just the pages which correspond to one single subject, but which respond to all subjects.
This is my view:
<div class="subjects">
<ul>
<?php
foreach ($subjects as $subject) {?>
<li>
<?=$subject['menu_name'];?>
</li>
<ul>
<?php foreach ($pages as $page) {?>
<?=$page['menu_name']?>
<?php }?>
</ul>
<?php }?>
</ul>
</div>
First problem:
Notice: Undefined index: id in ...
the index id in array $tableName2 is not set, check if is set
Second problem:
Fatal error: Call to a member function rowCount() on a non-object ..
$conn->query() on fails return a non-object, check if $result is a object
In your code:
function getAllLinkedId($tableName, $tableName2, $conn) {
// check if index id is set
if( !isset($tableName2['id']) )
return false;
try {
$result = $conn->query("SELECT * FROM $tableName WHERE subject_id = {$tableName2['id']} ORDER BY id ASC");
// check if $result is object
if( !is_object($result) )
return false;
return ($result->rowCount() > 0) ? $result : false;
} catch (Exception $e) {
return false;
}
}
I was way off base on this. But I have figured it out. I am posting my solution to close this.
<?php
// controller file
include '../admin-head-includes.php';
$subjects = getAll('subjects', $conn);
$pages = getAll('pages', $conn);
$subjects = $subjects->fetchAll();
$pages = $pages->fetchAll();
view('manage-content', array(
'subjects' => $subjects,
'pages' => $pages,
));
<!-- what my view function does -->
<?php function view($path, $data = null) {
if ($data) {
extract($data);
}
$path = $path . '.views.php';
include "views/$path";
}?>
<!-- view -->
<div class="subjects">
<ul>
<?php
foreach ($subjects as $subject) {?>
<li>
<?=$subject['menu_name'];?>
<ul>
<li>
<?php foreach ($pages as $page) {?>
<ul>
<li>
<?php
if ($page['subject_id'] == $subject['id']) {
echo $page['menu_name'];
}
?>
</li>
</ul>
<?php }?>
</li>
</ul>
<?php }?>
</li>
</div>
</ul>
Related
I have a problem to find a way to get the MySQL-Result returned into an array which contains the data from the statement for every row and column.
controller.class.php:
class Controller {
private $template;
private $view;
private $data;
public function __construct() {
$this->view = new View();
$this->data = new Model();
}
public function display() {
$this->view->setTemplate();
$this->view->setContent("title", "Songs");
$this->view->setContent("content", $this->data->getAllDataFromSongs());
$this->view->setContent("footer", "© My name is Jeff\n");
return $this->view->parseTemplate();
}
}
model.class.php:
class Model {
public $db_connection = null;
public function __construct() {
$this->openDatabaseConnection();
}
private function openDatabaseConnection() {
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($this->db_connection->connect_error) {
die('Connect Error (' . $this->db_connection->connect_errno . ') '
. $this->db_connection->connect_error);
}
}
public function getAllDataFromSongs() {
$query = "SELECT * FROM songs";
$row_content = array();
if ($result = $this->db_connection->query($query)){
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
array_push($row_content, $row['id']);
array_push($row_content, $row['artist']);
array_push($row_content, $row['song']);
array_push($row_content, $row['year']);
}
$result->free();
return $row_content;
}
else
echo 'No results';
}
}
view.class.php:
class View {
private $path = 'templates';
private $template;
private $content = array();
public function setContent($key, $value){
$this->content[$key] = $value;
}
public function setTemplate($template = 'default') {
$this->template = $this->path . DIRECTORY_SEPARATOR . $template . '.tpl.php';
}
public function parseTemplate() {
if (file_exists($this->template)) {
ob_start();
require_once('templates/header.tpl.php');
include_once $this->template;
require_once('templates/footer.tpl.php');
$output = ob_get_contents();
ob_end_clean();
return $output;
}
else{
return "Can't find ".$this->template." Template";
}
}
}
default.tpl.php:
<table>
<tr>
<th>ID</th>
<th>artist</th>
<th>song</th>
<th>year</th>
</tr>
<tr>
<?php
foreach ($this->content['content'] as $con){
echo '<td>'. $con . '</td>';
}
?>
</tr>
</table>
<br>
<?php echo $this->content['footer']; ?>
It's not the entire Code, but it should show you what I'm trying.
The problem which I have now, is that the result from getAllDataFromSongs() is an Array with all Datas in behind each other. I can't separate them in a table.
This is the output:
Array (
[0] => 1 [1] => Artist 1 [2] => Song 1 [3] => Year 1
[4] => 2 [5] => Artist 2 [6] => Song 2 [7] => Year 2
[8] => 3 [9] => Artist 3 [10] => Song 3 [11] => Year 3
[12] => 4 [13] => Artist 4 [14] => Song 4 [15] => Year 4
[16] => 5 [17] => Artist 5[18] => Song 5 [19] => Year 5
)
ID artist song year
1 Artist 1Song 1Year 12Artist 2Song 2Year 2 3Artist 3Song 3Year 3...
I hope you can relate what I'm trying to explain..
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
array_push($row_content, $row['id']);
array_push($row_content, $row['artist']);
array_push($row_content, $row['song']);
array_push($row_content, $row['year']);
}
Your problem here is that you are creating a new array element for each column, so in the end you will have them all one after the other, one the same level.
Either create a temporary array first, and then assign that (so that you get rows of columns),
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$temp = [];
array_push($temp, $row['id']);
array_push($temp, $row['artist']);
array_push($temp, $row['song']);
array_push($temp, $row['year']);
array_push($row_content, $temp);
}
Or, assign just the full row array directly:
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
array_push($row_content, $row);
// $row_content[] = $row; // same thing
}
If you get additional columns from your SELECT statement that you don’t want in here, then you should name the columns directly in the SELECT statement, instead of selecting *.)
Additionally, mysqli_result::fetch_all also exists. That function puts all rows in the result set in an array in one go - so you could do away with the while loop completely.
Currently working with a php project in which I connect to a database in phpmyadmin. I'm currently implementing my one to many relationship and on one of my forms there is a drop down list with the list of categorys(foreign key) that a product in my database can have, however when I check the post array, and the array that contains all the values for the insert query everything is there except the foreign key.
Drop down list and array of values:
<select name="Category_ID">
<?php
foreach ($category as $cat) {
echo '<option value="' . $cat['ID'] . '">' . $cat['ID'] . '</option>';
}
?>
</select>
Array (
[authorName] => Hiroshi Sakurazaka
[bookName] => All You Need Is Kill
[costPrice] => 59
[sellPrice] => 99
[productCatID] => )
Could not insert book
Heres the file that converts the data in the formdata array into an object:
<?php
require_once 'product.php'; //Connecting to the product class
require_once 'Classes/productTable.php'; //Connecting to the TableGateway
require_once 'Classes/Connection.php'; //Connecting to the Connection class
require_once 'validateProduct.php';//Connecting to the product validation
require_once 'utils/functions.php';
//start_session();
//
//if (!is_logged_in()) {
// header("Location: login_form.php");
//}
echo '<pre>';
print_r($_POST);
echo '</pre>';
$formdata = array();
$errors = array();
validate($formdata, $errors);
if (empty($errors)) {
$AuthorName = $formdata['AuthorName'];
$BookName = $formdata['BookName'];
$costPrice = $formdata['CostPrice'];
$sellPrice = $formdata['sellPrice'];
$productCatID = $formdata['productCatID'];
echo '<pre>';
print_r($formdata);
echo 'Form Data array';
echo '</pre>';
$connection = Connection::getInstance();
$gateway = new productTable($connection);
$id = $gateway->insert($AuthorName, $BookName, $costPrice, $sellPrice, $productCatID);
header('Location: viewProducts.php');
}
else {
require 'createProductForm.php';
}
Heres the function in the table gateway that inserts the object into the database:
> public function insert($authorName, $bookName, $costPrice, $sellPrice,
> $productCatID) {
> $sql = "INSERT INTO "
> . "`product`(`AuthorName`, `BookName`, `CostPrice`, `sellPrice`, `productCatID`)"
> . " VALUES (:authorName,:bookName,:costPrice,:sellPrice,:productCatID)";
> $statement = $this->connection->prepare($sql);
> $params = array(
> "authorName" => $authorName,
> "bookName" => $bookName,
> "costPrice" => $costPrice,
> "sellPrice" => $sellPrice,
> "productCatID" => $productCatID
> );
> print_r($params);
> $status = $statement->execute($params);
>
> if (!$status) {
> die("Could not insert book");
> }
>
> $id = $this->connection->lastInsertId();
>
> return $id; }
can somebody please tell me what I'm missing?
Your select has the name of Category_ID not productCatID. If you expecting GET/POST data coming in under productCatID you need to name your select productCatID.
Solved my problem finally, so I'll post how I did it. For debuging my code and to see what values were being passed into the $POST array and the $formdata array, I used print_r to post each array if there was a problem and heres what I got:
$POST Array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[productCatID] => 4
[createProduct] => Create Product
)
form data array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[ProductCatID] =>
)
As you can see the $POST array was getting the value from the drop down list just fine, it was the form data array that was the issue. Embarrassingly the issue was just a simple typo error that was quickly resolved in my validation script.
With foreach you have to explicitly request access to the key, so if you don't, you'll only get the array values.
Just do this to debug (outside of the <select>):
foreach($category as $key=>$cat){
var_dump($cat['ID'], $cat, $key);
}
And I think you'll see where the actual data you need is.
(also, you seem to be running without strict errors and notices on, which is crucial for debugging and might show you some notices when array keys you try to access don't exist)
Am using following code to get values for SQL from specific id
include 'classes/connection.class.php';
include 'classes/news.class.php';
$connection = new Connection('localhost', '1video', 'sanoj', '123456');
$news = new News($connection->getDb());
$id=$_GET['name'];
try {
print_r($news->get($id));
and it works
RESULT
Array ( [id] => 103 [title] => bkjbjkuk [location] => 1video.com_81e81be69867c77aea1b9f630c4cf482.mp4 [thumb] => 1video.com_81e81be69867c77aea1b9f630c4cf482.jpg [views] => 1 [likes] => 1 [uploader] => lawrence [added_on] => 19-Feb-16 [tags] => hhuhuhuo [duration] => [comments] => [shortstory] => hihouihohoh )
but i need to echo result in specific location but doesn't works
Method 1
include 'classes/connection.class.php';
include 'classes/news.class.php';
$connection = new Connection('localhost', '1video', 'sanoj', '123456');
$news = new News($connection->getDb());
$id = $_GET['name'];
try {
print_r($news->get($id));
foreach ($news->result() as $row) {
$news= $row->title;
?>
<h3><?php echo $vidid ?></h3>
Fatal error: Call to undefined method News::result()
can someone guide me how do i echo array() in various location
class news
class News {
private $db;
private $newsByPage = 5;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function get($id)
{
$q = $this->db->prepare("SELECT * FROM videos WHERE id = :id");
$q->bindValue(":id", $id, PDO::PARAM_INT);
if(!$q->execute())
{
$errors = $q->errorInfo();
throw new Exception("Error while getting a news (".$errors[2].").");
}
else
{
if($res = $q->fetch(PDO::FETCH_ASSOC)){
return $res;
}else{
throw new Exception("No match for id(".$id.").");
}}
$q->closeCursor();
}
}
It should be like:
try {
$myNews = $news->get($_GET['name']);
echo $myNews['title'];
} // -------
I need to echo out a variable value in the CodeIgniter view file. But when I run the site with...
<?php echo $highcharts; ?>
...on line 108, in the view, it gives an error. Please help me to echo out the value, so I can use it in HighCharts.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: highcharts
Filename: reports/bqt_daily_income_view.php
Line Number: 108
This is my Controller:
function bqt_daily_income() {
$json_data = array();
$query = $this->db->query("SELECT time_stamp, SUM(paid) AS income FROM payments WHERE type = 'Banquet Reservation' GROUP BY time_stamp ORDER BY time_stamp ASC LIMIT 30");
if ($query->num_rows() > 0) {
foreach($query->result_array() as $row) {
$json_data['data'][] = (int) $row['income'];
}
}
$highcharts = json_encode($json_data);
//return $json_data;
//print_r($json_data); // Array ( [data] => Array ( [0] => 1700 [1] => 5000 ) )
//print_r($highcharts); // {"data":[1700,5000]}
$this->load->view('reports/bqt_daily_income_view', $highcharts);
Try like:
$this->load->view('reports/bqt_daily_income_view', array('highcharts' => $highcharts));
In view file:
echo $highcharts;
Alternative post method:
$this->data['highcharts'] = json_encode($json_data);
$this->data['other'] = "bla bla bla";
$this->load->view('reports/bqt_daily_income_view', $this->data);
In view file:
echo $highcharts;
echo $other;
I think you need:
$data['highcharts'] = json_encode($json_data);
$this->load->view('reports/bqt_daily_income_view', $data);
You are supposed to pass the array of data to the view and the keys of array will become the the variables accessible in views
function bqt_daily_income() {
$json_data = array();
$query = $this->db->query("SELECT time_stamp, SUM(paid) AS income FROM payments WHERE type = 'Banquet Reservation' GROUP BY time_stamp ORDER BY time_stamp ASC LIMIT 30");
if ($query->num_rows() > 0) {
foreach($query->result_array() as $row) {
$json_data['data'][] = (int) $row['income'];
}
}
$highcharts['highcharts'] = json_encode($json_data);
//return $json_data;
//print_r($json_data); // Array ( [data] => Array ( [0] => 1700 [1] => 5000 ) )
//print_r($highcharts); // {"data":[1700,5000]}
$this->load->view('reports/bqt_daily_income_view', $highcharts);
}
in view
<?php echo print_r(json_decode($highcharts)); ?>
i have mysql table (exe_categories)
| id, title, parent_id, extension |
`<ul>
<li>Parentcat</li>
<ul>
<li>ParentSub</li>
<li>ParentSub</li>
<li>ParentSub</li>
</ul>
<li>Parentcat</li>
<ul>
<li>ParentSub</li>
<li>ParentSub</li>
<li>ParentSub</li>
</ul>
</ul>`
and i want to show a nested category list and subcategory using 2 arguments
first-argument is (parent_id) (0)
AND second argument is (extension) 'com_extension'
I want to show up the nested categories titles and path for the 2 arguments above
i have used this code below and works fine but i cant have another argument for extension argument.
<?php
function query($parent_id) { //function to run a query
$query = mysql_query ( "SELECT * FROM exe_categories WHERE parent_id=$parent_id");
return $query;
}
function has_child($query) { //This function checks if the menus has childs or not
$rows = mysql_num_rows ( $query );
if ($rows > 0) {
return true;
} else {
return false;
}
}
function fetch_menu($query) {
while ( $result = mysql_fetch_array ( $query ) ) {
$id = $result ['id'];
$extension = $result['com_bids'];
$title = $result ['title'];
$menu_link = $result ['menu_link'];
echo "<li><a href='{$menu_link}'><span>{$title}</span></a>";
if (has_child ( query ( $id ) )) {
echo "<div>";
echo '<ul role="menu" class="fofc">';
fetch_menu ( query ( $id) );
echo "</ul>";
echo "</div>";
}
echo "</li>";
}
}
fetch_menu (query(1)); //call this function with 1 parent id
?>
the code above will fetch list of categories starting from parent_id=0 which works great only that i cant have another rule for my extension column .
any help will be appreciated :)
The Html output is like this
Parentcat
ParentSub
ParentSub
ParentSub
Parentcat
ParentSub
ParentSub
ParentSub