So my code was working perfectly fine, until I tried to insert to the database..
my DB.php (The problem seems to be here, I checked all the other files and nothing is causing any problems, the function I used was the Insert function and I got an error on line 37:
<?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))) {
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 error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
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++;
}
$sql = "INSERT INTO users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
echo $sql;
if(!$this->query($sql, $fields)->error()){ //where my error occurred
return true;
}
}
return false;
}
}
(The data's inserted to the table but that error seems crucial and I didn't find anything about it anywhere)
I watched a tutorial on YouTube and the problem occurred here- https://youtu.be/zvXgsouIzVg?t=5258
(The full error):
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error in D:\xampp\htdocs\classes\DB.php:37 Stack trace: #0 D:\xampp\htdocs\classes\DB.php(37): PDOStatement->fetchAll(5) #1 D:\xampp\htdocs\classes\DB.php(93): DB->query('INSERT INTO use...', Array) #2 D:\xampp\htdocs\test.php(4): DB->insert('users', Array) #3 {main} thrown in D:\xampp\htdocs\classes\DB.php on line 37
Thanks in advance, that would help me a lot!
Related
I'm learning from a tutorial online, but I can't seem to get my SQL statements to insert into the database. This is my first try at functions. I'm thinking it's the "back-tick" in my SQL statement here:
$sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES (".$values.")";`
Anyway here's my code db.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'));
echo 'Connected<br>';
}
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))
{
$r = 1;
if (count($params))
{
foreach($params as $param)
{
$this->_query->bindValue($r, $param);
$r++;
}
}
if($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
echo 'success<br>';
}
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 = '';
$r = 1;
foreach($fields as $field)
{
$values .= '?';
if($r < count($fields))
{
$values .= ', ';
}
$r++;
}
//die($values);
$sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES (".$values.")";
echo $sql;
if(!$this->query($sql, $fields)->error())
{
return true;
}
}
return false;
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
public function results()
{
return $this->_results;
}
public function first()
{
return $this->results()[0];
}
}
and here's my index.php:
$user = DB::getInstance()->insert('users', array(
'username' => 'Dale',
'password' => 'password',
'salt' => 'salt'
));
if($user){ echo 'true';}
I've tried removing the "back-ticks" (that's what the guy in the tutorial called them, (`), but that didn't work. I'm trying to get the index.php to insert the data into my database. Any help would be appreciated.
I have a database with 5 users like hr, pay ,misc. I am using singleton database pattern to connect and execute query to these database users.
I am accessing connection information from Config Class, where i am storing connection parameters as an array.
I want to get a new connection object when i change parameter in getInstance method for example
$data1 = DB::getInsatance('common')->query("select * from Table1 (in common)");
$data2 = DB::getInsatance('misc')->query("select * from Table2 (in misc) ");
But whenever two instance methods are created with seperate users,the object initiated later in the flow is not generated
<!--
This is my DB class where my pdo parameters will change based on arguement supplied in getInstance() method --->
<?php
include_once 'Config.php';
class DB {
private static $_instance = null;
private $_pdo, $_query, $_error = false, $_results, $_count = 0;
protected $user;
private function __construct($user) {
try {
$this -> _pdo = new PDO('oci:dbname=//' . Config::get($user.'/host') . '/' . Config::get($user.'/db'), Config::get($user.'/username'), Config::get($user.'/password'));
} catch (PDOException $e) {
die($e -> getMessage());
}
}
public static function getInstance($user) {
if (!isset(self::$_instance)) {
self::$_instance = new DB($user);
}
//return $user;
return self::$_instance;
}
public function query($sql, $params = array()) {
//echo $sql.'<br>';
$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);
foreach ($this ->_results as $result) {
$this -> _count++;
}
//return $this ->_count;
} else {
$this -> _error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()) {
if (count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=','like');
$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 getf($keys = array(), $table, $wheres = array(array(),array(),array())) {
$fields = $wheres[0];
$qoperator = $wheres[1];
$values = $wheres[2];
$operators = array('=', '>', '<', '>=', '<=');
foreach ($fields as $field) {
$this -> field = $field;
}
foreach ($qoperator as $operator1) {
$this -> operator = $operator1;
}
foreach ($values as $value1) {
$this -> value = $value1;
}
//if (in_array($operator, $operators)) {
if (count($fields) === count($values)) {
$sql = "SELECT " . implode(',', $keys) . "FROM {$table} WHERE" . implode('AND', '{$field} {$operator} ?');
} elseif (count($fields) === 0) {
$sql = "SELECT " . implode(',', $keys) . "FROM {$table} WHERE" . implode('AND', '{$field} {$operator} ?');
}
if (!$this -> query($sql, array($value)) -> error()) {
return $this;
}
//}
return false;
}
public function select($keys, $table, $where) {
return $this -> getf($keys, $table, $where);
}
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = '';
$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 TENDER_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];
return current($this -> results());
}
public function error() {
return $this -> _error;
}
public function count() {
return $this -> _count;
}
}
?>
Rather than setting $user and adding a new connection whenever the user changes, you can store the connections and only make a new connection when it doesn't exist:
private function __construct($user) {
try {
$this->_pdo = new PDO(
'oci:dbname=//'.Config::get($user.'/host').'/'.Config::get($user.'/db'),
Config::get($user.'/username'),
Config::get($user.'/password')
);
} catch (PDOException $e) {
die($e -> getMessage());
}
}
public static function getInstance($user) {
if (!empty(self::$_instance[$user])) {
self::$_instance[$user] = new DB($user);
}
return self::$_instance[$user];
}
I'm currently having trouble with inserting data into my database. I have this code to start inserting the query:
if (Input::exists()) {
$validate = new Validate();
$link = new Link();
$validation = $validate->check($_POST, array(
'name' => array(
'related' => 'hyperlink'
),
'hyperlink' => array(
'related' => 'name'
)
));
if ($validation->passed()) {
try {
$link->create(array(
'uid' => $user->data()->id,
'name' => Input::get('name'),
'hyperlink' => Input::get('hyperlink')
));
} catch (PDOException $e) {
die($e->getMessage());
}
} else {
echo '<div class="error">';
echo '<ol>';
foreach ($validation->errors() as $error) {
echo '<li>' . $error . '</li>';
}
echo '</div>';
echo '</ol>';
}
}
When running this code, the create method is called:
public function create($fields = array()) {
if (!$this->_db->insert('user_links', $fields)) {
echo 'Something went wrong';
}
}
Now the script will run the insert method:
public function insert($table, $fields = array()) {
if (count($fields)) {
$value_list = implode(", ", array_values($fields));
$keys = array_keys($fields);
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ({$value_list})";
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
Everything goes fine, but then when it goes to the query() method, it appears there are 2 queries saved in it. I already heard about __destruct, so I'm wondering if it has anything to do with that.
Here's the query method:
public function query($sql, $params = array()) {
$this->_error = false;
echo $sql;
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;
}
When I echo the $sql in the query() method, it echo's this:
SELECT * FROM users WHERE id = ?INSERT INTO user_links (uid,name,hyperlink) VALUES (1, test, test)
The SELECT * FROM users WHERE id = ? comes from a get() method. But In the code where I set all data for my query, I'm not using any get() method. Unless to grab the values of the inputfields. (But that's not the problem)
Thanks for help!
EDIT 1:
Select method:
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
EDIT 2:
public function find($user = null) {
if ($user) {
$field = (is_numeric($user)) ? 'id' : 'email';
$data = $this->_db->get('users', array($field, '=', $user));
if ($data->count()) {
$this->_data = $data->first();
return true;
}
}
}
EDIT 3:
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;
}
The problem is that you are not terminating you SQL statement. you need to put ; at end of query string so that both query can run.
Like in insert() method
$sql = "INSERT INTO
`$table` (`" . implode('`, `', $keys) . "`)
VALUES ({$value_list});"; //added semicolon
and in get() method which is calling action do the same
currently your sql is not valid because of two queries are merged, ; will make both valid and it will work.
'uid' => $user->data()->id,
above code is the cause of second query
SELECT * FROM users WHERE id = ?
Note : You should consider a singleton to deal with db and should run one query at a time. currently your $sql property is having two queries concated SELECT * FROM users WHERE id = ?INSERT INTO user_links (uid,name,hyperlink) VALUES (1, test, test). or an array of query will also work.
Update:
add ; in action method like this and try
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ? ;";
I was following this tutorial on Udemy about building login form. Everything went well.
Now I'm trying to reuse the code. The problem I'm having is when I'm trying to query all entries from a database in order to get a total number of websites. Could you please advise?
Here is my count function (this is where I'm having issues in obtaining a total number of entries to the database for pagination):
function get_all_websites(){
$all = array();
$db = DB::getInstance();
$all = $db->query("SELECT * FROM website");
if(!$all->count()){
echo 'No Websites available. Please check back later.';
} else {
foreach($all->results() as $all){
$all->id = $all;
}
}
return $all;
}
function get_websites_count(){
return count(get_all_websites());
}
if I use this I get all ID's listed.
function get_all_websites(){
$all = array();
$db = DB::getInstance();
$all = $db->query("SELECT * FROM website");
if(!$all->count()){
echo 'No Websites available. Please check back later.';
} else {
foreach($all->results() as $all){
echo $all->id;
}
}
}
Database class.
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;
// Check if query has been prepared properly
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
// If the query has been prepared successfuly, store the result
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;
}
// QUERYING DATA FROM DATABASE
public function get($table, $where){
return $this->action('SELECT *', $table, $where);
}
// DELETING DATA FROM DATABASE
public function delete($table, $where){
return $this->action('DELETE', $table, $where);
}
// INSERTING DATA INTO DATABASE
public function insert($table, $fields = array()){
$keys = array_keys($fields);
$values = '';
$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 results(){
return $this->_results;
}
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 first(){
return $this->results()[0];
}
public function error(){
return $this->_error;
}
public function count(){
return $this->_count;
}
}
This part doesn't seem right:
} else {
foreach($all->results() as $all){
$all->id = $all;
}
}
return $all;
but I'm not exactly sure what you want.
We could append each id to an array called $allWebsiteIds:
} else {
foreach($all->results() as $all){
$allWebsiteIds[] = $all->id;
}
}
return $allWebsiteIds;
That might give you what you want.
SQL provides built-in support for counting rows in a table.
SELECT COUNT(*) FROM ...
This is highly optimizable and avoids loading every row into PHP's memory.
Additionally, pay close attention to the construct of your loops; specifically what it means to say:
foreach($foo as $foo)
As part of your study, you should be able to say why that expression is almost never the intended one.
There is a broader rule: Never mutate that which you are iterating over.
Why not use the select to count the rows?
SELECT COUNT(1) FROM website;
I'm building this Login system for my website. Everything seemed to work ok until I came across updating user details stored in database. Every time I try to update dummy details I get thrown an Exception and Can't figure out why.
Could You please scan through quickly and help me find an error if there is one? There are no syntax errors.
update.php
$user = new User();
if(!$user->isLoggedIn()){
Redirect::to('index.php');
}
// Check whether token is submited and user exists
if(Input::exists()){
if(Token::check(Input::get('token'))){
$validate = new Validate();
$validation = $validate->check($_POST, array(
'Name' => array(
'required' => true,
'min' => 4,
'max' => 30
),
'email' => array(
'required' =>true
)
));
if($validation->passed()){
// Update
try{
$user->update(array(
'Name' => Input::get('Name'),
'email' => Input::get('email')
));
Session::flash('home', 'Your details have been updated');
Redirect::to('index.php');
}catch(Exception $e) {
die($e->getMessage());
}
} else {
foreach($validation->errors() as $error){
echo ('<p>' . $error . '</p>');
}
}
}
}
User.php class
class User{
private $_db,
$_data,
$_sessionName,
$_cookieName,
$_isLoggedIn;
public function __construct($user = null){
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
if(!$user){
if(Session::exists($this->_sessionName)){
$user = Session::get($this->_sessionName);
if($this->find($user)){
$this->_isLoggedIn = true;
} else {
// Process Log out
}
}
} else {
$this->find($user);
}
}
public function update($fields = array(), $id = null){
if(!$id && $this->isLoggedIn()){
$id = $this->data()->id;
}
if(!$this->_db->update('user', $id, $fields)){
throw new Exception('Sorry, there was problem updating. Please try again later.');
}
}
public function create($fields = array()){
if(!$this->_db->insert('user', $fields)){
throw new Exception('There was a problem creating new account.');
}
}
public function find($user = null){
if($user){
$field = (is_numeric($user)) ? 'id' : 'Username';
$data = $this->_db->get('user', array($field, '=', $user));
if($data->count()){
$this->_data = $data->first();
return true;
}
}
return false;
}
public function login($Username = null, $password = null, $remember = false){
if(!$Username && !$password && $this->exists()){
// Log User in
Session::put($this->_sessionName, $this->data()->id);
} else {
$user = $this->find($Username);
if($user){
if($this->data()->Password === Hash::make($password, $this->data()->salt)){
Session::put($this->_sessionName, $this->data()->id);
if($remember){
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if(!$hashCheck->count()){
$this->_db->insert('users_session', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
}
}
}
return false;
}
public function exists(){
return (!empty($this->_data)) ? true : false;
}
public function logout(){
$this->_db->delete('users_session', array('user_id', '=', $this->data()->id));
Session::delete($this->_sessionName);
Cookie::delete($this->_cookieName);
}
public function data(){
return $this->_data;
}
public function isLoggedIn(){
return $this->_isLoggedIn;
}
}
(if(!$this->_db->update('user', $id, $fields)){
throw new Exception('Sorry, there was problem updating. Please try again later.');
})
This is the exception i get.. Thanks a million
If it helps update() is the method I get the error from
This is my DB class:
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;
// Check if query has been prepared properly
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
// If the query has been prepared successfuly, store the result
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;
}
// QUERYING DATA FROM DATABASE
public function get($table, $where){
return $this->action('SELECT *', $table, $where);
}
// DELETING DATA FROM DATABASE
public function delete($table, $where){
return $this->action('DELETE', $table, $where);
}
// INSERTING DATA INTO DATABASE
public function insert($table, $fields = array()){
$keys = array_keys($fields);
$values = '';
$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 results(){
return $this->_results;
}
public function update($table, $userID, $fields){
$set = '';
$x = 1;
foreach($fields as $name => $value){
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE userID = {ID}";
if(!$this->query($sql, $fields)->error()){
return true;
}
return false;
}
public function first(){
return $this->results()[0];
}
public function error(){
return $this->_error;
}
public function count(){
return $this->_count;
}
}
If you tried to return the sql you will find that it is not valid, such as:
function update($table, $userID, $fields){
$set = '';
$x = 1;
foreach($fields as $name => $value){
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE userID = {ID}";
return $sql;
}
echo update('table',1,array('f1'=>'v1','f2'=>'v2','f3'=>'v3','f4'=>'v4'));
Results would look like:
UPDATE table SET f1 = ?, f2 = ?, f3 = ?, f4 = ? WHERE userID = {ID}
so your ID is not the actual integer that I passed.
but if you changed your statement to be:
//some code
$sql = "UPDATE {$table} SET {$set} WHERE userID = {$userID}";
return $sql;
the result would be:
UPDATE table SET f1 = ?, f2 = ?, f3 = ?, f4 = ? WHERE userID = 1