PHP BD error line 72 - php

The error is Fatal error: Call to undefined method stdClass::retrieve_all_accounts() in /home/mjcrawle/public_html/cit0215/assignment5/onlinebanking/viewaccounts.php on line 72
I am not getting any html errors so I will leave that out.
My php code up to the error is:
<?php
require_once('footer_nav/navigation.inc.php');
require_once('../websiteconfig.inc.php');
require_once('../class/person_class.php');
require_once('../class/database.class.php');
/*Start Session*/
session_start();
$currentMember =unserialize($_session['currentMember']);
/*DataBase*/
$db = new Database;
$conn = $db->connection;
?>
<td width="16"> </td>
<td width="595">
</td>
</tr>
</div>
<h2>Accounts</h2>
</td>
<table id="accounts" summary="Bank Account Balance Information">
<thread>
<tr>
<th>Account Number</th>
<th>Account Balance</th>
</tr>
</thead>
<tbody>
<php?
/*Accounts*/
$currentMember->connection = $conn;
this is where I get the error line 72:
$accounts = $currentMember->retrieve_all_accounts();
/* Loop Though Accounts*/
while($account = mysqli_fetch_assoc($account)) {
/* Retrieve Account Balance*/
$bankaccount = new Bankaccount ($account['BankAccountID']);
$bankaccount->connection = $conn;
$balance = mysqli_fetch_assoc($bankaccount->retrieve_current_balance());
echo '<tr>' . "\n";
echo "\t" . '<td class="account_number">' . $account['BankAccountID'] . '</td>' . "\n";
echo "\t" . '<td class="account_balance">$' . number_format($balance['CurrentBalance'], 2) . '</td>' . "\n";
echo '</tr>' . "\n";
}
/*Closed DataBase*/
mysqli_close($db->connection);
?>

First, you are using this, in your first portion of code :
<php?
/*Accounts*/
$currentMember->connection = $conn;
If you really copy-pasted this, you have a problem here : this is not PHP code.
Instead, you should have :
<?php
/*Accounts*/
$currentMember->connection = $conn;
Note that a PHP opening tag is <?php and not <php?
Then, your $currentMember variable is set this way :
$currentMember =unserialize($_session['currentMember']);
It seems this makes $currentMember just on container, and not an instance of a class that would have a retrieve_all_accounts() method.
So, when trying to call that method :
$accounts = $currentMember->retrieve_all_accounts();
You get a Fatal error, because there is no such method in your $currentMember object.

Related

Want to pass variables in foreach loop to another php file

if (!empty($_SESSION["shopping_cart"])) {
$total = 0;
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
?>
<tr>
<td><?php echo $values["item_name"]; //$GLOBALS['x']= $values["item_name"] $_COOKIE["iname"] = $values["item_name"] ?></td>
<td><?php echo $values["item_quantity"];//$GLOBALS['y']= $values["item_quantity"]//$_SESSION["iquantity"] = $values["item_quantity"]?></td>
<td>₹ <?php echo $values["item_price"]; //$GLOBALS['z']= $values["item_price"]//$_SESSION["iprice"] = $values["item_price"]?></td>
<td>₹ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2); ?></td>
<?php
$menus = array("name"=>$values["item_name"],
"quan"=>$values["item_quantity"],
"price"=>$values["item_price"],
"id"=>$values["item_id"]);
?>
<td><span class="text-danger">Remove</span></td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["item_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">₹ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Confirm" class="btn btn-primary">
</td>
</tr>
</form>
<?php
}
Basically I am trying to create a cafeteria management system using sql, html and php. So I want to insert the items ordered by the user into a table for that I am supposed to pass the variables from a foreach of one php file to another php file.
I want to pass the $values["item_name"], $values["item_quantity"], $values["item_price"] to the other php file to insert their values into a sql table which is below:
<?php
include_once('index.php');
$i_name = ("item_name");
$i_quantity =("item_quantity");
$i_price =("item_price");
$i_id = ("item_id");
/*$i_name = $_SESSION[$menus["name"]];;
$i_quantity =$_SESSION[$menus["quan"]];
$i_price = $_SESSION[$menus["price"]];
$i_id = $_SESSION[$menus["id"]];
*/
session_start();
$un = $_SESSION['username'];
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "cart";
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
} else {
$sql = "INSERT INTO tbl_order (itemname, itemquantity, itemprice, itemid, username) values ('$i_name','$i_quantity','$i_price','$i_id','$un')";
if ($conn->query($sql)) {
header("location: lastpageFINAL.php");
} else {
echo "Error: " . $sql . "" . $conn->error;
}
$conn->close();
}
echo '<br /><a href="orderstatus1.php">';
//echo '<br /><a href="index.php">';
?>
I tried using global variables but couldn't make it.
Back in the days when I was a university student, one of my teachers told us that the code that you repeatedly need to execute is called "function". She was right in my opinion. However, you can do without functions as well, even though it's not especially advisable. You can use include/require for this purpose:
foo.php
$something = 0;
for ($i = 1; $i < 100; $i++) {
$something += $i;
require "bar.php";
}
bar.php
echo $something."<br>";
As you can see, $something is visible in bar.php because it was initialized before the file was required. This is how you can "pass" variables to files. However, again, it is advisable to define functions, require them only once and call them whenever you need them. Even better is to implement classes, but learn function programming first.
And as a sidenote I should mention: beware SQL injection and use parameterized queries instead of string interpolation.

Search bar not functioning properly

My problem is when I enter a specific country name, for example: France, it'll output every data from my database instead of just France. I don't know where I've gone wrong and its probably something very simple but I don't even know how to attempt to fix it so I've come here to get some help
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$country = $_POST['country'];
$_SESSION['country'] = $country;
$sqlQuery = "SELECT * FROM campsites WHERE country LIKE '%$country%'";
$result = $campDataSet->fetchAllCamps($sqlQuery);
//var_dump($result);
if (count($result) > 0) {
echo'<div class="table-responsive">
<table class="table">
<thead id="table1Head">
<tr><td>Name</td>
<td>Address</td>
<td>Postcode</td>
<td>Country</td>
<td>Latitude</td>
<td>Longitude</td>
<td>email</td>
<td>Phone<td>
</thead>
<tbody>
</div>';
foreach ($result as $row) {
echo '<tr><td>' . $row->campsite_name . '</td> <td>' . $row->address . '</td> <td>' . $row->postcode . '</td> <td>' . $row->country. '</td> <td>' . $row->lattitude . '</td> <td>' . $row->longitude . '</td> <td>' . $row->email . '</td> <td>' . $row->phone_number . '</td></td></tr>';
}
echo "</tbody></table>";
} else {
print " 0 results";
}
}
my Database class
class campDataSet
{
public $dbHandle, $dbInstance;
public function __construct()
{
$this->db = new campData();
$this->conn = $this->db->getCampData();
}
public function fetchAllCamps()
{
//$sqlQuery = "SELECT campsites.id_campsite, campsites.campsite_name, campsites.address, campsites.postcode, campsites.country, campsites.lattitude, campsites.longitude, campsites.email, campsites.phone_number
// FROM sgb220_clientserver.campsites";
$sqlQuery = "SELECT * FROM sgb220_clientserver.campsites";
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
while ($row = $data->fetch()) {
$dataSet[] = new DBdata($row);
}
} else {
echo "<script> alert(\"Could not prepare SQL statement\") </script>";
}
return $dataSet;
}
Your fetchAllCamps() method doesn't accept any arguments.
Instead of defining the $sqlQuery inside fetchAllCamps, use a parameter:
public function fetchAllCamps($sqlQuery) // <- This
{
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
...
A warning about SQL Injection
Because you are inserting $_POST data directly into your query, the user is able to manipulate the sql and thus can extract/manipulate data however he wants to. Read up in SQL Injection and how to prevent it to keep your database safe from attackers.
This might be a good starting point: https://stackoverflow.com/a/601524/2232127
Your issue is that you are running a query that just gets all of the camps instead of only the ones in a certain country. Your fetchAllCamps() function does not accept any parameters.
It would probably be best to move your query into the fetchAllCamps() function, or make another function entirely if you need a function to give you all the camps instead o just ones in a certain country. Instead of passing in the query, just pass the $country variable. Build your query inside the function and run it.
This way you are separating all of your SQL from where you are building your HTML. This is more in line with modern programming standards.

Trying to delete a row from a table

At the moment I am displaying in a table all the patients that are registered to a health centre. I have added a delete button or delete link that will remove the patient from the table. When I click on the delete button I am getting an error message and all of the patients that were previously displayed are gone and the 'all patient view' page now echoes out '0 results'.
If someone could help me resolve the issue so that I can remove a patient from the table that would be much appreciated.
Error Message
Warning: main(): Couldn't fetch mysqli_result in E:\WebProgrammingAssignment\views\AllPatientsView.php on line 48
UPDATED Register Patient Model
<?php
require_once('DAO.php');
class RegisterPatientModel extends DAO
{
protected $target = "patient";
public function __construct()
{
parent::__construct();
}
public function insertPatient($firstname, $lastname, $patstreet, $patcity, $patpostcode, $patphone, $doctorid, $dob)
{
$firstname = parent::escape($firstname);
$empnin = parent::escape($lastname);
$patstreet = parent::escape($patstreet);
$patcity = parent::escape($patcity);
$patpostcode = parent::escape($patpostcode);
$sql = "INSERT INTO {$this->target} (`firstname`, `lastname`, `patstreet`, `patcity`, `patpostcode`, `patphone`, `doctorid`, `dob`) VALUES ('{$firstname}', '{$lastname}', '{$patstreet}', '{$patcity}', '{$patpostcode}', '{$patphone}', '{$doctorid}', '{$dob}');";
return parent::query($sql);
}
public function deletePatient($patientid)
{
$sql = "DELETE
FROM {$this->target}
WHERE patientid='{$patientid}'";
return parent::query($sql);
}
function getAllPatients()
{
$sql = "SELECT a.patientid,
concat(d.firstname, ' ', d.lastname) as fullname_doctor,
a.firstname, a.lastname, a.patstreet, a.patcity, a.patpostcode, a.patphone, a.dob
FROM patient as a
INNER JOIN doctor as d
on a.doctorid = d.doctorid;";
return parent::query($sql);
}
}
?>
UPDATE All Patient View
<html>
<tr>
<td colspan="5" align="center">
<div id="boxalign2" class="boxalign2">
<div class="inputwrap">
<br>
<table id="customers" width="900" border="1" cellspacing="0" cellpadding="1">
<tr align="center">
<td bgcolor="#008000">Patient ID</td>
<td bgcolor="#008000">Doctor Name</td>
<td bgcolor="#008000">First Name</td>
<td bgcolor="#008000">Last Name</td>
<td bgcolor="#008000">Street</td>
<td bgcolor="#008000">City</td>
<td bgcolor="#008000">Post Code</td>
<td bgcolor="#008000">Telephone</td>
<td bgcolor="#008000">DOB</td>
</tr>
<?php
$allpatients = $_SESSION['patients'];
if ($allpatients->num_rows > 0) {
while ($row = $allpatients->fetch_assoc()) {
echo "<td>" . $row["patientid"] . "</td>";
echo "<td>" . $row["fullname_doctor"] . "</td>";
echo "<td>" . $row["firstname"] . "</td>";
echo "<td>" . $row["lastname"] . "</td>";
echo "<td>" . $row["patstreet"] . "</td>";
echo "<td>" . $row["patcity"] . "</td>";
echo "<td>" . $row["patpostcode"] . "</td>";
echo "<td>" . $row["patphone"] . "</td>";
echo "<td>" . $row["dob"] . "</td>";
echo "<td><a href='../controllers/ViewAllPatientsController.php?patientid=" . $row['patientid'] . "'>Delete</a></td>";
echo "</tr>";
}
} else {
echo "0 results.";
}
?>
UPDATED View Patient Controller
<?php
session_start();
require_once("../models/RegisterPatientModel.php");
$vapc = new RegisterPatientModel;
if (isset($_GET['patientid'])) {
$vapc->deletePatient($_GET['patientid']);
}
$allpatients = $vapc->getAllPatients();
require_once("../views/AllPatientsView.php");
try this:
public function deletePatient($patientid)
{
$sql = "DELETE
FROM {$this->target}
WHERE patientid='{$patientid}'";
echo $sql;
die();
return parent::query($sql);
}
You will be able to figure out if the SQL query is getting created correctly.
Obligatory warning: this is not a good way to make queries.
See How can I prevent SQL injection in PHP?
Update the 1st
Since deletePatient() is not firing, the issue must be earlier in the source.
Try removing
require_once("../views/AllPatientsView.php");
from DeletePatientController.php
Update the 2nd
You are not using $_POST, so remove
if (isset($_POST["Delete"])) {
And use $_GET instead to access the patientid
Update the 3rd
if (isset($_GET['patientid'])) {
$patientid->{$_GET['patientid']}();
}
$rpms->deletePatient($patientid);
Should be
if (isset($_GET['patientid'])) {
$rpms->deletePatient($_GET['patientid']);
}
Update the 4th
Since the query is not the source of the issue, remove the debug statements:
public function deletePatient($patientid)
{
$sql = "DELETE
FROM {$this->target}
WHERE patientid='{$patientid}'";
return parent::query($sql);
}
Update the 5th
Since the delete itself is not part of the issue, your next step is to debug the other parts of the code.
$allpatients = $vapc->getAllPatients();
$_SESSION['patients'] = $allpatients;
...
$allpatients = $_SESSION['patients'];
The $_SESSION shenanigans are not needed. Remove $_SESSION['patients'] = $allpatients; and $allpatients = $_SESSION['patients'];.
Then, change
if ($allpatients->num_rows > 0) {
to
var_dump($allpatients);
die();
if ($allpatients->num_rows > 0) {
and see if that leads anywhere. You should see some kind of DAO object or mysql_result (whatever parent::query() returns).
Quick Tip
You can remove the last ?> from .php files. This will save you from some weird Header bugs down the line with trailing line breaks in your outputs.

Foreach loop and variables in php

Happy new yar. I am still new to php so I need your great help. I am designing a post page where visitors can post anything. I am almost through but when I post something to the page, the new post over ride the old one, I am certain I need to use foreach loop but my problem I can't define the $posting variable.
My bad, but I really need you guys to help me. here is my coding:
<?php
include 'connect.php';
?>
<?php
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$post = $_POST['post'];
$name = $_POST['name'];
if (empty($title) or empty($post) or empty($name)) {
$message = "Please fill in all fields";
} else {
mysql_query("INSERT INTO prayer VALUES('', '" . $title . "', '" . $post . "', '" . $name . "')");
$message = "PRAYER REQUEST SUBMITTED!!!";
}
echo"$message";
}
?>
<form method="post" action="prayerpage.php">
<table width="80%">
<tr>
<td><b>Name:</b><input type="text" name="name" />
<b>Title:</b><input type="text" name="title" /></td>
</tr>
<tr>
<td><b>Prayer<br>Request:</b></td>
<td><textarea name='post' rows='10' cols='40'></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="SUMIT"/></td>
</tr>
</table>
</form>
<hr width="70%">
<?php
function postid($id) {
$array = array();
$q = mysql_query("SLECT * FROM prayer WHERE id='.$id.'");
while ($r = mysql_fetch_assoc($q)) {
$array['id'] = $r['id'];
$array['title'] = $r['title'];
$array['name'] = $r['name'];
$array['post'] = $r['post'];
}
return $array;
}
foreach ($posting as $posting) {
?>
<table width="60%">
<tr>
<td><font color="blue"><?php echo $title; ?></font></td>
</tr>
<tr>
<td><?php echo $post; ?> - <font color="blue"><?php echo $name; ?></font> </td>
</tr>
</table>
<hr noshade width="50%">
<?php
}
?>
And please i also need the code to make the post a link to its page
check your id is auto increment or not if not then make it autoincrement
then try to change this code in your page :
mysql_query("INSERT INTO prayer VALUES('', '".$title."', '".$post."', '".$name."')");
to
mysql_query("INSERT INTO prayer VALUES('".$title."', '".$post."', '".$name."')");
There are a couple problems with your code. The first is that you mysql_query when you should be using mysqli_query, same mysql_fetch_assoc, should be mysqli_fetch_assoc -- please replace all references of mysql_* with mysqli_*. The second is you are running a query inside of a function. The third problem is your query is wrong. And... you do not need a foreach in the way you are using it.
function postid($id) {
global $db;
$array = array();
$id = (int)$id; // cast as int to prevent SQL injection
$q = mysqli_query($db, "SELECT * FROM prayer WHERE id=$id");
while ($r = mysqli_fetch_assoc($q)) {
$array['id'] = $r['id'];
$array['title'] = $r['title'];
$array['name'] = $r['name'];
$array['post'] = $r['post'];
}
return $array;
}
You had a typo, it should be SELECT not SLECT. You do need to concatenate variables when you are inside of a double quoted string. I would link to the PHP documentation about it but is not super clear. Basically the following lines all result in the same output:
$amazing = "neato!";
$example1 = "This is my variable: $amazing"; // Output: This is my variable: neato!
$example2 = 'This is my variable: ' . $amazing; // Output: This is my variable: neato!
$example3 = "This is my variable: " . $amazing; // Output: This is my variable: neato!
Notice how you can put a variable inside of a string with double quotes. But you cannot do this:
$doesNotWork = 'This is my variable: $amazing'; // Output: This is my variable: $amazing
$doesNotWork = "This is my variable: '.$amazing.'"; // Output: This is my variable: '.$amazing.'
The reason you should use mysqli_query is because mysql_query is no longer supported. Inside of your function you will need to use the special keyword global to get the variable of your database connection (I set it to $db in the example but you might have it called something else).
Basically, global is a PHP keyword that will allow you to access variables that have been defined in the global scope. Read about in the documentation by clicking here
[..] within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
Lastly.. you do not have the variable $posting defined correctly.
You can fix this by getting rid of your call to foreach, replace this line:
foreach ($posting as $posting) {
With these 2 lines:
$q = mysqli_query($db, "SELECT * FROM prayer");
while ($posting = mysqli_fetch_assoc($q)) {
Your $posting variable is undefined, when it looks like you actually just want to query the database and get all the rows from the prayer table.
This query will give you warnings in MYSQL but execute due to PK auto increment:
mysql_query("INSERT INTO prayer
VALUES('', '" . $title . "', '" . $post . "', '" . $name . "')");
Solution is that define column names in this query and if your id is PK than not use because its auto increment:
mysql_query("INSERT INTO prayer (title,post,name)
VALUES('".$title."','".$post."','".$name."')");

PHP/MySQL Table with Hyperlinks

I have 2 PHP forms. One displays a list of events and the other displays the results of each specific event. On the page with the list of events I would like it so that a hyperlink can be created to access each individual event's results.
For example, on the Events page I click on row 2's hyperlink which will then take me to the Results page that has the results for that specific event.
Any help would be appreciated as I am very, very new to PHP. If any extra details are needed, please feel free to ask.
Thanks.
Edit: Sorry I'll show you what the Events form looks like so far:
<?php
mysql_connect('localhost','root','');
mysql_select_db('clubresults') or die( "Unable to select database");
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
$result = mysql_query ($sql);
?>
<table border = 1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "</td><td>" . $row['EventID'] . "</td><td>" . $row['EventName'] . "</td><td>" . $row['newdate'] . "</td><td>" . $row['Location'] . "</td><tr>";
}
echo "</table>";
mysql_close();
?>
You don't need two scripts, but just one:
events.php?list
events.php?event=1234
in there you only need to check for things:
$db = new Database(); # simplified
/* show event details if requested */
if (isset($_GET['event']) {
if ($event = $db->getEventByID($_GET['event'])) {
printf('<h2>Event: %s</h2>', htmlspecialchars($event->title));
# ...
}
}
/* show the list if requested (or show it always, whatever pleases you) */
if (isset($_GET['list']) {
echo '<table>';
foreach($db->getEventList() as $event) {
printf('<tr><td>%s</td></tr>'
, $event->ID, htmlspecialchars($event->title));
}
echo '</table>';
}
Edit: As I saw in your updated question, you should switch from those oldskool mysql_* functions to the class style I outlined in my example, because it is much simpler to use. Here is a code-example that is close to yours:
<?php
/**
* My First PDO Databaseclass
*/
class Database extends PDO
{
public function __construct()
{
$host = 'localhost';
$name = 'clubresults';
$user = 'root';
$pass = NULL;
parent::__construct("mysql:host=$host;dbname=$name", $user, $pass);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function getEvents()
{
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
return $this->query($sql, PDO::FETCH_OBJ );
}
public function getEventByID($id)
{
$sql = sprintf("SELECT * FROM Events WHERE EventID = %d;", $id);
return $this->query($sql)->fetchObject();
}
}
$db = new Database();
?>
<table border=1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
foreach($db->getEvents() as $event)
{
echo "</td><td>" . $event->EventID . "</td><td>" . $event->EventName . "</td><td>" . $event->newdate . "</td><td>" . $event->Location . "</td><tr>";
}
?>
</table>

Categories