Why can't instantiate my object to an array[]? - php

Why can't initiate my object to an array[]?
This is my work: clothing_product.php
include('../database.php');
class Clothing_Product {
public $db;
public $procode;
public $probprice;
public $proprice;
public $prodes;
public $propath;
public $prostatus;
public $image;
public function __construct() {
$this->db = new MySqlDatabase();
}
public function get_all(){
return self::get_by_query('SELECT * FROM tblclothing_product;');
}
public function get_by_query($sql=""){
$result_set = $this->db->query($sql);
$object_array = array();
while($row = $this->db->fect_array($result_set)){
$object_array[] = $this->instantiate($row);
echo var_dump($object_array);
}
return $object_array;
}
private function instantiate($record){
//Dynamic control
$object = new self;
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)){
$object->attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute){
$object_vars = get_object_vars($this);
return array_key_exists($attribute,$object_vars);
}
public function add_new($a,$b,$c,$d,$e,$f){
$this->procode = $a;
$this->probprice = $b;
$this->proprice = $c;
$this->prodes = $d;
$this->propath = $e;
$this->prostatus = $f;
$sql="INSERT INTO `tblclothing_product`(`proCode`,`proBPrice`,`proPrice`,`proDes`,`proPath`,`proStatus`) VALUES(
'" . $a ."',
'" . $b ."',
'" . $c ."',
'" . $d ."',
'" . $e ."',
" . $f ."
)";
$this->db->query($sql);
}
public function image_string($a,$b,$c,$d,$e){
$this->image='';
if($a!=""){
$this->image = $this->image. $a .";";
}
if($b!=""){
$this->image = $this->image. $b .";";
}
if($c!=""){
$this->image = $this->image. $c .";";
}
if($d!=""){
$this->image = $this->image. $d .";";
}
if($e!=""){
$this->image = $this->image. $e;
}
return $this->image;
}
public function remove_by_id($id){
$this->db->query('DELETE FROM tblclothing_product WHERE proId={$id};');
}
public function get_by_id($id=0){
$result_array = self::get_by_query('SELECT * FROM tblclothing_product WHERE proId={$id} LIMIT 1;');
return !empty($result_array) ? array_shift($result_array) : FALSE;
}
public function image_exploit_string(){
$arr = array();
if($this->image != ""){
$arr = explode(";",$this->image);
}
return $arr;
}
}
I try to echo the above script var_dump($object_array) my array and it has shown null to every object. It looks like it can't initiate at all.
In clothing_view.php it is a script to view my array of object but it has shown null.
require_once("../include/function.php");
require_once("../include/database.php");
$buttonname = $_POST["submit"];
$image1 = '';
$image2 = '';
$image3 = '';
$image4 = '';
$image5 = '';
$image1 = $_FILES['image1']['name'];
$image2 = $_FILES["image2"]['name'];
$image3 = $_FILES["image3"]['name'];
$image4 = $_FILES["image4"]['name'];
$image5 = $_FILES["image5"]['name'];
$obj = new Clothing_Product();
$items = $obj->get_all();
foreach($items as $item){
echo "ProId:".$item->procode."<br />";
echo "ProPath:".$item->propath."<br />";
}
In database.php:
require_once('config.php');
class MySqlDatabase
{
private $connection;
private $last_query;
private $magic_quotes_active;
private $real_escape_string_exist;
function __construct(){
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exist = function_exists("mysql_real_escape_string");
}
private function open_connection()
{
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$this->connection){
die("Connection failed!". mysql_error());
}
else{
$db_select = mysql_select_db(DB_NAME);
if(!$db_select){
die("Select database failed". mysql_error());
}
}
}
public function query($sql){
$this->last_query = $sql;
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function confirm_query($result){
if(!$result){
$output = "Database query failed: " . mysql_error()."<br /><br />";
$output.= "Last query that fail is:" . $this->last_query;
die($output);
}
}
private function escape_value($value) {
if ($this->real_escape_string_exist) {
if($this->magic_quotes_active) {$value = stripslashes($value);}
$value = mysql_real_escape_string($value);
}
else {
if (!$this->magic_quotes_active) {$value = addslashes($value);}
}
return $value;
}
public function fect_array($result){
return mysql_fetch_array($result);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function last_id(){
return mysql_insert_id($this->connection);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
}
Is there problem with $item->? It always returns null.

Finally, I got what you trying to do.. If you need db result as object (ORM-like), you can use another class for this (just an advise).
Pseudo;
// Let's call another class as CProduct
class CProduct
{
public $procode, $probprice,
$proprice, $prodes,
$propath, $prostatus,
$image;
public function __construct($row) {
foreach ($row as $key => $val) {
if ($this->_hasAttr($key)) {
$this->$key = $val;
}
}
}
private function _hasAttr($key) {
return array_key_exists($key, get_class_vars($this));
}
// you can also extend your class here
// and use it anywhere
public function printCode() {
print $this->procode;
}
}
And using in your case;
while ($row = $this->db->fect_array($result_set)) {
$object_array[] = new CProduct($row);
}
Html part;
<p>Product Code: <?php $cp->printCode(); ?></p>

As far as I see, self::get_by_query will never work cos it is not defined as static function.
Opt. 1- You can define it so: public static function get_by_query
Opt. 2- You can call it so: $this->get_by_query
PS: var_dump doesn't need echo.

I think your problem is that you set the object properties in the instantiate function with
$object->attribute = $value;
instead of the likely more useful
$object->{$attribute} = $value;
Even if it does not solve your problem right away, this would likely make you pull your hair later...

Related

Using functions in PHP Method

I have a db class that I've been using for years. I noticed something interesting today.
function example_function($key)
{
global $db; // db variable - class
$a_id = 1; // example
$admins = $db->table('admins')->where('id','=',$a_id)->order('id','desc')->limit(1)->get();
$admin_data = $admins['data'][0];
$return = $admin_data[$key];
return $return;
}
$id = example_function('id');
$new = $db->table('rooms')->where('id','=',$id)->order('id','desc')->limit(2)->get();
print_r($new);
//WORKS
$new = $db->table('rooms')->where('id','=',2)->order('id','desc')->limit(2)->get();
print_r($new);
//WORKS
$new = $db->table('rooms')->where('id','=',example_function('id'))->order('id','desc')->limit(2)->get();
print_r($new);
//NOT WORKING ?
->where('id','=',example_function('id'))->
When I use an external function in this part, things get messy.
But the following also works. When doing another operation with the db in the relevant function, things get messy.
function example_function($key)
{
return '1';
}
$new = $db->table('rooms')->where('id','=',example_function('id'))->order('id','desc')->limit(2)->get();
Is the problem in global usage? Or is the database class wrong?
DB CLASS
class DB
{
protected $connect;
protected $db_database = DB_DATABASE;
protected $db_host = DB_HOST;
protected $db_username = DB_USERNAME;
protected $db_password = DB_PASSWORD;
protected $db_name = DB_NAME;
protected $db_prefix = DB_PREFIX;
//parameters
protected $error = null;
protected $last_id = null;
protected $query = null;
protected $from = null;
protected $select = '*';
protected $where = null;
protected $group = null;
protected $order = null;
protected $limit = null;
protected $pagination_type = false;
protected $per_page = 0;
protected $get_arr = null;
function __construct()
{
try {
$this->connect = new PDO("{$this->db_database}:host={$this->db_host};dbname={$this->db_name};charset=utf8mb4", "{$this->db_username}", "{$this->db_password}");
$this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connect->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8mb4");
} catch ( PDOException $e ){
echo "<b>Veritabanı bağlantısı sağlanamadı! - Hata Kodu: </b>".$e->getMessage();
exit;
}
}
public function now($type="datetime")
{
switch($type)
{
case 'timestamp';
return time();
case 'date';
return date('-m-d');
case 'datetime';
return date('Y-m-d H:i:s');
default:
return date('Y-m-d H:i:s');
}
}
public function m_empty($data)
{
if($data=='' and $data!='0')
{
return true;
}
else
{
return false;
}
}
public function query($query,$arr=false)
{
$this->reset();
if($query!="")
{
try
{
$run = $this->connect->prepare($query);
if($arr)
{
if(is_array($arr))
{
$run->execute($arr);
return $run;
}
else
{
$run->execute(array($arr));
return $run;
}
}
else
{
$run->execute();
return $run;
}
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
return false;
}
public function table($table)
{
$this->from = $this->db_prefix . $table;
return $this;
}
public function select($fields)
{
$this->select = $fields;
return $this;
}
public function where($field,$op='=',$values,$and="AND")
{
if(!$this->m_empty($field))
{
if(is_null($this->where))
{
$this->where="{$field} {$op} ?";
$this->get_arr[] = $values;
}
else
{
$this->where.=" {$and} {$field} {$op} ?";
$this->get_arr[] = $values;
}
}
return $this;
}
public function where_set($field,$op='=',$values,$and="AND")
{
if(!$this->m_empty($field) and !$this->m_empty($values))
{
if(is_null($this->where))
{
$this->where="{$field} {$op} {$values}";
}
else
{
$this->where.=" {$and} {$field} {$op} {$values}";
}
}
return $this;
}
public function group($fields)
{
if(is_null($this->group))
{
$this->group = $fields;
}
else
{
$this->group .=",{$fields}";
}
return $this;
}
public function order($field,$type="desc")
{
if(!is_null($field))
{
if(is_null($this->order))
{
if(strtolower($field)=="rand()")
{
$this->order = $field;
}
else
{
$this->order = $field.' '.strtoupper($type);
}
}
else
{
if(strtolower($field)=="rand()")
{
$this->order .=",{$fields}";
}
else
{
$this->order .= ','.$field.' '.strtoupper($type);
}
}
}
return $this;
}
public function limit($start,$end=null)
{
if(is_null($end))
{
if(is_numeric($start))
{
$this->limit = $start;
}
}
else
{
if(is_numeric($start) and is_numeric($end))
{
$this->limit = "{$start},{$end}";
}
}
return $this;
}
public function pagination($per_page)
{
if(is_numeric($per_page))
{
$this->per_page = $per_page;
$this->pagination_type = true;
}
return $this;
}
public function get()
{
$query = "SELECT {$this->select} FROM {$this->from}";
if(!is_null($this->where))
{
$query.=" where {$this->where}";
}
if(!is_null($this->group))
{
$query.=" group by {$this->group}";
}
if(!is_null($this->order))
{
$query.=" order by {$this->order}";
}
if($this->pagination_type)
{
$c_per_page = $this->per_page;
$c_arr = $this->get_arr;
$extra_query = preg_replace("#SELECT (.*?) FROM#","SELECT COUNT(*) as total_count FROM",$query);
$all = $this->query($extra_query,$this->get_arr);
if($all)
{
$total_count = $all->fetchAll(PDO::FETCH_ASSOC)[0]['total_count'];
$page_count = ceil($total_count/$c_per_page);
$current_page = (integer)m_u_g(DB_PAGINATION_GET) ? (integer)m_u_g(DB_PAGINATION_GET) : 1;
$current_limit=($current_page - 1) * $c_per_page;
$query = $query." limit {$current_limit},{$c_per_page}";
$current_rows = $this->query($query,$c_arr);
$data = $current_rows->fetchAll(PDO::FETCH_ASSOC);
$return = array();
$return['total_count'] = $total_count;
$return['current_count'] = count($data);
$return['total_page'] = $page_count;
$return['current_page'] = $current_page;
$return['data'] = $data;
return $return;
}
else
{
return false;
}
}
else
{
if(!is_null($this->limit))
{
$query.=" limit {$this->limit}";
}
$gets = $this->query($query,$this->get_arr);
if($gets)
{
$data = $gets->fetchAll(PDO::FETCH_ASSOC);
$return = array();
$return["total_count"] = count($data);
$return["data"] = $data;
return $return;
}
else
{
return false;
}
}
}
public function get_var($field)
{
if($this->m_empty($field))
{
return false;
}
else
{
$query = "SELECT {$field} FROM {$this->from}";
if(!is_null($this->where))
{
$query.=" where {$this->where}";
}
if(!is_null($this->order))
{
$query.=" order by id desc limit 1";
}
$gets = $this->query($query,$this->get_arr);
if($gets)
{
return $gets->fetchAll(PDO::FETCH_ASSOC)[0][$field];
}
else
{
return false;
}
}
}
public function get_vars($table,$where,$var,$type=true)
{
if($type)
{
$data = $this->connect->query("select $var from $table where $where order by id desc limit 1")->fetch(PDO::FETCH_ASSOC);
}
else
{
$data = $this->connect->query("select $var from $table where $where")->fetch(PDO::FETCH_ASSOC);
}
return $data["$var"];
}
public function count()
{
$grouped = false;
$query = "SELECT count(*) as total_count FROM {$this->from}";
if(!is_null($this->where))
{
$query.=" where {$this->where}";
}
if(!is_null($this->group))
{
$grouped = true;
$query.=" group by {$this->group}";
}
if(!is_null($this->order))
{
$query.=" order by {$this->order}";
}
$gets = $this->query($query,$this->get_arr);
if($gets)
{
if($grouped)
{
$count = 0;
foreach($gets->fetchAll(PDO::FETCH_ASSOC) as $counts)
{
$count = $count+$counts["total_count"];
}
return $count;
}
else
{
return $gets->fetch(PDO::FETCH_ASSOC)["total_count"];
}
}
else
{
return false;
}
}
public function insert(array $data)
{
if(is_array($data))
{
$query = 'INSERT INTO '.$this->from;
$keys = array_keys($data);
$query.=' ('.implode(',',$keys).') values (';
$query_add='';
$values = array_values($data);
foreach($values as $val)
{
$query_add.='?,';
}
$query_add = trim($query_add,',');
$query.=$query_add.')';
if($this->query($query,$values))
{
$this->last_id = $this->connect->lastInsertId();
return $this->last_id;
}
else
{
return false;
}
}
return false;
}
public function update(array $data)
{
if(is_array($data))
{
$query = "UPDATE {$this->from} set";
$keys = array_keys($data);
$values = array_values($data);
$query_add = '';
foreach($keys as $key)
{
$query_add.=" {$key} = ?,";
}
$query_add = trim($query_add,',');
$query.=$query_add;
if(!is_null($this->where))
{
$query.=" where {$this->where}";
}
$new = array_merge($values,$this->get_arr);
if($this->query($query,$new))
{
return true;
}
else
{
return false;
}
}
return false;
}
public function delete()
{
$query = "DELETE FROM {$this->from}";
if(!is_null($this->where))
{
$query.=" where {$this->where}";
}
if($this->query($query,$this->get_arr))
{
return true;
}
else
{
return false;
}
}
public function error()
{
return $this->error;
}
public function last_id()
{
return $this->last_id;
}
protected function reset()
{
$this->error = null;
$this->last_id = null;
$this->query = null;
$this->from = null;
$this->select = '*';
$this->where = null;
$this->group = null;
$this->order = null;
$this->limit = null;
$this->pagination_type = false;
$this->per_page = 0;
$this->get_arr = null;
}
}
$db = new DB();
?>```
The issue is caused by changing the mutable object properties prior to completing the desired query with Db::get(). Resulting in the Db::$table property being changed when being called on the same instance of the Db class.
This is one of the reasons behind best-practices discouraging the use of global, since the intention/context of the current variable state is not easily determined.
What's happening with your code is
Db::$table = 'rooms'
Db::$table = 'admin'
Db::$where = 'admin.id = 1'
Db::get() //SELECT * FROM admin WHERE admin.id = 1
Db::$table = null
Db::$where = null
Db::$where = 'rooms.id = 1'
Db::get() //SELECT * FROM WHERE rooms.id = 1
To avoid the issue and ensure the desired order of operations, you need to call Db::get() prior to calling any other DB methods that modify the properties of the query issued when calling DB::get().
$roomId = example_function('id'); // (int) 1
//SELECT * FROM admin WHERE id = 1
$db->table('rooms')->where('id','=', $roomId)->get();
//SELECT * FROM rooms WHERE id = 1
Alternatively, to ensure that the intention of two individual queries is preserved, you would need to create a separate instance of DB for your second query. However, this would also create a separate PDO instance with your current code.
To avoid a second instance of PDO you would have to change $this->connect to a static property self::$connect and refactor any method using $this->connect to self::$connect. The static property will ensure that only a single instance of PDO will ever exist whenever new Db() is called.
class Db
{
protected static $connect;
//...
public function __construct()
{
try {
if (!isset(self::$connect)) {
self::$connect = new PDO("{$this->db_database}:host={$this->db_host};dbname={$this->db_name};charset=utf8mb4", "{$this->db_username}", "{$this->db_password}");
self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$connect->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8mb4");
}
} catch ( PDOException $e ){
echo "<b>Veritabanı bağlantısı sağlanamadı! - Hata Kodu: </b>".$e->getMessage();
exit;
}
}
//...
}
Afterwards replace all usages of global $db; in your application with $db = new Db();.
This approach will also ensure your entire codebase is protected from the mutable object property overwrite issue and better adheres to best-practices.
function example_function($key)
{
$db = new Db();
$a_id = 1; // example
$admins = $db->table('admins')->where('id','=',$a_id)->order('id','desc')->limit(1)->get();
$admin_data = $admins['data'][0];
$return = $admin_data[$key];
return $return;
}
$new = $db->table('rooms')->where('id','=', example_function('id'))->get();
Another approach could be to use clone to workaround the mutable object issue. However, using clone will have adverse affects on the PDO instance, since it resides in the Db class. Most likely requiring you to separate the PDO connection code from the Query Builder code.
function example_function($key)
{
global $db;
$db2 = clone $db;
$a_id = 1; // example
$admins = $db2->table('admins')->where('id','=',$a_id)->order('id','desc')->limit(1)->get();
//...
}

Why cant work roting, when i get id with php7 in db

In my project db connection works, because I can get all info at db and can it record into db. Routs are working too, when I write in adress input a word "/blog", but when I write "/blog/1" or some other numbers it doesn't work.
class "Router"
<?php
class Router
{
private $routes;
public function __construct(){
$routesPath = ROOT.'/config/routes.php';
$this->routes = include($routesPath);
}
private function getURI(){
if (!empty($_SERVER['REQUEST_URI'])) {
return trim($_SERVER['REQUEST_URI'], '/');
}
}
public function run (){
$uri = $this->getURI();
foreach ($this->routes as $uriPattern=>$path) {
if (preg_match("~$uriPattern~", $uri)) {
$internalRoute = preg_replace("~$uriPattern~", $path, $uri);
$segments = explode('/', $internalRoute);
$controllerName = array_shift($segments).'Controller';
$controllerName = ucfirst($controllerName);
$actionName = 'action'.ucfirst(array_shift($segments));
$parameters = $segments;
$controllerFile = ROOT . '/controllers/' .
$controllerName . '.php';
if (file_exists($controllerFile)) {
include_once ($controllerFile);
}
$controllerObject = new $controllerName;
$result = call_user_func_array(array($controllerObject, $actionName), $parameters);
if ($result != null) {
break;
}
}
}
}
}
class BlogController
<?php
include_once ROOT. '/models/Blog.php';
class BlogController
{
public function actionIndex() {
$recordsList = array();
$recordsList = Blog::getRecordsList();
echo '<pre>';
print_r($recordsList);
echo '</pre>';
echo 'Read more >';
return true;
}
public function actionView($id){
if($id) {
$recordsItem = Blog::getRecordsItemById($id);
echo '<pre>';
print_r($recordsItem);
echo '</pre>';
}
echo '< Back ';
return true;
}
}
class model 'Blog'
<?php
class Blog
{
public static function getRecordsItemById($id){
$id = intval($id);
if ($id) {
$db = Database::getConnection();
$result = $db->query('SELECT * FROM `blog_records` WHERE `id` ='.$id);
$result->setFetchMode(PDO::FETCH_ASSOC);
$recordsItem = $result->fetch();
return $recordsItem;
return $result;
}
}
public static function getRecordsList() {
$db = Database::getConnection();
$recordsList=array();
$result = $db->query('SELECT * FROM `blog_records`'
. 'ORDER BY reg_date DESC');
$i = 0;
while ($row = $result->fetch()) {
$recordsList[$i] ['id'] = $row['id'];
$recordsList[$i] ['name'] = $row['name'];
$recordsList[$i] ['content'] = $row['content'];
$recordsList[$i] ['reg_date'] = $row['reg_date'];
$i++;
}
return $recordsList;
}
}

Object of class Database could not be converted to string

i'm using this methode to get data from db
class Database {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct() {
try {
$this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
} catch (PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new Database();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()) {
if (count($where) === 3) {
$operators = array('=','>','<','>=','<=','<>');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE ${field} {$operator} ?";
if (!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where) {
return $this->action('DELETE', $table, $where);
}
public function insert($table, $fields = array()) {
if (count($fields)) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach ($fields as $field) {
$values .= '?';
if ($x<count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`".implode('`,`', $keys)."`) VALUES({$values})";
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
public function update($table, $id, $fields = array()) {
$set = '';
$x = 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if ($x<count($fields)) {
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if (!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function results() {
return $this->_results;
}
public function first() {
return $this->_results[0];
}
public function error() {
return $this->_error;
}
public function count() {
return $this->_count;
}
}
this is what i want to get AND
this is my table
this is my code ...
public function getModule() {
$epreuve = $this->_db->get('epreuve', array('concour_code', '=', $this->data()->concour_code));
foreach($epreuve->results() as $epreuve){
echo "<tr><td>".$epreuve->designation."</td>"
.$module = $this->_db->get('module', array('epreuve_code', '=', $epreuve->code ));
foreach($module->results() as $module){
echo "<tr><td>".$epreuve->designation."</td>";
}
"</tr>";
}
}
but i have this error
'' Catchable fatal error: Object of class Database could not be converted to string ''
The error seems to be here:
echo "<tr><td>".$epreuve->designation."</td>"
.$module = $this->_db->get('module', array('epreuve_code', '=',
Note that you did not close echo with semi colon, and there is a dot before $module, so PHP is trying to string concat echo string with $module class plus the iteration also inside the concatenation. You cant do that.
Do the following:
public function getModule() {
$epreuve = $this->_db->get('epreuve', array('concour_code', '=', $this->data()->concour_code));
foreach($epreuve->results() as $epreuve){
echo "<tr>";
echo "<td>".$epreuve->designation."</td>";
$module = $this->_db->get('module', array('epreuve_code', '=', $epreuve->code ));
foreach($module->results() as $module){
echo "<td>".$epreuve->designation."</td>";
}
echo "</tr>";
}
}
Suggesiton:
On your code
foreach($epreuve->results() as $epreuve){
AND
foreach($module->results() as $module){
You should not use the same variable name of what you are iterating. Try change it to
public function getModule() {
$epreuve = $this->_db->get('epreuve', array('concour_code', '=', $this->data()->concour_code));
foreach($epreuve->results() as $epreu){
echo "<tr>";
echo "<td>".$epreu->designation."</td>";
$module = $this->_db->get('module', array('epreuve_code', '=', $epreu->code ));
foreach($module->results() as $mod){
echo "<td>".$epreu->designation."</td>";
}
echo "</tr>";
}
}
NOTE: The HTML table is a bit messy I tried by best to understand it. Change it to your needs.

php class _Construct empty

<?
session_start();
/*
echo $_SESSION['SQLIP'];
echo "<br>";
echo $_SESSION['SQLDB'];
echo "<br>";
echo $_SESSION['SQLUSER'];
echo "<br>";
echo $_SESSION['SQLPASS'];
echo "<br>";
*/
class DB_MSSQL {
private $Host;
private $Database;
private $User;
private $Password;
public $Link_ID = 0;
public $Query_ID = 0;
public $Record = array();
public $Row = 0;
public $Errno = 0;
public $Error = "";
public $Halt_On_Error = "yes";
public $Auto_Free = 1;
public $PConnect = 0;
public function _construct(){
$this->Host = $_SESSION['SQLIP'];
$this->Database = $_SESSION['SQLDB'];
$this->User = $_SESSION['SQLUSER'];
$this->Password = $_SESSION['SQLPASS'];
}
function DB_MSSQL($query = "") {
if($query) {
$this->query($query);
}
}
function connect() {
if ( 0 == $this->Link_ID ) {
if(!$this->PConnect) {
$this->Link_ID = mssql_connect($this->Host, $this->User, $this->Password);
} else {
$this->Link_ID = mssql_pconnect($this->Host, $this->User, $this->Password);
}
if (!$this->Link_ID)
$this->connect_failed("connect ($this->Host, $this->User, \$Password) failed");
else
if (!mssql_select_db($this->Database, $this->Link_ID)) {
$this->connect_failed("cannot use database ".$this->Database);
}
}
}
function connect_failed($message) {
$this->Halt_On_Error = "yes";
$this->halt($message);
}
function free_result(){
mssql_free_result($this->Query_ID);
$this->Query_ID = 0;
}
function query($Query_String)
{
/* No empty queries, please, since PHP4 chokes on them. */
if ($Query_String == "")
/* The empty query string is passed on from the constructor,
* when calling the class without a query, e.g. in situations
* like these: '$db = new DB_Sql_Subclass;'
*/
return 0;
if (!$this->Link_ID)
$this->connect();
// printf("<br>Debug: query = %s<br>\n", $Query_String);
$this->Query_ID = mssql_query($Query_String, $this->Link_ID);
$this->Row = 0;
if (!$this->Query_ID) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Invalid SQL: ");
}
return $this->Query_ID;
}
function next_record() {
if ($this->Record = mssql_fetch_row($this->Query_ID)) {
// add to Record[<key>]
$count = mssql_num_fields($this->Query_ID);
for ($i=0; $i<$count; $i++){
$fieldinfo = mssql_fetch_field($this->Query_ID,$i);
$this->Record[strtolower($fieldinfo->name)] = $this->Record[$i];
}
$this->Row += 1;
$stat = 1;
} else {
if ($this->Auto_Free) {
$this->free_result();
}
$stat = 0;
}
return $stat;
}
function seek($pos) {
mssql_data_seek($this->Query_ID,$pos);
$this->Row = $pos;
}
function metadata($table) {
$count = 0;
$id = 0;
$res = array();
$this->connect();
$id = mssql_query("select * from $table", $this->Link_ID);
if (!$id) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Metadata query failed.");
}
$count = mssql_num_fields($id);
for ($i=0; $i<$count; $i++) {
$info = mssql_fetch_field($id, $i);
$res[$i]["table"] = $table;
$res[$i]["name"] = $info->name;
$res[$i]["len"] = $info->max_length;
$res[$i]["flags"] = $info->numeric;
}
$this->free_result();
return $res;
}
function affected_rows() {
// Not a supported function in PHP3/4. Chris Johnson, 16May2001.
// return mssql_affected_rows($this->Query_ID);
$rsRows = mssql_query("Select ##rowcount as rows", $this->Link_ID);
if ($rsRows) {
return mssql_result($rsRows, 0, "rows");
}
}
function num_rows() {
return mssql_num_rows($this->Query_ID);
}
function num_fields() {
return mssql_num_fields($this->Query_ID);
}
function nf() {
return $this->num_rows();
}
function np() {
print $this->num_rows();
}
function f($Field_Name) {
return $this->Record[strtolower($Field_Name)];
}
function p($Field_Name) {
print $this->f($Field_Name);
}
function halt($msg) {
if ("no" == $this->Halt_On_Error)
return;
$this->haltmsg($msg);
if ("report" != $this->Halt_On_Error)
die("Session halted.");
}
function haltmsg($msg) {
printf("<p>Server have a critical error!<br><br><br>We are very sorry for any inconvenience!<br><br>\n", $msg);
printf("<b>MSSQL Error</b>: %s (%s)</p>\n",
$this->Errno,
$this->Error);
}
}
$_php_major_version = substr(phpversion(), 0, 1);
if((4 > $_php_major_version) or !class_exists("DB_Sql"))
{
class DB_Sql extends DB_MSSQL
{
function DB_Sql($query = "")
{
$this->DB_MSSQL($query);
}
}
}
unset($_php_major_version);
?>
I have a question, why on DB_MSSQL my $Host,$Datebase,$User,$Password are empty?
If i test $_SESSIONS Between DB_MSSQL are OK.
Class don't have errors but this variables are empty... and i don't know why..
Can anybody help me?
Thank you verry much!
You have missed one underscore, you should have write :
public function __construct()
It should work like this.

How to display MySQL select statements in PHP / HTML

The MySQL selects are not displaying properly in the PHP / HTML
This is my code:
<?php
session_start();
require_once("database.php");
require_once("MySQL_connection.php");
/* Database connection */
$db = new MySQLConnection($config['sql_host'], $config['sql_username'], $config['sql_password'], $config['sql_database']);
$db->Connect();
unset($config['sql_password']);
/* Cron */
require_once("cron.php");
/* Display Advert */
$ad_link = $db->Query("SELECT `site_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;");
$img_link = $db->Query("SELECT `image_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;");
?>
<!DOCTYPE html>
<html>
<body>
<img src="<? echo $img_link ?>">
</body>
</html>
For some reason that is displaying as:
<html><head></head><body>
<img src="Resource id #7">
</body></html>
Is anybody know what is wrong?
Forgot to add the code for MYSQL_connection.php, the following code is everything within that file that is used to connect to the DB.
<?php
class MySQLConnection {
private $sqlHost;
private $sqlUser;
private $sqlPassword;
private $sqlDatabase;
private $mySqlLinkIdentifier = FALSE;
public $QueryFetchArrayTemp = array();
private $numQueries = 0;
public $UsedTime = 0;
public function __construct($sqlHost, $sqlUser, $sqlPassword, $sqlDatabase = FALSE) {
$this->sqlHost = $sqlHost;
$this->sqlUser = $sqlUser;
$this->sqlPassword = $sqlPassword;
$this->sqlDatabase = $sqlDatabase;
}
public function __destruct() {
$this->Close();
}
public function Connect() {
if($this->mySqlLinkIdentifier !== FALSE) {
return $this->mySqlLinkIdentifier;
}
$this->mySqlLinkIdentifier = mysql_connect($this->sqlHost, $this->sqlUser, $this->sqlPassword, TRUE); // Open new link on every call
if($this->mySqlLinkIdentifier === FALSE) {
return FALSE;
}
if($this->sqlDatabase !== FALSE) {
mysql_select_db($this->sqlDatabase, $this->mySqlLinkIdentifier);
}
return $this->mySqlLinkIdentifier;
}
public function Close() {
if($this->mySqlLinkIdentifier !== FALSE) {
mysql_close($this->mySqlLinkIdentifier);
$this->mySqlLinkIdentifier = FALSE;
}
}
public function GetLinkIdentifier() {
return $this->mySqlLinkIdentifier;
}
public function Query($query) {
$start = microtime(true);
$result = mysql_query($query, $this->GetLinkIdentifier());
$this->UsedTime += microtime(true) - $start;
$this->numQueries++;
if( $result === false ){
die($this->GetErrorMessage());
}
return $result;
}
public function FreeResult($result) {
mysql_free_result($result);
}
public function FetchArray($result) {
return mysql_fetch_array($result, MYSQL_ASSOC);
}
public function FetchArrayAll($result){
$retval = array();
if($this->GetNumRows($result)) {
while($row = $this->FetchArray($result)) {
$retval[] = $row;
}
}
return $retval;
}
public function GetNumRows($result) {
return mysql_num_rows($result);
}
public function GetNumAffectedRows() {
return mysql_affected_rows($this->mySqlLinkIdentifier);
}
// Helper methods
public function QueryFetchArrayAll($query) {
$result = $this->Query($query);
if($result === FALSE) {
return FALSE;
}
$retval = $this->FetchArrayAll($result);
$this->FreeResult($result);
return $retval;
}
public function QueryFirstRow($query) {
$result = $this->Query($query);
if($result === FALSE) {
return FALSE;
}
$retval = FALSE;
$row = $this->FetchArray($result);
if($row !== FALSE) {
$retval = $row;
}
$this->FreeResult($result);
return $retval;
}
public function QueryFirstValue($query) {
$row = $this->QueryFirstRow($query);
if($row === FALSE) {
return FALSE;
}
return $row[0];
}
public function GetErrorMessage() {
return "SQL Error: ".mysql_error().": ";
}
public function EscapeString($string) {
if (is_array($string))
{
$str = array();
foreach ($string as $key => $value)
{
$str[$key] = $this->EscapeString($value);
}
return $str;
}
return get_magic_quotes_gpc() ? $string : mysql_real_escape_string($string, $this->mySqlLinkIdentifier);
}
function GetNumberOfQueries() {
return $this->numQueries;
}
public function BeginTransaction() {
$this->Query("SET AUTOCOMMIT=0");
$this->Query("BEGIN");
}
public function CommitTransaction() {
$this->Query("COMMIT");
$this->Query("SET AUTOCOMMIT=1");
}
public function RollbackTransaction() {
$this->Query("ROLLBACK");
$this->Query("SET AUTOCOMMIT=1");
}
public function GetFoundRows() {
return $this->QueryFirstValue("SELECT FOUND_ROWS()");
}
public function GetLastInsertId() {
return $this->QueryFirstValue("SELECT LAST_INSERT_ID()");
}
public function QueryFetchArray($query, $all = false, $useCache = true)
{
$tempKey = sha1($query . ($all === true ? 'all' : 'notAll'));
$temp = $this->QueryFetchArrayTemp[$tempKey];
if ($temp && $useCache === true)
{
return unserialize($temp);
}
else
{
$queryResult = $this->Query($query);
$result = $all === true ? $this->FetchArrayAll($queryResult) : $this->FetchArray($queryResult);
$this->QueryFetchArrayTemp[$tempKey] = serialize($result);
return $result;
}
}
}
?>
Using your custom MySQL class, this will probably work:
$result = $db->Query("SELECT `site_url`,`image_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;");
while($row = $db->FetchArray($result)) {
echo '<img src="' . $row['image_url'] . '">';
}
$db->FreeResult($result);
However, as others have pointed out, the code used in your custom MySQL class is deprecated and should be updated to use newer php methods/libraries.
You are using some custom MySQL wrapper, but you probably should fetch the result from the query using mysql_result(), mysql_fetch_array() or similar.
You would do well to read up on mysqli, which is a safer way to carry out MySQL queries. You can find the excellent documentation here: http://php.net/manual/en/book.mysqli.php and there is also a very useful tutorial here which covers simple queries like yours: http://www.phphaven.com/article.php?id=65
For your specific question, I would use the following:
$query = "SELECT `site_url`,`image_url` FROM `adverts` WHERE `zone`=1 AND `days`>0 ORDER BY RAND() LIMIT 0,1;";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// I've split these lines up to make them a little more readable.
echo '<a href="';
echo $row['site_url'];
echo '">';
echo '<img src="';
echo $row['image_url'];
echo '"</img></a>';
}
}
else {
echo 'NO RESULTS';
}
I hope this helps.

Categories