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.
Related
I learning oop and want to use pdo to execute mysql query. I have a query inside function that I want to execute. When I do this I get an error:
Fatal error: Call to a member function exec() on a non-object
What I'am doing wrong?
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function testDuplicate($model) {
$SQL = "SELECT product_id FROM " . DB_PREFIX . "product WHERE model LIKE '" .$model . "'";
$result = $conn->exec($SQL);
if ($result->rows) return false;
return true;
}
function testDuplicateCat($cat) {
$SQL = "SELECT category_id FROM " . DB_PREFIX . "category WHERE category_id = '" .$cat . "'";
$result = $conn->exec($SQL);
if ($result->rows) return false;
return true;
}
foreach ($xml->PRODUCT as $child) {
if(testDuplicate($child->ID)){
...
}
}
This issue is raised because the $conn variable inside the testDuplicate function is not defined inside the scope of the function.
You could do this:
function testDuplicate($model) {
global $conn;
...
}
However it is not advice able to do so, its better to use static variables.
function getconn(){
static $conn;
if(!isset($conn)){
$conn = new PDO(...);
}
return $conn;
}
function foobar(){
$result = getconn()->query($sql);
while($row = $result->fetch()){
$ids[] = $row['category_id'];
}
return sizeof($ids) > 0 ? $ids : false;
}
if(($list = foobar()) == false){
echo "products " . var_export($list) . ' are duplicate values';
}
Why? Because you cannot simply overwrite the connection variable, even by accident or by using someone elses code. There are better alternatives but this is just a quick and safe example.
I created a function to grab data from my database. I want this function to be reusable just by placing correct arguments for different tables. Here's what I've done :
public function selectdata($table, $arguments='*', $where = null){
if($this->isconnect){
//check whether users put column names in the select clause
if(is_array($arguments)){
$new_args = implode(',', $arguments);
$sql = 'SELECT '.$new_args.' FROM '.$table;
} else {
$sql = 'SELECT '.$arguments.' FROM '.$table;
}
//check whether users use the where clause
if($where != null && is_array($where)){
$where = implode(' ', $where);
$sql .= ' WHERE '.$where ;
}
$query = $this->db->query($sql);
$query -> SetFetchMode(PDO::FETCH_NUM);
while($row = $query->fetch()){
print_r($row);
}
} else {
echo 'failed, moron';
}
}
And this is the way to run the function :
$columnname = array('bookname');
$where = array('bookid','=','2');
echo $database-> selectdata('buku', $columnname, $where);
The code worked quite decently so far, but I'm wondering how I want to use $where but without $columnname in the function. How do I pass the arguments in the function?
And could you point to me the better way to create a function to grab data using PDO?
Just use a PDO class which can look like this:
<?php
class DB_Connect{
var $dbh;
function __construct(){
$host = "xxx";
$db = "xxx";
$user = "xxx";
$password = "xxx";
$this -> dbh = $this -> db_connect($host, $db, $user, $password);
}
public function getDBConnection(){
return $this -> dbh;
}
protected function db_connect($host, $db, $user, $password){
//var_dump($host, $db, $user, $password);exit();
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->getDBConnection();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
}
?>
Now you can include that class and create an object with $dbh = new DB_Connect; and call every statement you want just with the reference on $dbh->query($statement)
This is my prefered way to do this.
EDIT: If you want to use a statement on another Database, just use the __construct($db) method to pass your database name on object creation
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 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.
I'm a beginner in OOP PHP.
I'm trying to make a class that will connect,query and fetch data
I done the below coding
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con= mysql_connect($this->host, $this->username, $this->password);
if(!$con){ die("Couldn't connect"); }
}
public function Database($set_database)
{
$this->database=$set_database;
mysql_select_db($this->database)or die("cannot select Dataabase");
}
public function Fetch($set_table_name){
$this->table_name=$set_table_name;
$query=mysql_query("SELECT * FROM ".$this->table_name);
$result= mysql_fetch_array($query);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
what I'm trying to achieve is this
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
and I want to fetch the data using a format like this
echo $result[0];
but I'm not getting that logic to make this happen
please help
Thanks!
Your Fetch function is only pulling one row from the database, and you aren't returning the results...
The method isn't the best, but in order to achieve what you're trying to do:
public function Fetch($set_table_name){
$query=mysql_query("SELECT * FROM ".$set_table_name);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
This will make each row a part of $result, but you'll have to access it like this:
You would call the fetch function like this:
$result = $connect->Fetch('posts');
echo $result[0]['columnName']; // for row 0;
Or in a loop:
for ($x = 0; $x < count($result); $x++) {
echo $result[$x][0] . "<BR>"; // outputs the first column from every row
}
That said, fetching the entire result set into memory is not a great idea (some would say it's a very bad idea.)
Edit: It also looks like you have other issues with your class... I have to run but will check back tomorrow and if others haven't set you straight I will expand.
Edit2: Ok, going to do a once-over on your class and try to explain a few things:
class MySQL {
//declaring the private variables that you will access through $this->variable;
private $host;
private $username;
private $password;
private $database;
private $conn; // Adding the connection, more on this later.
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// Combining the connection & connection check using 'or'
// Notice that I removed the semi-colon after the mysql_connect function
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function Database($set_database)
{
$this->database=$set_database;
// Adding the connection to the function allows you to have multiple
// different connections at the same time. Without it, it would use
// the most recent connection.
mysql_select_db($this->database, $this->conn) or die("cannot select Dataabase");
}
public function Fetch($table_name){
// Adding the connection to the function and return the result object instead
return mysql_query("SELECT * FROM ".$table_name, $this->conn);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$posts = $connect->Fetch('posts');
if ($posts && mysql_num_rows($posts) > 0) {
echo "Here is some post data:<BR>";
while ($record = mysql_fetch_array($posts)) {
echo $record[0]; // or a quoted string column name instead of numerical index.
}
} else {
echo "No posts!";
}
I hope this helps... It should get you started at least. If you have more questions you should ask them separately.
That's because $result is set inside the Fetch function. It won't be available outside the Fetch function.
Instead of this line $result= mysql_fetch_array($query);, you'll want something like return mysql_fetch_array($query);.
And then in your code
$row = $connect->Fetch('posts');
// do something with $row
On another note, your Fetch function only applies to database queries that return one row. You'll have to separate the mysql_query & mysql_fetch_array calls into another function if you want to loop through rows in a query result.
And on another note, you shouldn't need to encapsulate this code into a class. PHP already provides OOP-based database classes called PDO, or PHP Data Objects. There's a learning curve to it, but it's best practice, and will help secure your code against things like SQL injection.
This is a pretty good tutorial: http://www.giantflyingsaucer.com/blog/?p=2478
I would make a function that returns the value of the object.
public function returnData($data){
return $this->$data;
}
Then within the page you wish to get the data on just initiate the class and call the function within that class.
$post->returnDate("row name here");
<?php
//database.php
class Databases{
public $con;
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "giit");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insert($table_name, $data)
{
$string = "INSERT INTO ".$table_name." (";
$string .= implode(",", array_keys($data)) . ') VALUES (';
$string .= "'" . implode("','", array_values($data)) . "')";
if(mysqli_query($this->con, $string))
{
return true;
}
else
{
echo mysqli_error($this->con);
}
}
public function selectmulti($selecttype,$table_name)
{
$array = array();
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
public function selectsingle($selecttype,$table_name)
{
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
$row = mysqli_fetch_assoc($result);
return $row;
}
}
?>
<?php
$data = new Databases;
$post_data = $data->selectmulti('*','centerdetail');
$n = 1;
foreach($post_data as $post)
{
echo $n.'.'.$post['CenterCode'].'___';
$n += 1;
}
echo '<br>';
$post_data = $data->selectsingle('*','centerdetail');
echo $post_data['CenterCode'];
?>