I'm having a problem with some PHP / MySQL code.
I need a view called gameview for a Star Wars game I'm writing.
If I created the view in MySQL then the code runs perfectly. However, I need this view to be dropped every time the game starts. So if I start without the view "gameview" present in the DB, the page cannot be displayed due to the view not existing. However, the moment I manually add the view into MySQL, it works. I can't see why.
Class code
<?php
class gameView
{
protected $Conn;
public function __construct($Conn)
{
$this->Conn = $Conn;
}
public function dropGameView()
{
$drop = "DROP VIEW if EXISTS gameview;";
$stmt = $this->Conn->prepare($drop);
$stmt->execute(array());
}
public function createGameView()
{
$view = "CREATE VIEW gameview AS SELECT id, name, image, quote FROM person;";
$stmt = $this->Conn->prepare($view);
$stmt->execute(array());
}
public function useGameView()
{
$query = "SELECT * from gameview";
$stmt = $this->Conn->prepare($query);
$stmt->execute(array());
$gameView = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $gameView;
}
}
?>
PHP code
<?php
$gameView = new gameView($Conn);
$finalCharacter = $gameView->useGameView();
$smarty->assign('game_view', $finalCharacter);
?>
Well.... stone the crows. I thought this would be too simple to work, but it did!
<?php
$gameView = new gameView($Conn);
$dropGameView = $gameView->dropGameView();
$smarty->assign('drop_gameview', $dropGameView);
$createGameView = $gameView->createGameView();
$smarty->assign('create_gameview', $createGameView);
$finalCharacter = $gameView->useGameView();
$smarty->assign('game_view', $finalCharacter);
?>
Now to crack on and use the view.
Related
Iam currently trying to use my data in my database and insert it into a formular, which has multiple textfields. The formular is in a different php file and when I try to insert the data, nothing happens. Even if I have a blanked website and try to print it out via echo, none of the data inside my database is shown up.
The first file is where I get all my connections and and work with the database (config.php)
public function article_details($id){
global $connection;
$stmt = $connection->prepare("SELECT * FROM `items` WHERE item_name=:id");
$stmt->bindparam(':id', $id);
$stmt->execute();
}
this file is for the redirect when I click on the a tag and the magic happens (view.php)
<?php
$id=$_GET['id'];
include('config.php');
#header("Location: Website.php?page=add_article");
$call = new article();
$call->article_details($id);
foreach ($call as $row)
echo $row['item_name']; ?>
Since its a bigger project with multiple files, I dont want to spamm them all in here. But if you need more information let me know.
You need to return stmt object then call fetch function on it to display data
public function article_details($id){
global $connection;
$stmt = $connection->prepare("SELECT * FROM `items` WHERE item_name=:id");
$stmt->bindparam(':id', $id);
$stmt->execute();
return $stmt;
}
$call = new article();
$stmt = $call->article_details($id);
while ($row = $stmt->fetch()) {
echo $row['item_name']."<br />\n";
}
Your article_details function is not returning anything so you are basically passing null to the foreach loop. I think this will help.
class article {
//...
public function article_details($id){
global $connection;
$stmt = $connection->prepare("SELECT * FROM `items` WHERE item_name=:id");
$stmt->bindparam(':id', $id);
$stmt->execute();
return $stmt;
}
}
Then ...
$id=$_GET['id'];
include('config.php');
//header("Location: Website.php?page=add_article");
$myarticle = new article();
$call = $myarticle->article_details($id);
foreach ($call as $row){
echo $row['item_name'];
}
Hope that helps.
first question here, because i'm stuck since this morning and i don't find a single way to fix my problem.
I'm trying to show every images listed in my DB (DB contains img name, img are stored in local files, each has been send in the same time via an input page).
The current code do not send any errors between thoses parts :
public function findall()
{
require_once ('Classes/ClasseDB.php');
$pdo = Database::connect();
$req = "SELECT IDphoto, nomImage, testCom FROM test";
$stmt = $pdo->query($req);
$CollectionPhotos = array();
while ($ligne = $stmt->fetch())
{
$LaPhoto = new ClasseTest($ligne["testCom"]);
array_push($CollectionPhotos, $LaPhoto);
}
return $CollectionPhotos;
}
public function get_nomImage()
{
return $this->nomImage;
}
And
Image List :
<?php
echo "test1 ";
require_once "Classes/ClasseTest.php";
$laPhoto = new ClasseTest;
$CollectionPhotos = $laPhoto -> findall();
$i = 0;
echo "test2 ";
while ($i < count($CollectionPhotos)){
// here is where it's broken ↓
echo $CollectionPhotos[$i]->get_nomImage(); //don't work :'(
//html <img __ > is removed in order to simplify
echo 'test3 '; //shows every items
$i++;
}
echo "test4 ";
?>
ClasseDB code here as asked :
<?php
class Database {
public static $conn = null;
public static function connect() {
if ( null == self::$conn ) {
try {
self::$conn = new PDO('mysql:host=localhost;dbname=myDB', 'root', '');
self::$conn->query("SET NAMES 'utf8'");
self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$conn;
}
}
?>
Each tests are shown, and 'test3' appears 10 times, so i know my loop repeats enough times.
Nb : this is like what we did in class...
So what is wronnnng, is that a newbie mistake, a misspelling or a bug (my pc has done everything to me so that's also possible) ?
In your SQL query, you select three columns:
SELECT IDphoto, nomImage, testCom FROM test
However, only one of these is actually referenced in your PHP code:
$LaPhoto = new ClasseTest($ligne["testCom"]);
You haven't shown the constructor of ClasseTest, so it's not clear where testCom is stored (if anywhere), but from its name, I suspect it is not in the nomImage property, which is what you later try to retrieve:
public function get_nomImage()
{
return $this->nomImage;
}
That property is presumably supposed to come from the nomImage column in the database, which you're not storing anywhere.
You can help yourself a lot by naming things more carefully and thinking about responsibilities. If you want an object representing a photo, the logical name for it would be Photo, and you would pass all the columns you've selected to its constructor:
$LaPhoto = new Photo($ligne["IDphoto"], $ligne["nomImage"], $ligne["testCom"]);
Your findAll method doesn't belong to a single photo, so you can either put it on a different class, like ChercheurPhoto:
$leChercheurPhoto = new ChercheurPhoto;
$CollectionPhotos = $leChercheurPhoto->findall();
Or, you can use a static method, which is a method on the class, not a particular instance of the class:
$CollectionPhotos = Photo::findall();
What I want is to get and store the last inserted ID, but I am not sure how. The scenario is, after a user add a record he/she will be redirected to a page that will show him/her of the summary of what he/she saved. But I am not sure how I can do that, to retrieved the recently added record.
I have a class which look like this record.php
<?php
class Record {
private $conn;
private $table_name_1 = "name_of_the_table_1";
private $table_name_2 = "name_of_the_table_2";
public $name;
public $age;
public function __construct($db){
$this->conn = $db;
}
function newRecord(){
$query = "INSERT INTO " . $this->table_name_1 . " SET name=:name;
INSERT INTO " . $this->table_name_2 . " SET age=:age";
$stmt = $this->conn->prepare($query);
$this->name=$this->name;
$this->age=$this->age;
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':age', $this->age);
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
?>
now I have another php form that create and add record, the code is something like this add_record.php
<?php
inlude_once 'db.php'
inlude_once 'record.php'
$database = new Database();
$db = $database->getConnection();
$record = new Record($db);
?>
<?php
if($_POST) {
$record->name=$_POST['name'];
$record->age=$_POST['age'];
if(record->record()){
header("Location:{$home_url}view_recently_added_record.php?action=record_saved");
}
else{
echo "Unable to save";
}
}
?>
The idea is to save the query to two different table and the same time automatically record the auto increment ID of table 1 to table 2 so that they have a relationship. I am thinking I can do that if I can store immediately the ID from table 1 and assigned it a variable maybe so it can be automatically saved to table two using a new query or function maybe. Is this possible? does it make sense? and another thing I wanted to display the recently recorded data immediately to the user. Thank you.
You can return $stmt->insert_id or -1 insteaf of boolean in the newRecord function:
function newRecord(){
...
if($stmt->execute()){
return $stmt->insert_id;
}else{
return -1;
}
}
and use the value to redirect like this:
$newrecord = record->newRecord();
if($newrecord != -1) {
header("Location:{$home_url}view_recently_added_record.php?action=record_saved&id=".$newrecord);
}
else{
echo "Unable to save";
}
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 have my main (user visible) file which displays posts, and I need to set-up pagination.
It would be easy if I fetch DB in the same file (but I want to avoid that), that is why I created a seperate (user hidden) file which contains class' which are then called from main file(blog.php):
BLOG.php(simplified):
<?php
require 'core.php';
$posts_b = new Posts_b();
$posts_bx = $posts_b->fetchPosts_b();
foreach($posts_hx as $posts_hy){
echo $posts_hy['title'];
}
?>
core.php(simplified);
class Posts_b extends Core {
public function fetchPosts_b(){
$this->query ("SELECT posts_id, title FROM posts");
//return
return $this->rows();
}
}
This works like a charm, but now I need to do the count within query, which works fine, and which gives me a variable $pages=5 (handled inside class posts_b - in file core.php),
core.php(simplified-with variable);
class Posts_b extends Core {
public function fetchPosts_b(){
$this->query ("SELECT posts_id, title FROM posts");
$pages=5;
//return
return $this->rows();
}
}
Now I need a way to return this variable value to blog.php (the way I return rows())
Please help, anyone,
Thank you...
A function can only have a single return value.
There are ways to get around this though. You can make your return value be an array that contains all of the values you want. For example:
return array("pages"=>$pages, "rows"=>$this->rows());
Then in your code
require 'core.php';
$posts_b = new Posts_b();
$posts_bx = $posts_b->fetchPosts_b();
$pages = $posts_bx["pages"];
foreach($posts_hx["rows"] as $posts_hy){
echo $posts_hy['title'];
}
?>
Or you can adjust a input parameter provided it was supplied as a reference
public function fetchPosts_b(&$numRows){
$this->query ("SELECT posts_id, title FROM posts");
//return
return $this->rows();
}
In your code
require 'core.php';
$posts_b = new Posts_b();
$pages = 0;
$posts_bx = $posts_b->fetchPosts_b(&$pages);
foreach($posts_hx["rows"] as $posts_hy){
echo $posts_hy['title'];
}
?>
Or you can opt to figure out your pagination outside of the fetchPosts_b method.
$posts_bx = $posts_b->fetchPosts_b();
$pages = floor(count($posts_bx)/50);