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.
Related
When I invoke 'get' function with username as an argument, it does not show any result. But when I do it by passing id, then it shows the result. The information is stored correctly in the database. I am following the tutorial from codecourse on PHP OOP login/register system. My functions look:
$user =DB::getInstance();
$user->get('users', array('username', '=', 'subodh')); // doesn not show result
$user->get('users', array('id', '=', '24')); // shows result
if(!$user->count()) {
echo 'No user';
}
else {
echo $user->first()->username;
}
public function get($table, $where)
{
return $this->action('SELECT *', $table, $where);
}
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 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;
}
I keep getting the warning error while trying to make this object oriented log in system. I am trying to do the insert function right now but the warning is stopping me.
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\YetiDraft\yetidb\classes\db.php on line 32
Line 32 is the function query foreach statement
<?php
class db {
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 db();
}
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 = '';
$x = 1;
foreach($fields as $fields){
$values .= "?";
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO users (`" . implode('`, `', $keys) ."`) VALUES ({$values})";
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 part might cause the problem:
foreach($fields as $fields){
$values .= "?";
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
You are using the variable $fields both as source and as iterator.
Doing so overwrites $fields with the last element of the array. For this reason, in the following call, $fields is not an array anymore:
if(!$this->query($sql, $fields)->error()){
And since you are trying to iterate over the value of $fields in $this->query(), you are getting the error.
Thanks to Barmar for the tip!
Try this instead:
foreach($fields as $field){
$values .= "?";
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
Edit: Or use Barmar's solution instead. His solution is better.
My guess is that $params isnt an array and hence isnt traversable. Make a small check before the foreach like this.
if (is_array($params))
{
foreach ($params as $param)
{
//do things here
}
}
count() is not a reliable way to check if a variable is an array. Use is_array instead of count(). Your error probably is the variable isnt an array, and you are trying to traverse through the variable.
Replace the loop:
foreach($fields as $field){
$values .= "?";
if($x < count($field)){
$values .= ', ';
}
$x++;
}
with
$values = implode(', ', array_fill(0, count($fields), '?'));
Because you're reusing the variable $fields as the iteration variable, when your loop is done $fields no longer contains an array of fields, it contains the value of the last field. So when you call $this->query($sql, $fields), you're passing a string instead of an array, and the foreach inside query() won't work.
I'm following PHP Academy OOP Login/Register Tutorial currently in 16th part.
I used this code to create object in $data.
$data = $this->_db->get('users', array($field, '=', $user));
Then this code to add values from that object.
$this->_data = $data;
and trying to access the variables there by
public function data(){
return $this->_data;
}
$this->data()->password
The last code is throwing error. I tried to debug using this code
$vars = get_object_vars ($this->_data);
print_r($vars);
That is printing this line
Array ( [error] => [_requests] => Array ( [0] => stdClass Object ( [uid] => 16 [username] => admin [password] => 46651b6f1d743345d82d32da2cda7f891016ebe9f8b4416314b127e35b72fc30 [salt] => ²ê$ÓÕBF49ð®}€Æ¥A];ÛAc«íÊùÍ„s [name] => admin [joined] => 2015-03-17 22:53:52 [groups] => 1 ) ) )
What does this mean? How can I access those fields?
Here is the full code:
DB.php
<?php
/**
* Connect to database.
*
*/
class DB{
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 DB();
}
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->_requests = $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 = '';
$x = 1;
foreach ($fields as $field) {
$values .= '?';
if($x < count($fields))
{
$values .= ', ';
}
$x++;
}
// die($values);
$sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";
echo $sql;
if(!$this->query($sql, $fields)->error())
{
return true;
}
}
return false;
}
public function update($table, $id, $fields)
{
$set = '';
$x = 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields))
{
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE uid = {$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;
}
}
user.php
<?php
class User{
private $_db,
$_data;
public function __construct($user = null)
{
$this->_db = DB::getInstance();
}
public function create($fields = array())
{
if(!$this->_db->insert('users', $fields))
{
throw new Exception("Problem Creating User Account");
}
}
public function find($user = null)
{
if($user)
{
$field = (is_numeric($user)) ? 'uid' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if($data->count())
{
$this->_data = $data;
$vars = get_object_vars ($this->_data);
print_r($vars);
return true;
}
}
}
public function login($username = null, $password = null)
{
$user = $this->find($username);
if($user)
{
if($this->data()->password === Hash::make($password, $this->_data->salt))
{
echo "ok";
}
}
return false;
}
public function data()
{
return $this->_data;
}
}
login.php
<?php
require_once 'core/init.php';
if(Input::exists())
{
if(Token::check(Input::get('token')))
{
$validate = new Validation();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true
),
'password' => array(
'required' => true
),
));
if($validation->passed())
{
$user = new User();
$login = $user->login(Input::get('username'), Input::get('password'));
if($login)
{
echo "Success";
}
else{
echo "sorry! Failed";
}
}
else{
foreach ($validation->errors() as $error) {
echo $error, '<br />';
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username" autocomplete="off">
</div>
<div class="field">
<label for="password">Password</label>
<input type="password" name="password" id="password" autocomplete="off">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Log In">
</form>
The variable returns array output. So you need to get values like $this->_data[0]->password, $this->_data[0]->username. Or when you store value to $this->_data, you can store the first child of the array.
instead of
$this->_data = $data;
You can use
$this->_data = $data->first();
So now you can get fields like $this->_data->username,$this->_data->password
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am learning PHP OOP by utilizing a PHP Academy tutorial. The tutorial is a Registration/Login system. I am having trouble on the "Remember Me" portion of the tutorial. This part of the tutorial retains a users selection to be able to stay logged in.
I am having an error:
"Fatal error: Call to a member function count() on a non-object in C:\xampp\htdocs\Rikarsen.hol.es\core\init.php on line 32
I have placed the PHP classes below to show what I have done thus far. Since I am new to PHP coding I am unable to locate the problem. Can anyone please help me? If any additional code is needed please let me know so I can supply it to you in order to help you discover my problem.
init.php
<?php
session_start();
$GLOBALS ['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'rikars'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user',
'token_name' => 'token'
)
);
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));
if($hashCheck->count()) {
echo 'asass';
}
}
I think I made a mistake in DB.php
<?php
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_result,
$_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 DB();
}
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()) {
$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) {
$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;
}
public function ins() {
$instance = DB::getInstance();
$instance->get('users',array('user_id','=','1'));
if (!$instance->Count()) {
echo 'No user';
} else {
echo 'User exists';
}
}
}
?>
Your method action return false but you expect object.
if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));
if($hashCheck === false) {
echo 'Action return false';
} else {
$count = $hashCheck->count();
if($count) {
echo 'Its object and count ='.$count;
}
}
}
Make sure your table name and column names are correct in get method. I was having the same problem and this was the solution that worked for me.
I'm using SQL Server as a database and PHP PDO to connect, When creating a registration page, I get this error when executing the query
Notice: Array to string conversion in C:\webdev\classes\DB.php on line 36
There was a problem creating an account.PHP Notice: Array to string conversion in C:\webdev\classes\DB.php on line 36
Line 36 - $this->_query->bindValue($x, $param);
<?php
class DB {
public static $instance = null;
private $_pdo = null,
$_query = null,
$_error = false,
$_results = null,
$_count = 0;
private function __construct() {
try {
$this->_pdo = new PDO('sqlsrv:server=' . Config::get('sqlsrv/servername') . ';database=' . Config::get('sqlsrv/db'), Config::get('sqlsrv/username'), Config::get('sqlsrv/password'));
} catch(PDOExeption $e) {
die($e->getMessage());
}
}
public static function getInstance() {
// Already an instance of this? Return, if not, create.
if(!isset(self::$instance)) {
self::$instance = new DB();
}
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) {
/* Line 36 */ $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 get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where) {
return $this->action('DELETE', $table, $where);
}
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 insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $value) {
$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 = null;
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ', ';
}
$x++;
}
$sql = "UPDATE users SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function results() {
// Return result object
return $this->_results;
}
public function first() {
return $this->_results[0];
}
public function count() {
// Return count
return $this->_count;
}
public function error() {
return $this->_error;
}}
Why would this be, I used the same code and had a mysql database and it sent the data to the db no problems, why would it be the case for SQL Server?
One of the $param iterations is coming in as an array probably:
if(count($params)) {
foreach($params as $param) {
if(is_array($param) || is_object($param)){ $param=''; }
$this->_query->bindValue($x, $param);
$x++;
}
}
Recommendation for debugging public function insert()
// add a debug parameter
public function insert($table, $fields = array(), $debug = false) {
$return = false;
if(is_array($fields) && count($fields) > 0 && $table != ''){
// build SQL and debug SQL
$sql = "INSERT INTO '$table' (";
$debug_sql = $sql;
// declare variables
$sql_fields = '';
$values = '';
$debug_values = '';
foreach($fields as $k=>$v) {
// encase fields and values in quotes
$sql_fields.= "'$k',";
$values.= "?,";
$debug_values.= "'$v',";
}
// remove trailing commas
$sql_fields = substr($sql_fields, 0, -1);
$values= substr($values, 0, -1);
$debug_values= substr($debug_values, 0, -1);
// finish SQL and debug SQL
$sql.= "$sql_fields) VALUES ($values)";
$debug_sql.= "$sql_fields) VALUES ($debug_values)";
if($debug === true) {
$return = $debug_sql;
}
else {
if(!$this->query($sql, $fields)->error()) {
$return = true;
}
}
}
return $return;
}
// now change the insert call to look like this
die($this->_db->insert('dbo.users', $fields, true)); // <-- notice the true parameter
/**
* Use the output to directly run the SQL from the MSSQL admin console or whatever they call it and it will provide a much more useful error description
*/