Information retrieved from database are not displayed? - php

I am using PHP(MVC) to build a website. I have successfully connected and inserted data to SQL database using PDO. However, I am having an issue from getting customer data back, I have recivied no errors. it just that the information are not displayed from the View, I have defined a class for the customer as follows:
<?php
class CustomerDetails {
private $_name,$_email,$_phone, $_choise;
public function __constructor($dbrow){
$this->_name = $dbrow['name'];
$this->_email = $dbrow['email'];
$this->_phone = $dbrow['phone'];
$this->_choise = $dbrow['choise'];
}
function get_name() {
return $this->_name;
}
function get_email() {
return $this->_email;
}
function get_phone() {
return $this->_phone;
}
function get_choise(){
return $this->_choise;
}
}
I have also defined a class to execute SQL query which featchs a customer details and store them in an array list as follows:
<?php
require_once ('Models/CustomerDetails.php');
require_once ('Models/Database.php');
class AdminPanel{
public function __construct() {
$this->_dbInstance = Database::getInstance();
$this->_dbHandle = $this->_dbInstance->getdbConnection();
}
public function fetchAllCustomers() {
$sqlQuery = 'SELECT * FROM info';
echo $sqlQuery; //helpful for debugging to see what SQL query has been created
$statement = $this->_dbHandle->prepare($sqlQuery); // prepare PDO statement
$statement->execute(); // execute the PDO statement
$dataSet = [];
while ($row = $statement->fetch()) {
$dataSet[] = new CustomerDetails($row);
}
return $dataSet;
echo $dataSet;
}
Views where it responsible for displaying the information, But noting appears :
<div class="row">
<div class="col-lg-6">
<h2>Customer Table</h2>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Choise</th>
</tr>
</thead>
<tbody>
<?php foreach ($view->infos as $adminPanel) {
echo '<tr>' . '<td>' . $adminPanel->get_name() . '</td>'
. '<td>' . $adminPanel->get_email() . '</td>'
. '<td>' . $adminPanel->get_phone() . '</td>'
. '<td>' . $adminPanel->get_choise() . '</td>'
. '</tr>';
} ?>
</tbody>
</table>
</div>
</div>
}
Controller which passes the view object to View:
require_once('Models/AdminPanel.php');
$view = new stdClass();
$adminPanel = new AdminPanel();
$view->infos = $adminPanel->fetchAllCustomers(); //->fetchAllStudents();
require_once('Views/adminPanel.phtml');
DataBase Connection Class:
class Database {
protected static $_dbInstance = null;
protected $_dbHandle;
public static function getInstance(){
$host = 'localhost';
$dbName = 'oasis';
$username = 'root';
$password = '';
if(self::$_dbInstance=== null) { //checks if the PDO exists, if not create it with
//the connection info
self::$_dbInstance= new self($username, $password, $host, $dbName);
}
return self::$_dbInstance;
}
private function __construct($username, $password, $host, $database) {
try {
$this->_dbHandle= new PDO("mysql:host=$host;dbname=$database", $username, $password); // creates database handle with connection info
}
catch (
PDOException$e) { // catch any failure to connect to database
echo $e->getMessage();
}
}
public function getdbConnection(){
return $this->_dbHandle; // returns the database handle to be used elsewhere
}
public function __destruct() {
$this->_dbHandle= null; // destroys the destroys the database handle
}
}
I have received no errors, it just the information are not displayed.

Related

Updating table with username php

I am currently working on a job claiming system and currently struggling with users being able to claim a piece of available work in my jobs table.
When replacing parts of the update query called by the update button it seems to be the order_id which is not being passed to the query properly from the original query.
I am very new to this so any other comments or direction would be very helpful
<?php
session_start();
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
echo "You are currently logged in as " . $_SESSION["login_user"] . ".<br>";
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Order ID</th><th>Status</th><th>Service</th><th>Document Type</th><th>Word Count</th><th>Other Considerations</th><th>Date Received</th><th>Claim</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo '<td><form id="view_admin" method="post">
<input type="submit" name="username" value="Accept"></td>';
echo "</tr>" . "\n";
}
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT `Order_ID`,`Status`,`Service`,`Document_Type`,`Word_Count`,`Other_Considerations`,`Receive_Date`
FROM `PRW_JOBS` where `staff_username` is null");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
echo "</table>";
if($_POST && isset($_POST['username'])){
$sql = "update `PRW_JOBS` set `staff_username` = :staff_username where `Order_ID`= :Order_ID and `staff_username` is NULL";
$stm = $conn->prepare($sql);
$stm->bindParam(':Order_ID', $result['Order_ID'], PDO::PARAM_INT);
$stm->bindParam(':staff_username', $_SESSION["login_user"], PDO::PARAM_STR);
$stm->execute();
}
$conn = null;
?>
Your problem arises because you're using setFetchMode() in a wrong way. setFetchMode() returns a boolean (true or false), not a $result. fetchAll() returns a $result! So, instead of using this:
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
use this:
$assigned = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
Then it will work properly.
I'd recommend you to use them like this:
$fetchedData = $selectStatement->fetchAll(PDO::FETCH_ASSOC);
I also recommend you to ALWAYS look into the php.net docs for each function you are using: parameters list, return value and especially which kind of errors/exceptions it throws. Therefore: always use exception handling. As you already did. But for example, a PDO::prepare function can not only throw a 'PDOexception', but it can also return false. This case must also be covered. See this: PDO::prepare (the "Return values" part).
I prepared for you a complete php solution for your question code. I did it to show you how to separate HTML output from php and to show you how to cover ALL data access functionality and the exception handling.
There are four pages: the main page (index.php), the TableRows.php containing your table rows class, a DataAccess.php for data access and a Printer.php with printing function(s).
I recommend you to ALWAYS save a class in its own php page, which has the same name as the class name.
I used functions in those files. But you can, of course, use OOP, e.g classes, instead. For example a Connection class to handle all db connectivity, a Printer class for printing functionality, etc.
Notice how I "relaxed" the html code and the handling of the whole php in one place. You see how slim is the html code now?
And notice that I don't bring functions like fetchAll() around the page. I call all data access functions in one place, I fetch the data and with THIS $fetchedData I can do what I want around the page. It's safe to close a db connection as soon as possible in code.
Nota bene, for development, not for production (!): if you think that you need to see the whole, detailed exceptions instead of your custom exception messages, just replace these:
printData($pdoException->getMessage());
printData($exception->getMessage());
with these:
printData($pdoException);
printData($exception);
Good luck!
Printer.php
<?php
/**
* Print data on screen in a preformatted way.
*
* #param mixed $data Data to print.
* #return void
*/
function printData($data) {
echo '<pre>' . print_r($data, true) . '</pre>';
}
DataAccess.php
<?php
/**
* Create a new db connection.
*
* #param string $dsn Connection DSN.
* #param string $username Username.
* #param string $password Password.
* #param array $options [optional] Driver options.
* #return PDO Db connection.
*/
function createConnection($dsn, $username, $password, $options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_PERSISTENT => true,
)) {
$connection = new PDO($dsn, $username, $password);
foreach ($options as $key => $value) {
$connection->setAttribute($key, $value);
}
return $connection;
}
/**
* Close a db connection.
*
* #param PDO $connection Db connection.
* #return void
*/
function closeConnection($connection) {
$connection = NULL;
}
/**
* Get the data type of a binding value.
*
* #param mixed $value Binding value.
* #return mixed Data type of the binding value.
*/
function getInputParameterDataType($value) {
$dataType = PDO::PARAM_STR;
if (is_int($value)) {
$dataType = PDO::PARAM_INT;
} elseif (is_bool($value)) {
$dataType = PDO::PARAM_BOOL;
}
return $dataType;
}
TableRows.php:
<?php
use RecursiveIteratorIterator;
/*
* Table rows class.
*/
/**
* Table rows class.
*
*/
class TableRows extends RecursiveIteratorIterator {
function __construct($iterator) {
parent::__construct($iterator, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current() . "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo '<td>';
echo '<form id="view_admin" method="post">';
echo '<input type="submit" name="username" value="Accept">';
echo '</td>';
echo '</tr>' . '\n';
}
}
index.php:
<?php
include 'TableRows.php';
include 'DataAccess.php';
include 'Printer.php';
session_start();
$servername = 'localhost';
$dbname = 'dbname';
$username = 'username';
$password = 'password';
$loginUser = isset($_SESSION['login_user']) ? $_SESSION['login_user'] : '';
try {
// Create db connection.
$connection = createConnection('mysql:host=' . $servername . ';dbname=' . $dbname, $username, $password);
// Define sql statement.
$sql = 'SELECT
`Order_ID`,`Status`,`Service`,`Document_Type`,
`Word_Count`,`Other_Considerations`,`Receive_Date`
FROM `PRW_JOBS`
WHERE `staff_username` IS NULL';
// Prepare and check sql statement (returns PDO statement).
$selectStatement = $connection->prepare($sql);
if (!$selectStatement) {
throw new Exception('The SQL statement can not be prepared!');
}
// Execute and check PDO statement.
if (!$selectStatement->execute()) {
throw new Exception('The PDO statement can not be executed!');
}
// Fetch all data.
$fetchedData = $selectStatement->fetchAll(PDO::FETCH_ASSOC);
// Get rows collection.
$tableRows = new TableRows(new RecursiveArrayIterator($fetchedData));
// Upon form submission by 'Accept' button.
if (isset($_POST['username'])) {
// Define sql statement.
$sql = 'UPDATE `PRW_JOBS`
SET `staff_username` = :staff_username
WHERE `Order_ID` = :Order_ID AND `staff_username` IS NULL';
// Prepare and check sql statement (returns PDO statement).
$updateStatement = $connection->prepare($sql);
if (!$updateStatement) {
throw new Exception('The SQL statement can not be prepared!');
}
// Bind values to sql statement parameters.
$updateStatement->bindValue(':Order_ID', $fetchedData['Order_ID'], getInputParameterDataType($fetchedData['Order_ID']));
$updateStatement->bindValue(':staff_username', $loginUser, getInputParameterDataType($loginUser));
// Execute and check PDO statement.
if (!$updateStatement->execute()) {
throw new Exception('The PDO statement can not be executed!');
}
}
closeConnection($connection);
} catch (PDOException $pdoException) {
printData($pdoException->getMessage());
exit();
} catch (Exception $exception) {
printData($exception->getMessage());
exit();
}
?>
<span>
You are currently logged in as <?php echo $loginUser; ?>
</span>
<br>
<table style="border: solid 1px black;">
<tr>
<th>Order ID</th>
<th>Status</th>
<th>Service</th>
<th>Document Type</th>
<th>Word Count</th>
<th>Other Considerations</th>
<th>Date Received</th>
<th>Claim</th>
</tr>
<?php
foreach ($tableRows as $row) {
echo $row;
}
?>
</table>

Establishing database connection through php class

I am currently learning and working with php classes. I have created a basic class in hopes to connect with mysql database and fetch results from two tables. I am using PDO style. In a separate file called db_con.php
I have my credentials to connect with my db. I am having difficulties in establishing and fetching the values successfully. I am not able to use $db_con from the db file inside the SelectList class to establish a connection.
I am getting an error in this line in particular:
$sql = $this->db_con->prepare("SELECT * FROM curriculum_selection_list");
The error states:
Fatal error: Call to a member function prepare() on a non-object in /data/24/2/26/14/2678177/user/2940861/htdocs/controlpanel/select.class.php
How can I fix this?
select.class.php
include "db_con.php";
class SelectList
{
private $db_con;
public function __construct()
{
$this->db_con = $db_con;
}
public function ShowCurriculum()
{
$sql = $this->db_con->prepare("SELECT * FROM curriculum_selection_list");
$sql->execute();
$data = $sql->fetchAll();
$curriculum = '<option value="0">choose...</option>';
foreach ($data as $row){
$curriculum .= '<option value="' . $row['curriculum_id'] . ':' . $row['curriculum_name'] . '">' . $row['curriculum_name'] . '</option>';
}
return $curriculum;
}
public function ShowCourse()
{
$sql = $this->db_con->prepare("SELECT * FROM course_selection_list");
$sql->execute();
$data = $sql->fetchAll();
$course = '<option value="0">choose...</option>';
foreach ($data as $row){
$course .= '<option value="' . $row['course_id'] . ':' . $row['course_name'] . '">' . $row['course_name'] . '</option>';
}
return $course;
}
}
$opt = new SelectList();
db_con.php
$dsn = '';
$user = '';
$password = '';
try {
$db_con = new PDO($dsn, $user, $password);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
you need a global declaration to access a variable assigned outside the function:
public function __construct()
{
global $db_con;
$this->db_con = $db_con;
}
But it would be better to either pass the connection in as a parameter when creating the object, or define a function in db_con.php and call it from the constructor.
As mentioned you are getting error into below line:
$sql = $this->db_con->prepare("SELECT * FROM curriculum_selection_list");
In this above code it is not able to create connection with db.php
please try
class SelectList
{
global $db_con;
....
....
.....
}

No records returned in PHP using OOP

I am making a module in which I am fetching users from Database Using OOP.
But due to some reason , records are not fetching, and there is no mysql error.
Here is my Code:
dbsetup_class.php :
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
/* echo "<pre>";
var_dump($this->dbc);
*/
//echo $sql;
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
And here is my index.php:
<?php
require_once("dbsetup_class.php");
$connection = new mySQL();
$connection->connect('localhost', 'admin', 'admin', 'oop_test');
//die('success');
$myquery = "SELECT * FROM users";
$query = $connection->query($myquery);
$array = $connection->fetch($query);
while($array)
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
What I am doing here?
Your fetch method expects SQL query, and not the result of a query. You should redefine it as (assuming that the client code is what you want as an interface):
public function fetch($resource)
{
$array = mysqli_fetch_array($resource);
return $array;
}
Also if you have results, your while will be infinite.

MySQLi database connection

I have this (from someone else derived from my first attempt at a database class):
require_once( "declarations.php" );
class Database{
private static $mysqli;
private static $dbName = '';
private static $username = '';
private static $password = '';
private static $host = 'localhost';
private static $prefix = '';
public function __construct(){
if( self::$host & self::$username & self::$password & self::$dbName )
{
self::$mysqli = new mysqli( self::$host, self::$username, self::$password, self::$dbName );
if (self::$mysqli->connect_error) {
die('Connect Error (' . self::$mysqli->connect_errno . ') '
. self::$mysqli->connect_error);
}
}
else
{
echo "You forgot to fill in your database connection details";
}
}
public function Query( $query ){
$query = self::$mysqli->real_escape_string( $query );
if ($query = self::$mysqli->prepare($query)) {
$query->execute();
$query->store_result();
$stmt = $query->result;
//$query->mysql_num_rows = $stmt->num_rows();
$query->close();
return $stmt;
}
}
public function Close()
{
self::$mysqli->close();
}
}
This is how i'm calling it:
include_once( "system/database.php" );
$query = "SELECT * FROM app";
$dbr = new Database();
//Change this here since your method is query and not $mysqli
while( $row = $dbr->Query( $query )->fetch_object() ){
echo '<td>'. $row['id'] . '</td>' ;
echo '<td>'. $row['title'] . '</td>' ;
}
Database::Close();
I am getting an error Call to a member function fetch_object() on a non-object in on the while loop.
Any ideas?
fetch_object works with result set returned after query is executed with methods like: mysql_query or use fetch_assoc instead with
$query->execute();
$result = $query->get_result();
while ($myrow = $result->fetch_assoc()) {
//Your logic
}
Well, your first attempt resulted with totally unusable code.
There are 2 critical faults and one serious one.
As I told you already, doing $query = self::$mysqli->real_escape_string( $query ); is useless and harmful at once. You have to get rid of this line. Completely and forever.
Preparing a query without binding variables is totally useless.
You have to check for mysql errors.
So, at the very least your query() function have to be
public function query($query)
{
$res = self::$mysqli->query($query);
if (!$res)
{
throw new Exception(self::$mysqli->error);
}
return $res;
}
But again - this function is not safe as it's not not implementing placeholders to substitute data in the query.

$mysqli->fetch_object cannot get a result to iterate through - PHP - Mysql

I have the current code:
Database::connect();
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM app";
$dbr = Database::query( $query );
while( $row = Database::$mysqli->fetch_object( $dbr->result ) ){
?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->title; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
Database::close();
?>
and here is the Database and DatabaseQuery classes
class DatabaseQuery{
public $result;
public $mysql_num_rows;
}
class Database{
public static $mysqli;
private static $db_name = '';
private static $username = '';
private static $password = '';
private static $host = 'localhost';
private static $prefix = '';
public static function connect(){
self::$mysqli = new mysqli( self::$host, self::$username, self::$password, self::$db_name );
if (self::$mysqli->connect_error) {
die('Connect Error (' . self::$mysqli->connect_errno . ') '
. self::$mysqli->connect_error);
}
}
public static function query( &$query ){
$query = self::$mysqli->real_escape_string( $query );
if ($stmt = self::$mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$DatabaseQuery = new DatabaseQuery();
$DatabaseQuery->result = $stmt;
$DatabaseQuery->mysql_num_rows = $stmt->num_rows();
$stmt->close();
return $DatabaseQuery;
}
}
public static function close(){
self::$mysqli->close();
}
}
I'm getting an error in my calling code: Fatal error: Call to undefined method mysqli::fetch_object()
Any ideas?
Replace your following line:
while( $row = Database::$mysqli->fetch_object( $dbr->result ) ){
for this one:
while( $row = $dbr->fetch_object( $dbr->result ) ){
Because fetch_object() is a method of mysqli_result object, and not of the general mysqli object.
I think this is your problem, but I would suggest looking into PDO's a very simple way of accessing databases and working with them.
<?php
$query = "SELECT * FROM app";
$dbr = Database::query( $query );
//Change this here since your method is query and not $mysqli
while( $row = Database::$dbr->fetch_object( $dbr->result ) ){
?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->title; ?></td>
</tr>
<?php
}
?>
If your dont mind I would say u are complicating your class a lot. If u have a reason then ok if not u could do it like this.
class Database{
private static $mysqli;
private static $db_name = '';
private static $username = '';
private static $password = '';
private static $host = 'localhost';
private static $prefix = '';
public function __construct(){
self::$mysqli = new mysqli( self::$host, self::$username, self::$password, self::$db_name );
if (self::$mysqli->connect_error) {
die('Connect Error (' . self::$mysqli->connect_errno . ') '
. self::$mysqli->connect_error);
}
}
public function query( $query ){
$query = self::$mysqli->real_escape_string( $query );
if ($query = self::$mysqli->prepare($query)) {
$query->execute();
$query->store_result();
$stmt = $query->result;
//$query->mysql_num_rows = $stmt->num_rows();
$query->close();
return $stmt;
}
}
}
The file that uses the class
//Include the file unless u have a autoloader
<tr>
<?php
$query = "SELECT * FROM app";
$dbr = new Database();
//Change this here since your method is query and not $mysqli
while( $row = $dbr->query($query)->fetch_object() ){
echo '<td>'. $row['IDcolumnName'] . '</td>' ;
echo '<td>'. $row['TitlecolumnName'] . '</td>' ;
}
?>
</tr>
Your logic is broken:
$query = self::$mysqli->real_escape_string( $query );
You do not escape the entire query. You escape data you're inserting into a query, e.g. if you had somethign like
SELECT id, name, ... WHERE firstname = '$searchterm'
you'd escape the value in $searchterm. Escaping the entire query turns it into
SELECT id, name, ... WHERE firstname = \'$searchterm\'
and you end up with syntax errors, because you no longer have quotes around $searchterm, you have a couple ignored characters as part of a bare string.
Then there's:
$stmt->store_result();
store_result() returns a statement handle you can use to fetch results from later. You're not capturing that handle, so your DB result is simply thrown away, even if the query had executed properly.

Categories