How to print array? - php

I'm trying to learn how to print results from a query, but I'm getting confused.
Config Table:
site_id | site_name | site_description
1 Test Testing
Config:
private $hostname = 'localhost';
private $username = 'blah';
private $password = 'blah';
private $database = 'blah';
public function __construct()
{
$this->connection = new mysqli($this->hostname,$this->username,$this->password,$this->database);
if($this->connection->connect_errno)
{
die('Error: ' . $this->connection->error);
}
}
public function query($query)
{
return $this->connection->query($query);
}
public function __destruct()
{
$this->connection->close();
}
Code #1:
public function __construct()
{
$this->db = new Config;
$si = $this->db->query('SELECT * FROM config');
while($site_if = $si->fetch_array())
{
$this->site_info[] = $site_if;
}
}
public function getSiteName()
{
echo $this->site_info['site_name'];
}
This prints nothing.
Code #2:
public function __construct()
{
$this->db = new Config;
$si = $this->db->query('SELECT * FROM config');
while($site_if = $si->fetch_array())
{
$this->site_name_info = $site_if['site_name'];
}
}
public function getSiteName()
{
echo $this->site_name_info;
}
This prints the info, but is it the correct approach? Is there a way to print with Code #1?
All I want to do is echo site name. There is only one site name.

Without more info about your config table design the only think I can suggest is something like that:
while($site_if = $si->fetch_array())
{
$this->site_info[$site_if["NAME_COLUMN_NAME"]] = $site_if["VALUE_COLUMN_NAME"];
}
NAME_COLUMN_NAME and VALUE_COLUMN_NAME have to be replaced with column names from your table design.
After that you'll be able to get custom config parameter from $this->site_info array by it's name, eg.
public function getSiteName()
{
echo $this->site_info['site_name'];
}

In example #1, $this->site_info contains an array of arrays. To simply see the contents:
print_r($this->site_info);
To loop over the contents, printing the names of each row:
foreach ($this->site_info as $row){
echo $row['site_name'];
}

Related

Why isn't the array I return in my __construct class available in the following function?

I've written a class which in the construct accesses the db and gets a list of names. These names go into an associative array e.g. ('name' => 'id').
i.e. the point is to pass in the name to get back an ID:
$id = names::nameToId('some name');
print $id;
// prints int
The problem is when I try and return the array from the construct I get an error:
Notice: Undefined variable: nameArray in (etc)
Here is the code so far:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while($row = mysqli_fetch_assoc($res)) {
$nameArray[$row['name']] = $row['id'];
}
return $nameArray;
}
static public function nameToId($name) {
$nameId = $nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;
Why doesn't $nameArray get passed to nameToId()? I'm new to classes, and I thought by declaring $nameArray as public when I first create the class that it would make it available. I have also tried to make it global even though I know that is not good form but even still it didn't work.
Because you cannot return anything from a constructor. Any return value is being ignored and just goes into the aether. $nameArray is a local variable and is not shared in any other scope, i.e. you can't access it in nameToId. Further, since nameToId is static, it won't have access to data from any non-static methods like __construct to begin with.
You probably want something like this:
class nameToId {
public $nameArray;
private $mysqli;
public function __construct($mysqli) {
...
while ($row = mysqli_fetch_assoc($res)) {
$this->nameArray[$row['name']] = $row['id'];
}
}
public function nameToId($name) {
return $this->nameArray[$name];
}
}
$namesToId = new nameToId($mysqli);
echo $namesToId->nameToId('some name');
Fix your code:
class nameToId {
public static $nameArray;
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
$sql = 'SELECT id, name FROM teams';
$res = mysqli_query($this->mysqli,$sql);
while($row = mysqli_fetch_assoc($res)) {
self::$nameArray[$row['name']] = $row['id'];
}
}
static public function nameToId($name) {
$nameId = self::$nameArray[$name];
return $nameId;
}
}
$namesToId = new nameToId($mysqli);
$nameId = $namesToId::nameToId('some name');
echo $nameId;

How can I complete my dropdown with database data?

I'm building an application based on Slim Framework, and I already have some working code. To return a JSON response with a list of projects, I wrote the following:
Controller class (controllerProyectos.php)
<?php
require "transferController/transferProyectos.php";
class NombreProyecto {
public function getProyectos() {
$list = array();
foreach ($this->fillObject() as $sKey => $oValue) {
$list[] = array(
'id' => $oValue->getId(),
'nombre_proyecto' => $oValue->getNombre(),
'state' => $oValue->getState(),
);
}
return $list;
}
private function fillObject() {
$aObjects = array();
for ($i = 0; $i < 5; $i++) {
$oTransfer = new TransferProyeCtr();
$oTransfer->setId($i);
$oTransfer->setNombre("proyecto " . $i);
$oTransfer->setState(1);
$aObjects[] = $oTransfer;
}
return $aObjects;
}
}
Front controller (index.php)
<?php
require "vendor/autoload.php";
$sPathApi = "/api/sistemaTareas/";
$app = new \Slim\Slim();
$app->get($sPathApi . $sVersion . 'proyectos', function () {
require "controller/controllerProyectos.php";
$oProyecto = new NombreProyecto();
header('Content-Type: application/json');
echo json_encode($oProyecto->getProyectos());
exit();
});
Model class (transferProyectos.php)
<?php
class TransferProyeCtr {
private $sNombre;
private $iId;
private $iState;
public function getNombre() {
return $this->sNombre;
}
public function setNombre($nombre) {
$this->sNombre = $nombre;
}
public function getId() {
return $this->iId;
}
public function setId($Id) {
$this->iId = $Id;
}
public function getState() {
return $this->iState;
}
public function setState($state) {
$this->iState = $state;
}
}
As you can see I'm using some mockup data in the controller. When I do an AJAX request to my application, I get the following result in a dropdown:
- proyecto 1
- proyecto 2
- proyecto 3
- proyecto 4
- proyecto 5
So far everything is working as expected. But I'd like to return real data from the database in that controller.
I wrote a function (inside bdconnection.php file) to open the database connection:
<?php
function connect_db() {
$server = 'localhost';
$user = 'root';
$pass = '123asd';
$database = 'bd_actividades';
$connection = new mysqli($server, $user, $pass, $database);
return $connection;
}
I think that in my controller I need something like:
public function getPro() {
require "sistema/bdconnection.php";
$sql = "select pro_nombre FROM act_proyecto";
try {
$db = connect_db();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
And replace $oTransfer->setNombre("proyecto " . $i); for $oTransfer->setNombre($users);, but I'm not sure.
Just to give you guys a little more detail about my application, here will go the files structure and database data:

Class with a db query, extending, functions and views. Am I doing it right way?

I have just a little progress in practicing. Most of my code works but I am not sure if I do things the right way?
Please, can you tell me if I do mistakes and correct me.
First, I create autoload functions:
function autoload_models($model) {
if (file_exists(MODELS_PATH . $model . '.php')) {
require_once MODELS_PATH . $model . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_models');
function autoload_controllers($controller) {
if (file_exists(CONTROLLERS_PATH . $controller . '.php')) {
require_once CONTROLLERS_PATH . $controller . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_controllers');
I have a class like this:
class Category {
public $db;
public $rows;
public $id;
public function build_category() {
global $db;
global $rows;
$db = new Database();
$db->query("SELECT * from categories");
$rows = $db->resultset();
}
public function category_items() {
global $db;
global $rows;
global $id;
$db = new Database();
$db->query("SELECT * from posts WHERE category_id = '$id'");
$rows = $db->resultset();
}
}
I extend with another class (still have some issues here. Nothing prints):
class Category_Items extends Category {
public $db;
public $rows;
public $id;
public function display_category_items() {
// Call the parent class function
parent::category_items();
global $rows;
global $id;
// Check if the page parameter is integer
if (ctype_digit($_GET['id'])) {
$id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
foreach ($rows as $row) {
print "test";
print $row['post_title']; // This does not work yet. Nothing prints
}
}
}
Class for building a menu with categories (Everything works here):
class Categories_Menu extends Category {
public $db;
public $rows;
public function build_category_menu() {
parent::build_category();
global $rows;
foreach ($rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
And finally instances:
$category_menu = new Categories_Menu();
$category_menu->build_category_menu();
$category_items = new Category_Items();
$category_items->display_category_items();
Thank you for your time and help!
Where do the global variables come from?
Anyway, you should get rid of them.
I guess your rows var does not get changed, after any interaction. Using globals also will not be relevant in extending classes.
Your public properties and globals mentioned, does no interact each other. Thus, the object members seems to be totally useless.
What I would suggest in simple schems would be
class Model {
protected $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
class Category extends Model {
public $_rows;
public $_id;
public function build_category() {
$this->_db->query("SELECT * from categories");
$this->_rows = $this->_db->resultset();
}
public function category_items() {
$this->_db->query("SELECT * from posts WHERE category_id = '{$this->_id}'");
$this->_rows = $this->_db->resultset(); // here you will overwrite $_rows ?
}
class Categories_Menu extends Category {
public $_rows;
public function build_category_menu() {
$this->build_category();
foreach ($this->_rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
class Category_Items extends Category {
public $_rows;
public $_id;
public function display_category_items() {
if (ctype_digit($_GET['id'])) { // just intval it, or use is_int?
$this->_id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
// You assign value to $_id, then call the function that requires it
$this->category_items();
foreach ($this->_rows as $row) {
print "test";
print $row['post_title'];
}
}
}

php class is not working

why my code is not working here I think I made something wrong but I just can not determine it if anyone can spot what I have made wrong here I will be thankfull
here is my code: I am trying here to use php class to insert new row in the database
<?php
$connection = new PDO('mysql:dbname=master;host=localhost','root','123');
/*if($connection)
{
echo 'Database is connected successfully';
}
else
{
echo 'please connect to a database';
}*/
class Topics
{
public $id;
public $title;
public $body;
public static $table_name = 'topics';
public static $fields = array ('title','body');
private function attributes()
{
$string = array();
foreach (self::$fields as $field)
{
if (!empty($field)) {
if(is_int($this->$field))
{
$string[] = $field." =".$this->$field;
}
else
{
$string[] = $field." ="."'".$this->$field."'";
}
}
}
return join(',', $string);
}
public function add()
{
global $connection;
$sql = 'INSERT INTO'.self::$table_name.'SET'.$this->attributes();
$number_of_affected_rows = $connection->exec($sql);
if($number_of_affected_rows >0)
{
$this->id = $connection->lastInsertId();
}
return ($number_of_affected_rows>0) ? $number_of_affected_rows : FALSE;
}
}
$mohamed = new Topics();
$mohamed->title = 'Hello';
$mohamed->body = 'Hello world again';
return $mohamed->add();
?>
What's not working exactly? Your SQL is wrong anyway, beacause it needs whitespaces in it.
'INSERT INTO '.self::$table_name.' SET '.$this->attributes();
And btw you should also escape table and field name in your SQL.

MySQL access classes in PHP

I have a connection class for MySQL that looks like this:
class MySQLConnect
{
private $connection;
private static $instances = 0;
function __construct()
{
if(MySQLConnect::$instances == 0)
{
//Connect to MySQL server
$this->connection = mysql_connect(MySQLConfig::HOST, MySQLConfig::USER, MySQLConfig::PASS)
or die("Error: Unable to connect to the MySQL Server.");
MySQLConnect::$instances = 1;
}
else
{
$msg = "Close the existing instance of the MySQLConnector class.";
die($msg);
}
}
public function singleQuery($query, $databasename)
{
mysql_select_db(MySQLConfig::DB, $this->connection)
or die("Error: Could not select database " . MySQLConfig::DB . " from the server.");
$result = mysql_query($query) or die('Query failed.');
return $result;
}
public function createResultSet($query, $databasename)
{
$rs = new MySQLResultSet($query, MySQLConfig::DB, $this->connection ) ;
return $rs;
}
public function close()
{
MySQLConnect::$instances = 0;
if(isset($this->connection) ) {
mysql_close($this->connection) ;
unset($this->connection) ;
}
}
public function __destruct()
{
$this->close();
}
}
The MySQLResultSet class looks like this:
class MySQLResultSet implements Iterator
{
private $query;
private $databasename;
private $connection;
private $result;
private $currentRow;
private $key = 0;
private $valid;
public function __construct($query, $databasename, $connection)
{
$this->query = $query;
//Select the database
$selectedDatabase = mysql_select_db($databasename, $connection)
or die("Error: Could not select database " . $this->dbname . " from the server.");
$this->result = mysql_query($this->query) or die('Query failed.');
$this->rewind();
}
public function getResult()
{
return $this->result;
}
// public function getRow()
// {
// return mysql_fetch_row($this->result);
// }
public function getNumberRows()
{
return mysql_num_rows($this->result);
}
//current() returns the current row
public function current()
{
return $this->currentRow;
}
//key() returns the current index
public function key()
{
return $this->key;
}
//next() moves forward one index
public function next()
{
if($this->currentRow = mysql_fetch_array($this->result) ) {
$this->valid = true;
$this->key++;
}else{
$this->valid = false;
}
}
//rewind() moves to the starting index
public function rewind()
{
$this->key = 0;
if(mysql_num_rows($this->result) > 0)
{
if(mysql_data_seek($this->result, 0) )
{
$this->valid = true;
$this->key = 0;
$this->currentRow = mysql_fetch_array($this->result);
}
}
else
{
$this->valid = false;
}
}
//valid returns 1 if the current position is a valid array index
//and 0 if it is not valid
public function valid()
{
return $this->valid;
}
}
The following class is an example of how I am accessing the database:
class ImageCount
{
public function getCount()
{
$mysqlConnector = new MySQLConnect();
$query = "SELECT * FROM images;";
$resultSet = $mysqlConnector->createResultSet($query, MySQLConfig::DB);
$mysqlConnector->close();
return $resultSet->getNumberRows();
}
}
I use the ImageCount class like this:
if(!ImageCount::getCount())
{
//Do something
}
Question: Is this an okay way to access the database? Could anybody recommend an alternative method if it is bad?
Thank-you.
Hey Mike, there's nothing wrong with implementing your own classes to handle database connection, what you have so far is fine, however PHP already provides an interface for handling DB connections regardless of the database manager you are connecting to. I'd recommend you to take a look at it http://www.php.net/manual/en/book.pdo.php since it has mostly all the functionality needed for handling queries, statements, resultsets, errors, and so forth.
Cheers,
M.
I'm not sure that having a class called "ImageCount" is really necessary. If you're going to be working with images - I would simply have a class called "Image" with a static function to get the count of all images, and some other functions to deal with images.
Also, if you try to create a new instance when one exists - how about returning the existing instance instead of using die() to stop the program.

Categories