I'm trying to display some data this way from mysql in php:
CompteDAO.php
<?php
namespace DAO;
include_once(__DIR__ . '/bdConfig.php');
class CompteDAO
{
public $bdd;
public function getList(){
$this->bdd = new \DAO\bdConfig();
$requete = $this->bdd->bd->prepare('SELECT * FROM compte');
$requete->execute();
return $requete;
}
}
?>
bdConfig.php
<?php
namespace DAO;
use PDO;
class bdConfig
{
public $bd;
public function __construct()
{
try
{
$this->bd = new PDO('mysql:host=127.0.0.1;dbname=d', 'root', '');
}
catch (Exception $e)
{
die('Erreur: ' . $e->getMessage());
}
}
}
?>
index.php
$daoCompte = new \DAO\CompteDAO();
$comptes = $daoCompte->getList();
while ($data = $this->comptes->fetch()) {
echo '<td>' . $data['CIN'] . '</td>';
}
But, doing this, I get no result. (Knowing that my database isn't empty) I think that the probelm is becoming from the getList return value, but I couldn't be able to found why and how to resolve it.
How do I fix this, please ?
try this:
$daoCompte = new \DAO\CompteDAO();
$comptes = $daoCompte->getList();
$dataArray = $comptes->fetchAll(PDO::FETCH_ASSOC);
foreach ($dataArray as $data) {
echo '<td>' . $data['CIN'] . '</td>';
}
you are not using class and you have no class property name $comptes. So $this->comptes is invalid.
Related
I do have a search form on a page which search records from a table in my database. I want to show how many results each query gives us. All this is written in codeigniter.
All my code on that page:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index() {
$data['title'] = "Welcome | randomsite";
$data['html'] = "";
if($this->input->post()) {
$uq = $this->security->xss_clean($this->input->post('query'));
if(trim($uq) != "") {
$searchBy = $this->security->xss_clean($this->input->post('searchBy'));
$searchByJSON = json_encode(array(1 => "Email", 2 => "Username", 3 => "IP", 4 => "FullName", 5 => "Phone"), JSON_FORCE_OBJECT);
if(isset(json_decode($searchByJSON)->$searchBy)) {
$start = microtime(true);
$this->db->from('Databases');
$rs = $this->db->get()->result();
$end = microtime(true);
$data['html'] .= "Search completed in: " . ($end - $start) . " seconds.<p></p>";
foreach($rs as $row) {
$this->db->distinct();
$this->db->select('Username, Password, Email, FullName, IP, Phone, salt');
$this->db->from('Accounts');
$this->db->where(json_decode($searchByJSON)->$searchBy, $uq);
$this->db->where('DatabaseID', $row->ID);
$query = $this->db->get();
if($query->num_rows() > 0) {
if($searchBy == 5 && $query->row()->Phone == 0) {
break;
}
$resultsHTML = "";
foreach($query->result() as $qr) {
$resultsHTML .= "<div class='card-block-results' style='table-layout:fixed; word-wrap:break-word;'><table class='table table-hover' style='font-size:13px;'>";
foreach($qr as $key => $value) {
if(!empty($value)) {
if($key == "FullName") {
$key = "Full Name";
}
$resultsHTML .= "<tr><td>" . $key . ": " . $value . "</td></tr>";
}
}
$resultsHTML .= "</table></div>";
}
$data['html'] .= $row->Website . " has: <b style='color:lime;'>" . $query->num_rows() . "</b> result(s) found. This data was hacked on approximately " . $row->Date . ". <button class='btn btn-success btn-sm' style='margin-bottom:5px;' id='button" . $row->ID . "'>view results</button><div id='results" . $row->ID . "' style='display:none;'><div class='card card-outline-primary' style='margin-bottom:10px;text-align:left;margin-top:5px;'><div class='card-header card-primary'>Results</div>" . $resultsHTML . "</div></div><script type='text/javascript'>$('#button" . $row->ID . "').click(function() { $(this).hide(); $('#results" . $row->ID . "').show(); });</script><br>";
}
}
if($data['html'] == "Search completed in: " . ($end - $start) . " seconds.<p></p>") {
$data['html'] .= "No results found!<p></p>Are you searching in the right fields? Searching for an email in the phone number field will not work.<br>Make sure first and last names are correct. Example: Mike Tyson";
}
$data['html'] .= "<br><br><br>";
$this->db->from('Lookups');
$query = $this->db->get();
$new_lookup = $query->row()->Number + 1;
$qdata = array(
"Number" => $new_lookup
);
$this->db->update('Lookups', $qdata);
}
} else {
$data['html'] = '<div class="alert alert-danger">×Please enter something in your query before searching!</div>';
}
}
$this->load->view('welcome', $data);
}
}
So how can I add that into every time someone is searching? Like 'Query had x results.'
Like this:
I searched on many different sites about this but I couldn't find anything for my specific question.
you have already used it in your code,
$query->num_rows()
will give you the number of rows u get from the query.
i think this is abusing a framework like CI - i give you some insights in to this framework - if you are willing to learn, study this piece of code because
you nearly don't use any of his built in functionality
in my opinion you've to restructure your code to such an extent that you don't even recognize your previous attempt ;)
i'll try to give you a hunch - but in order to understand - you've to work with this code
put in your models folder the following models
Database Model
class Database_model extends CI_Model
{
private $objCollection;
public function __construct()
{
$this->objCollection = new Database_Collection();
}
public function getCollection()
{
$this->benchmark->mark('code_start');
$this->db->from('Databases');
$this->objCollection->append($this->db->get()->result());
$this->benchmark->mark('code_end');
$this->objCollection->queryTime = $this->benchmark->elapsed_time('code_start', 'code_end');
return $this->objCollection;
}
}
class Database_Collection extends ArrayObject
{
public $queryTime = 0;
}
Accounts Model
class Accounts_model extends CI_Model
{
private $objCollection;
public function __construct()
{
$this->objCollection = new Accounts_Collection();
}
public function getCollection()
{
$this->benchmark->mark('code_start');
$this->db
->distinct()
->select('Username, Password, Email, FullName, IP, Phone, salt')
->from('Accounts');
$this->objCollection->append($this->db->get()->result());
$this->benchmark->mark('code_end');
$this->objCollection->queryTime = $this->benchmark->elapsed_time('code_start', 'code_end');
return $this->objCollection;
}
}
class Accounts_Collection extends ArrayObject
{
public $queryTime = 0;
}
Search Model
class Search_model extends CI_Model
{
private $strSearchQuery = "";
public function getSearchObject()
{
if ($this->isValidSearch())
{
$this->load->model("Database_Model");
$this->load->model("Accounts_Model");
$objSearch = new Search;
$objDBCollection = $this->Database_Model->getCollection();
foreach($objDBCollection AS $objItem)
{
$this->db
->where("DatabaseID", $objItem->ID)
->where($this->input->post("searchBy"), $this->strSearchQuery);
$objItem->collection = $this->Accounts_Model->getCollection();
}
$objSearch->addResultCollection($objDBCollection);
return $objSearch;
}
return false;
}
public function isValidSearch()
{
$strSearchQuery = $this->security->xss_clean($this->input->post('query'));
$this->strSearchQuery = trim($strSearchQuery);
if (empty($this->strSearchQuery)) return false;
$arrValidSearchCriteria = array("Email", "Username", "IP", "FullName", "Phone");
return (in_array($this->input->post("searchBy"),arrValidSearchCriteria));
}
}
class Search
{
public $queryTime = 0;
private $objCollection;
public function addResultCollection(Database_Collection $objCollection)
{
$this->objCollection = $objCollection;
}
public function getRenderedTime()
{
if ($this->queryTime == 0)
{
$this->queryTime += $this->objCollection->queryTime;
foreach($this->objCollection AS $objItem)
{
if (isset($objItem->collection)
{
$this->queryTime += $objItem->collection->queryTime;
}
}
}
return $this->queryTime;
}
public function getCountSearchResults()
{
if (!$this->countSearchResults)
{
$this->countSearchResults = 0;
foreach($this->objCollection AS $objItem)
{
if (isset($objItem->collection)
{
$this->countSearchResults += $objItem->collection->count();
}
}
}
return $this->countSearchResults;
}
}
your controller
class Welcome extends CI_Controller
{
public function index()
{
$this->load->model("Search_model");
$data['title'] = "Welcome | randomsite";
if ($this->Search_model->isValidSearch()
{
$objSearch = $this->Search_model->getSearchObject();
$arrViewData = array("objSearch" => $objSearch);
$this->load->view("list-search", $arrViewData);
}
}
}
pS: maybe there are some typos because i just wrote it down
Hello I am trying to build my first restful web service and im using the instruction from lorna jane mitchell blog.
If the req comes through this Url : http://localhost:8888/lorna/index.php/tree/getpath?node_id=75
i call the function getpath passing node_id
The function get path looks like this :
class NestedSet
{
public function getPath($id) {
$sql = "SELECT p." . $this->pk . ", p." . $this->name . " FROM ". $this->table . " n, " . $this->table . " p WHERE n.lft BETWEEN p.lft AND p.rgt AND n." . $this->pk ." = " . $id . " ORDER BY p.lft;";
$result = $this->db->query($sql);
if ($result->num_rows == 0) {
return $this->error(1, true);
}
$path = array();
$i = 0;
while ($row = $result->fetch_assoc()) {
$path[$i] = $row;
$i++;
}
return $path;
}
}
Now i want to pass this variable $path to the class JsonView that looks like this :
class JsonView extends ApiView {
public function render($path) {
header('Content-Type: application/json; charset=utf8');
echo json_encode($path);
return true;
}
}
class ApiView {
protected function addCount($data) {
if(!empty($data)) {
// do nothing, this is added earlier
} else {
$data['meta']['count'] = 0;
}
return $data;
}
}
Any Idea on how can I pass the variable $path or any other variable through this JsonView Class.
Thank you very much for your time :)
UPDATE This is the code for creating the nested class object
public function getAction($request) {
$data = $request->parameters;
if(isset($request->url_elements[2])) {
switch ($request->url_elements[2]) {
case 'getpath':
$id = $data['node_id'];
$nested = new NestedSet();
$nested->getPath($id);
$api = new JsonView();
$api->render($path);
break;
default:
# code...
break;
}
} else {
$nested = new NestedSet();
echo $nested->treeAsHtml();
}
}
Just create object of JsonView and then call the function render using that object.
$api = new JsonView;
$api->render($path);
i create function called empty_fields but i can't figure out, to make it work..
<?php
function empty_fields($field_name)
{
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
} else { $output = null; }
return $output;
}
to display in html
<?php empty_fields('indigofera'); ?>
Change
if(!empty($order['$field_name'])){
to
if(!empty($order[$field_name])){
'$field_name' does not evaluate to anything and it will search for
key '$field_name' in the $orders array everytime, hence will not work.
Hope it works.
If you use $order as a global variable, use:
function empty_fields($field_name)
{
global $order;
$output = null;
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
return $output;
}
and use it:
<?php echo empty_fields('indigofera'); ?>
EDIT: the OOP way:
class Orders
{
private $order = null;
public function get_order()
{
$this->order = //....
}
public function empty_fields($field_name)
{
if(!isset($this->order) || empty($order[$field_name])) return;
return "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
}
and use it:
<?php
$orders = new Orders();
$orders->get_order();
echo $orders->empty_fields("indigofera");
I have a array i want its value to be "public $somevariable". Here is my function how it looks like.
public function __construct(){
global $database;
$result = $database->query("SHOW COLUMNS FROM ".self::$tabel_name."");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
$attributes_var = array();
while ($row = $database->fetch_array($result)) {
$attributes_var[] = $row[0];
}
}
foreach($attributes_var as $key)
{
public $$key;
}
}
But its showing syntax error on "public $$key". I want to use the dynamic generated variable as public variable and want to use them outside the class.
Any suggestion?
Thank you!
You can do like below, the default value is null.
foreach($attributes_var as $key)
{
$this->{$key} = null;
}
I'm making a little PHP function that will show the avatar of all the administrators in my database. For some reason, I get the following error when I try to call the function $backend->addSnippet('login: show-admins');. Here is the PHP Class.
<?php
class zBackend {
private $adminCount;
final public function fetchAdminInfo() {
global $zip, $db, $tpl;
$query = $db->prepare('SELECT first_name, last_name FROM zip__admins');
$query->execute();
$result = $query->fetchAll();
$id = 1;
foreach($result as $row) {
$tpl->define('admin: first_name-' . $id, $row['first_name']);
$tpl->define('admin: last_name-' . $id, $row['last_name']);
$id++;
}
$this->adminCount = $id;
}
final public function addSnippet($z) {
global $tpl;
if(isset($z) && !empty($z)) {
$this->fetchAdminInfo();
switch($z) {
case 'login: show-admins':
$tpl->write('<ul id="users">');
$id = 0;
while($this->adminCount > $id) {
$tpl->write('<li data-name="{admin: first_name-' . $id + 1 . '} {admin: last_name-' . $id + 1 . '}">');
$tpl->write('<div class="av-overlay"></div><img src="{site: backend}/img/avatars/nick.jpg" class="av">');
$tpl->write('<span class="av-tooltip">{admin: first_name-' . $id + 1 . '} {admin: last_name-' . $id + 1 . '}</span>');
$tpl->write('</li>');
}
break;
}
} else {
return false;
}
}
}
?>
Here is where I set the function:
final public function __construct() {
global $zip, $core, $backend;
$this->Define('site: title', $zip['Site']['Title']);
$this->Define('site: location', $zip['Site']['Location']);
$this->Define('site: style', $zip['Site']['Location'] . '/_zip/_templates/_frontend/' . $zip['Template']['Frontend']);
$this->Define('site: backend', $zip['Site']['Location'] . '/_zip/_templates/_backend/' . $zip['Template']['Backend']);
$this->Define('social: email', $zip['Social']['Email']);
$this->Define('social: twitter', $zip['Social']['Twitter']);
$this->Define('social: youtube', $zip['Social']['Youtube']);
$this->Define('social: facebook', $zip['Social']['Facebook']);
$this->Define('snippet: show-admins', $backend->addSnippet('login: show-admins'));
}
And here is where I call the function:
<ul id="users">
{snippet: show-admins}
<br class="clear">
</ul>
Here is where I declare $backend
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
define('D', DIRECTORY_SEPARATOR);
define('Z', '_zip' . D);
define('L', '_lib' . D);
define('C', '_class'. D);
require Z . 'config.php';
require Z . L . 'common.php';
try {
$db = new PDO($zip['Database']['Data']['Source']['Name'], $zip['Database']['Username'], $zip['Database']['Password']);
} catch(PDOException $e) {
die(zipError('ZipDB: Connection Failed', $e->getMessage()));
}
require Z . C . 'class.ztpl.php';
require Z . C . 'class.zcore.php';
require Z . C . 'class.zbackend.php';
require Z . C . 'class.zmail.php';
$tpl = new zTpl();
$backend = new zBackend();
$core = new zCore();
?>
It works just fine if I put the code into the file, but that limits what I can do. I want to be able to do it in a class and use functions to call it. Any ideas?
$backend isn't defined when your constructor fires. It's unclear from the code you've posted what class your __construct is constructing, but I'm guessing it's within zTpl. Consider moving your snippet definition call to a separate method, which you can call once all dependent objects have been constructed.
In class zTpl:
final public function __construct() {
global $zip; //note that we don't need $core or
//$backend, since they aren't yet defined
//Personally, I would pass the $zip array
//as a parameter to this constructor.
$this->Define('site: title', $zip['Site']['Title']);
//...
}
public function defineShowAdminsSnippet($backend) {
$this->Define('snippet: show-admins', $backend->addSnippet('login: show-admins'));
}
Where you define your objects:
$tpl = new zTpl();
$backend = new zBackend();
$core = new zCore();
//new:
$tpl->defineShowAdminsSnippet();
In my opinion, it is easier to avoid dependency problems like this if you eliminate use of the global keyword.