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.
Related
I have 3 files: dbconnect (here's declaration of $pdo), core.php (file with class to manage) and test.php.
I want to receive data from DB, but I have error:
Notice: Undefined variable: pdo in C:\xampp\htdocs\project\core.php on line 24
In dbconnect $pdo is in try catch, but before this I put: $pdo=null(to make variable accessible) but it doesn't work.
dbconnect ---> core.php(error here) ---> test.php;
//dbconnect.php
<?php
$mysql_host = 'localhost';
$username = 'root';
$password = '';
$database = 'db';
$pdo = null;
try {
$pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
?>
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
?>
Anyone can solve this? Thanks.
This is a scoping problem. $pdo doesn't exists in your getCore class.
You can make a DatabaseConnect class to manage your db access.
You can use this basic class for your database connection :
<?php
class DatabaseConnect {
private $mysql_host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'db';
private $pdo = null;
public function getPdo(){
return $this->pdo;
}
public function __construct(){
try {
$this->pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
}
}
?>
You can getting your PDO instance in an other class with calling DatabaseConnect object -> getPdo() :
- Instannciate a new DatabaseConnect.
- Get PDO instance with the methof of the class.
Like that :
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect->getPdo();
You next code :
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect-getPdo();
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
You need to pass $pdo to the getLinks() function as an input to make it available for use. you could try getLinks($pdo)
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I put those two code snippets in a class so the databasehandling is in a class? Like a PDO connection or put all that have to do with database is in a class, how would you guys do it?
Here are two parts of the code from different files. I am trying to develop a blog application.
<?php
mysql_connect("localhost", "root", "")or die(mysql_error());
mysql_select_db("blogg1")or die(mysql_error());
if(isset($_POST["submit"])){
$title = $_POST["title"];
$category = $_POST["category"];
$content = $_POST ["content"];
mysql_query("INSERT INTO blogdata(title , category , content) VALUES('$title', '$category', '$content')");
}else{
?>
<?php
mysql_connect("localhost", "root", "")or die(mysql_error());
mysql_select_db("blogg1")or die(mysql_error());
$sql = mysql_query("SELECT * FROM blogdata ORDER BY id DESC")or die(mysql_error());;
while($row = mysql_fetch_array($sql)){
$title = $row["title"];
$category = $row["category"];
$content = $row["content"];
?>
<table border = "1">
<tr><td><?php echo $title; ?></td><td><?php echo $category; ?></td></tr>
<tr><td colspan="2"><?php echo $content; ?></td></tr>
</table>
<?php
}
?>
First, you should keep your database credentials in a separate PHP file in a folder not accessible by the web, for example ~/lib/db.php
<?php
define('SQL_HOST', 'localhost');
define('SQL_DATABASE', 'your-db-name');
define('SQL_USER', 'your-db-user');
define('SQL_PASS', 'your-db-password');
?>
Then your Database class (also in ~/lib):
<?php
require_once('~/lib/db.php');
require_once('~/lib/BlogData.php');
class Database
{
protected $db = null;
function __construct()
{
// db connection options
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false
);
// set new connection
$this->db = PDO(
"mysql:dbname=".SQL_DATABASE.";host=".SQL_HOST,
SQL_USER, SQL_PASS, $driverOptions
);
}
// This function lets you fetch blog data using any sort order you'd like and any WHERE criteria you want
function getBlogData($where = "1", $orderBy = "id DESC")
{
$stmt = $this->db->prepare("
SELECT *
FROM {'blogdata'} WHERE $where
ORDER BY $orderBy
");
$blogData = Array();
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$oneBlogData = new BlogData($this);
$oneBlogData->init($row);
$blogData[] = $oneBlogData;
}
}
return $blogData;
}
function insertBlogData(BlogData $blogData)
{
$stmt = $this->db->prepare("
INSERT INTO {'blogdata'} (title , category , content) VALUES
(:title, :category, :content);
");
$stmt->bindParam(':title', $blogData->title, PDO::PARAM_STR);
$stmt->bindParam(':category', $blogData->category, PDO::PARAM_STR);
$stmt->bindParam(':content', $blogData->content, PDO::PARAM_STR);
$stmt->execute();
}
}
?>
Then I would define another class for your blog data:
<?php
class BlogData {
public $title;
public $category;
public $content;
private $db;
function __construct(Database $db)
{
$this->db = $db;
}
function init($dbRow)
{
$this->title = $dbRow['title'];
$this->category = $dbRow['category'];
$this->content = $dbRow['content'];
}
function save()
{
// TODO: Write sql statement to save the row...
}
}
?>
Then your first block of code could create a new BlogData entry like this:
<?php
require_once('~/lib/Database.php');
$db = new Database();
if(isset($_POST["submit"]))
{
$blogData = new BlogData($db);
$blogData->title = $_POST["title"];
$blogData->category = $_POST["category"];
$blogData->content = $_POST["content"];
$db->insertBlogData($blogData);
}
?>
And your second block of code could look like this:
<?php
require_once('~/lib/Database.php');
$db = new Database();
$blogDataArray = $db->getBlogData("1", "id DESC");
echo "<table border = '1'>";
foreach($blogDataArray as $blogData)
{
echo "<tr><td>" . $blogData->title . "</td><td>" . $blogData->category . "</td></tr>";
echo "<tr><td colspan='2'>" . $blogData->content . "</td></tr>";
}
echo "</table>";
?>
This also makes it really easy to modify BlogData entries - just fetch the blog data from the Database using the getBlogData function, modify the object by simply changing it's values and calling save. For example:
<?php
// ...
$newContent = "New Content";
$blogData = $db->getBlogData("id='1'");
$blogData->content = $newContent;
$blogData->save();
?>
I should also point out the obvious that you need some unique field for your blog data entries. With some id, it'd be easier to write addToDatabase and save in one function.
Please see below for the code example:
class SomeClass {
protected $db = null;
protected $table = 'blogdata';
public function __construct()
{
// db connection options
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
// set new connection
$this->db = PDO(
"mysql:dbname=blogg1;host=localhost",
'root', '', $driverOptions
);
}
public function save($data)
{
// prepare your data
$title = $data["title"];
$category = $data["category"];
$content = $data ["content"];
// prepare statement
$stmt = $this->db->prepare("
INSERT INTO {$this->table} (title , category , content) VALUES
(:title, :category, :content);
");
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':category', $category, PDO::PARAM_STR);
$stmt->bindParam(':content', $content, PDO::PARAM_STR);
$stmt->execute();
}
public function getRecords()
{
$stmt = $this->db->prepare("
SELECT *
FROM {$this->table}
ORDER BY id DESC
");
$stmt->execute();
return $stmt->fetchAll();
}
}
And a usage example:
<?php
require_once('SomeClass.php');
$ent = new SomeClass();
if (isset($_POST["submit"])) {
$ent->save($_POST);
}
else {
// get and output
$records = $ent->getRecords();
if (count($records) > 0) {
?>
<table>
<?php
foreach ($records as $record) {
echo "<tr><td>{$record->title}</td><td>{$record->category}</td></tr>
<tr><td colspan='2'>{$record->content}</td></tr>";
}
?>
</table>
I have a function with 2 arguments. Here it is
function listBoats($con,$table){
//get record set for all boats sort them by their "sort" number
$queryBoat = "SELECT * FROM " .$table. " WHERE `id` <> 'mainPage' ORDER BY `sort` LIMIT 0, 1000";
$result = mysqli_query($con,$queryBoat);
return $result;
}
here is how I'm calling it
$result = listBoats($con,"CSINSTOCK"); //run query to list all the boats in the CSINSTOCK table
I can't get it to work. But If I add the variable $table = "CSINSTOCK" inside the function it does work. Why wont the function pass the "CSINSTOCK" variable through?
I would suggest that you use PDO. Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
If you have the access to your database you should be able to perform your required operations.
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.