So I'm training in MVC and extending functionality from a tutorial. I'm not getting any echos after "SUBMITTED: " with each of the values for binding. I double-checked and ran the query in PHPMyAdmin and it's inserting fine. The page is just bombing as soon as I call $this->query and I don't understand why. In the add function that's bombing, I'm trying to add a List Item. List Items (like Vacuum) belong to a List (like Cleaning). The class where I add Lists is EXACTLY the same and works perfectly.
public function add(){
// Sanitize POST
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// show the List name
$lModel = new ListModel();
$lName = $lModel->getListTitle($this->listID);
if($post['submit']){
echo "SUBMITTED: Name: " . $post['name'] . " ID: " . $this->listID . " And 1 for Position<br>";
// Insert
$this->query("INSERT into list_item (list_id, name, position) VALUES (:list_id, :name, :position)");
echo "After query<br>";
$this->bind(':list_id', $this->listID);
$this->bind(':name', $post['name']);
$this->bind(':position', 1);
echo "After binding<br>";
//Verify
$this->execute();
echo "Execute?<br>";
if($this->lastInsertId()){
echo "Insert ID " . $this->lastInsertId();
//redirect
//header("Location: " .ROOT_URL."listItems/index/" . $this->listID);
}else{
echo "Didn't insert<br>";
Messages::setMsg('Failed to insert list','error');
}
}
//echo "lName: $lName";
return $lName;
}
}
Here is the entire class for your viewing pleasure.
<?php
class ListItemModel extends Model{
public $listID;
public function __construct($id){
$this->listID = $id;
}
public function Index(){
return "some data";
$this->query("SELECT * FROM list_item WHERE list_id = :list_id ORDER BY create_dt DESC");
$this->bind(':list_id', $this->listID);
$rows = $this->resultSet();
return $rows;
}
public function add(){
// Sanitize POST
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// show the List name
$lModel = new ListModel();
$lName = $lModel->getListTitle($this->listID);
if($post['submit']){
echo "SUBMITTED: Name: " . $post['name'] . " ID: " . $this->listID . " And 1 for Position<br>";
// Insert
$this->query("INSERT into list_item (list_id, name, position) VALUES (:list_id, :name, :position)");
echo "After query<br>";
$this->bind(':list_id', $this->listID);
$this->bind(':name', $post['name']);
$this->bind(':position', 1);
echo "After binding<br>";
//Verify
$this->execute();
echo "Execute?<br>";
if($this->lastInsertId()){
echo "Insert ID " . $this->lastInsertId();
//redirect
//header("Location: " .ROOT_URL."listItems/index/" . $this->listID);
}else{
echo "Didn't insert<br>";
Messages::setMsg('Failed to insert list','error');
}
}
//echo "lName: $lName";
return $lName;
}
}
?>
And here's the query function in Model as requested
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
I figured it out!!!
Because I was using the constructor in ListItemModel (which extends Model) to pass in the $id for the list, I needed parent::__construct().
Thanks, everyone!
Related
I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.
MySQl tables are below:
In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:
function insert() {
function adduserdetails($con, $accountId, $name, $contact) {
$query = "insert into userdetails(accountId,name,contact)
values('$accountId','$name','$contact')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query);
if ($insertResult) {
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
} else {
echo " Error !";
echo "{$query}";
//header('Location: post.php');
}
}
}
if ($con->query($query) === TRUE) {
$last_id = $con->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $query . "<br>" . $con->error;
}
function adduseremployment($con,$last_id,$occupationMain,$comapny){
$query1 = "insert into useremployment(userId,Occupation,company)
values('$last_id',$occupationMain','$comapny')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query1);
if($insertResult){
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
}
else {
echo " Error !";
echo "{$query1}";
//header('Location: post.php');
}
}
You have vertical table.
Check below code,
Be remember to prepare statement.
<?php
function addUser(){
// parent table.
$queryParent = ''; // Your userdetails table insert query
$insertResult = mysqli_query($con, $queryParent);
$userId = mysqli_insert_id($con); // This is your last inserted userId.
// child table.
$queryChild = ''; // Your useremployment table insert query with userId.
$insertResult = mysqli_query($con, $queryChild);
}
?>
your Query is wrong, please check this,
$query1 = "insert into useremployment(userId,occupation,company)
values('$last_id',$occupationMain','$comapny')";
you have to store record on userId as a refrence not to "accountID".
hope it helps,
In second insert you are using wrong column name (userID and not accountID)
$query1 = "insert into useremployment(userID,Occupation,company)
^^^^^^ here
values('$last_id',$occupationMain','$comapny')";
and in function signature and body you have comapny (could be you want company)
I've been trying for the last six hours to figure out what is wrong with my code. My page keeps outputting 'Catchable fatal error: Object of class PDOStatement could not be converted to string.' I don't know why! I looked at previous assignments, tried googling the type of error, and nothing has changed the output. I want to display my menu items by category id. Here's my code.
class Menu {
public $conn;
public function __construct() {
$db = new Database();
$this->conn = $db->conn;
}
public function __destruct() {
$this-> conn = null;
}
/* Get function */
public function __get($name) {
return $this->$name;
} // End get function
public function __set($name, $value){
$this->$name=$value;
}
public function menu_items($category_id = 0){
try {
$sql = "SELECT item_id, category, category_id, display_order, item_name, item_image, item_description, item_cost FROM menu_items WHERE category_id = $category_id";
$result = $this->conn->query($sql);
return $result;
}
catch (PDOException $e){
echo 'Error: ' . $e->getMessage();
exit();
}
}
}
UPDATE: Here is where everything is outputting. Could there be something wrong with this code instead?
include(ABSOLUTE_PATH . 'classes/menu.class.php');
// Create Menu object
$menu = new Menu();
$menu_categories = $menu->menu_categories();
include(ABSOLUTE_PATH . '_includes/header.inc.php');
?>
<hr />
<h2><?=$page?></h2>
<?
while($item = $menu_categories->fetch(PDO::FETCH_OBJ)) {
// Retrieve menu items
$menu_items = $menu->menu_items($menu_categories);
$item_count = $menu_items->rowCount();
if($item_count > 0) {
echo '<h3>' . $item->category . '</h3>';
?>
<table id="menu_items" class="listing">
<?
// Loop through menu records
while($item = $menu_items->fetch(PDO::FETCH_OBJ)) {
echo "\t<tr>\n";
echo "\t\t" . '<td class="item"><h4>' . $item->item_name . '</h4><p>' . $item->item_description . '</p></td>' . "\n";
echo "\t\t" . '<td class="price">$' . $item->item_cost . '</td>' . "\n";
echo "\t\t" . '<td class="image"><img src="' . URL_ROOT . '_assets/images/menu/' . $item->item_image . '" alt="' . $item->item_name . '" /></td>' . "\n";
echo "\t</tr>\n";
}
?>
</table>
<?
}}
?>
<hr />
<?
include(ABSOLUTE_PATH . '_includes/footer.inc.php');
?>
Aha
here is your problem:
while($item = $menu_categories->fetch(PDO::FETCH_OBJ)) {
// Retrieve menu items
$menu_items = $menu->menu_items($menu_categories); //<--Error
$item_count = $menu_items->rowCount();
You should call:
$menu_items = $menu->menu_items($item->id);
You are passing $menu_categories (a PDOStatement) into menu_items(), then trying to use it as a string directly in your query. That is where the error is actually occurring.
A good practice that would have made this error more apparent is to type check query parameters. So in menu_items():
public function menu_items($category_id = 0){
if(!is_numeric($category_id)) {
//Do something better here, but just for example
echo "Error";
return false;
}
try {
$sql = "SELECT item_id, category, category_id, display_order, item_name, item_image, item_description, item_cost FROM menu_items WHERE category_id = $category_id";
$result = $this->conn->query($sql);
return $result;
...
I am a total noob with performing OOP, and am currently looking to refactor a procedural PHP project. Currently, I am having issues trying to simply display my results from a SELECT query--ironically doing an INSERT query made sense instead. This is my Class file:
<?php
class MadLibs {
private $noun;
private $verb;
private $adverb;
private $adjective;
private $story;
// Getters
public function getNoun() {
return $this->noun;
}
public function getVerb() {
return $this->verb;
}
public function getAdverb() {
return $this->adverb;
}
public function getAdjective() {
return $this->adjective;
}
public function getStory() {
return $this->story;
}
// Setters
public function setNoun($noun) {
$this->noun = $noun;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function setAdverb($adverb) {
$this->adverb = $adverb;
}
public function setAdjective($adjective) {
$this->adjective = $adjective;
}
public function setStory($story) {
$this->story = $story;
}
// Figured this one out
public function insertStoryToDatabase() {
date_default_timezone_set('America/Chicago');
$submit_date = date('Y-m-d' . " " . 'H:i:s');
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$query = "INSERT INTO storyTime (noun, verb, adjective, adverb, createdDate, fullStory) " .
"VALUES ('$this->noun','$this->verb','$this->adjective','$this->adverb','$submit_date','$this->story')";
mysqli_query($dbc,$query)
or die('Error querying database');
mysqli_close($dbc);
}
// method I am having trouble setting up
public function displayAllStories() {
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$result = "SELECT fullStory, createdDate FROM storyTime ORDER BY createdDate DESC";
$display = mysqli_query($dbc,$result)
or die('Error gathering data!');
while ($row = mysqli_fetch_array($display)) {
echo $row['story'] . '<br/>';
}
return $display;
}
}
?>
And this is what I am doing in my other php file:
<?php
require_once('MadLibs.php');
// Instantiating instance of MadLibs()
$foo = new MadLibs();
// Playing around to see ensure getters/setters were correct
$foo->setNoun('Bob');
$foo->setVerb('jumps');
$foo->setAdverb('quietly');
$foo->setAdjective('ugly');
$foo->setStory("The " . $foo->getNoun() . " always " . $foo->getVerb() . " at the "
. $foo->getAdjective() . " strangers " . $foo->getAdverb() . ".");
echo $foo->getNoun();
echo '<br />';
echo $foo->getVerb();
echo '<br />';
echo $foo->getAdverb();
echo '<br />';
echo $foo->getAdjective();
echo '<br />';
echo $foo->getStory();
$foo->insertStoryToDatabase();
$foo->displayAllStories();
?>
I'm sure it's something simple, but for the life of me I can't figure out what I'm doing wrong.
Any and all feedback is most appreciated!
You trying to display wrong variable in displayAllStories() function .
'echo $row['story']should be change to$row['fullStory'];` or change your query to
SELECT fullStory as story, createdDate FROM storyTime ORDER BY createdDate DESC
I would like to ask how could I display data from php class in HTML table I've tried echo theme out with HTML tags but for some reason my code doesn't recognize html tags.
public function getDataUser()
{
$sql = "SELECT ID, USERNAME , PASSWORD , EMAIL , PERMISSION_LEVEL FROM USERS";
$this->_data = $this->_connection->query($sql);
while ($row = $this->_data->fetch_assoc()) {
echo $row["ID"] .$row["USERNAME"] . $row["PASSWORD"]. $row["EMAIL"] . $row["PERMISSION_LEVEL"];
echo"<br />";
}
return $this->_data;
}
this br tag doesn't work.
As you return the data, maybe you want only to test the received data:
then you can use print_r (between <pre> tags):
public function getDataUser()
{
$sql = "SELECT ID, USERNAME , PASSWORD , EMAIL , PERMISSION_LEVEL FROM USERS";
$this->_data = $this->_connection->query($sql);
while ($row = $this->_data->fetch_assoc()) {
echo "<pre>";
print_r($row);
echo "</pre>";
}
return $this->_data;
}
Try this one
public function getDataUser()
{
$sql = "SELECT ID,USERNAME,PASSWORD,EMAIL,PERMISSION_LEVEL FROM USERS";
$this->_data = $this->_connection->query($sql);
while ($row = $this->_data->fetch_assoc()) {
//do print_r() to check wether data is coming or not
echo '<pre>';
print_r($row);
echo '</pre>';
//or you can print directly value by $row['ID']." ".$row['USERNAME'] by this way
}
return $this->_data;
}
echo $row["ID"] .$row["USERNAME"] . $row["PASSWORD"]. $row["EMAIL"] . row["PERMISSION_LEVEL"]. " <br>";
i've been creating functions for too long without taking my code to 'classes'.
I learn well through example and I just wanted to convert this simple function into a class so I can compare something I know with something I don't...
Take the following function:
function affiliateName($affiliateID) {
$sql = 'SELECT * FROM affiliates WHERE uID="' . $affiliateID . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$affiliateName = $row['firstName'] . ' ' . $row['lastName'];
return $affiliateName;
}
And how would I make that a class?
<?php
class AffiliateModel
{
public function first($id)
{
$sql = 'SELECT *, CONCAT(firstName, ' ', lastName) AS qualifiedName FROM affiliates WHERE uID="' . $id . '" LIMIT 1';
$res = mysql_query($sql);
return mysql_fetch_object($res);
}
}
$model = new AffiliateModel();
$a = $model->first($id);
echo $a->qualifiedName;
?>
Hope it helps
<?php
class affiliate{
// fields or properties
public $name = '';
public $id = 0;
// constructor
public function affiliate($id = 0){
$this->set_ID($id);
}
// methods
public function set_ID($id){
return $this->id = $id;
}
public function get_Name(){
if($this->name != ""){
$sql = 'SELECT * FROM affiliates WHERE uID="' . $this->id . '" ';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
return $this->name = $row['firstName'] . ' ' . $row['lastName'];
}else{
return $this->name;
}
}
}
// Example:
$currentAffiliate = new affiliate(153);
echo $currentAffiliate->name;
?>
I prefer the following design as it is the simplest to use:
class affiliates {
static function load($id) {
return new self(intval($id));
}
private function __construct($id) {
$query = "SELECT * FROM affiliates WHERE id = " . intval($id);
$result = mysql_query($query);
// TODO: make sure query worked
foreach(mysql_fetch_assoc($result) as $field => $value)
$this->$field = $value;
}
// composite fields - made by combining and/or re-formatting other fields
function qualifiedName() {
return $this->firstName . ' ' . $this->lastName;
}
function properName() {
return $this->lastName . ', ' . $this->firstName;
}
}
$a = affiliates::load(22);
// all db fields are available as properties:
echo $a->id; // 22
echo $a->firstName; // Fred
echo $a->lastName; // Smith
// composite fields are methods
echo $a->qualifiedName(); // Fred Smith
echo $a->properName(); // Smith, Fred
// to get a single field from a particular person
echo affiliates::load(72)->qualifiedName();