am new to php OOP I have tried to create a function in php to insert data to database but its not working ,please help.
my function:
public function insert($table, $fields = array(), $values = array()) {
$sql = " INSERT INTO{$table}($fields) VALUES($values)";
$this->_pdo->prepare ( $sql );
return $this->_pdo->exec ( $sql );
}
Here is a working OOP PHP Insert function, it should be easy to understand it but if you donĀ“t just ask.
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;
}
Related
I have looked at all of the other questions asked on SO and had no luck finding the problem in my code. I am trying to update a Database with an Update() method. My Insert() method is up and running, but I receive the above error when I run the code. It seems to be an error when binding my values. Would someone please give me some advice? Thank you.
<?php
class DB{
private static $_instance = null;
private $_pdo,$_query,$_error = false, $_result, $_count = 0, $_lastInsertID = null;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.DB_HOST.';port=3307;dbname='.DB_NAME , DB_USER, DB_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 = []){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
//binds paramaters
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()){
$this->_result = $this->_query->fetchALL(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
$this->_lastInsertID = $this->_pdo->lastInsertId();
} else{
$this->error = true;
}
}
return $this;
}
public function insert($table,$fields=[]){
$fieldString = '';
$valueString = '';
$values = [];
foreach( $fields as $field => $value){
$fieldString .= '`'. $field . '`,';
$valueString .= '?,';
$values[] = $value;
}
$fieldString = rtrim($fieldString, ',');
$valueString = rtrim($valueString, ',');
$sql = "INSERT INTO {$table} ({$fieldString}) VALUES ({$valueString})";
if(!$this->query($sql, $values)->error()){
return true;
}else{
return false;
}
}
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}
public function error(){
return $this->_error;
}
}
?>
<?php
class Home extends Controller{
public function __construct($controller,$action){
parent::__construct($controller, $action);
}
public function indexAction(){
//die('welcome to the home controller this is the index action.');
$db = DB::getInstance();
$fields = [
'fname'=> 'Jared',
'email'=>'JBowser#123.com'];
//$contacts = $db->insert('contacts',$fields); This is how we insert to our DB.
$contacts = $db->update('contacts',3, $fields); // This is how we update our DB.
$this->view->render('home/index'); ///path from views directory **
}
}
You dont load the values array in the Update method
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
$values[] = $value; // <<-- Added this line
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}
i'm using php to create a student registration system and i have created a database that has 6 tables
student_reg,
academics,
nextofkin,
contacts,
postal,
residential
and the primary key for student_reg is used as foreign key in the remaining 5 tables so i was trying to use last_insert_id() function to retrieve the primary key of student reg and insert it into the foreign key of the 5 tables. it does insert into the foreign key but the problem is that it inserts the correct id into one table but the rest receives a different id. insertAnyData is used to insert student_reg and insert Any is used to insert the remaining tables. WHAT HAVE I DONE WRONG or WHAT AM I MISSING. here is my code
public function insertAnyData($table, $fields = array())
{
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach ($fields as $field){
$values .= '?';
if ($x < count($fields)){
$values .= ', '; //coma and space
}
$x++;
}
//die($values);
$sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()){
return true;
}
//}
return false;
}
public function insertAny($table, $fields = array())
{
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach ($fields as $field){
$values .= '?';
if ($x < count($fields)){
$values .= ', '; //coma and space
}
$x++;
}
//die($values);
$sql = "SET #last_id_in_student_reg=LAST_INSERT_ID();
INSERT INTO {$table} (`".implode('`, `', $keys)."`,idstudent_reg) VALUES ({$values},#last_id_in_student_reg)";
if(!$this->query($sql, $fields)->error()){
return true;
}
//}
return false;
}
This is database class:
DB.php
<?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('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/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) {
$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;
}
}
I was looking this database approach and it seems very practical and useful. I'm beginner at oop and still learning. The requestQuote would look something like this:
How do I bindParam in query like this?
requestQuote = DB::getInstance()->query(""); (form DB.class)
This is code I have right now:
$request = "";
if ($_POST) {
$request = $_POST["request"];
} else if (isset($_GET["request"])) {
$request = $_GET["request"];
}
$requestQuote="%" . $request . "%";
$sql = $conn -> prepare("SELECT * FROM users WHERE concat(name, ' ',lastname, ' ', user_id) LIKE :request limit " . (($page * 50)-50) . ",50");
$sql->bindParam(":request", $requestQuote);
$sql -> execute();
$results = $sql -> fetchAll(PDO::FETCH_OBJ);
When I put it like this, then pagination works. But I need search form... and that won't work...
$sql= DB::getInstance()->query(
"SELECT * FROM users
WHERE (category='admin')
LIMIT " . (($page* 5)-5) . ",5");
#Paul was close but you got one more issue:
Check this part of the class:
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
It is not binding with named place holder, you need to change the code:
$limit = ($page * 50)-50;
$params = array('%lolcats%', $limit);
$query =
"SELECT * FROM users
WHERE concat(name, ' ',lastname, ' ', user_id)
LIKE ?
LIMIT ?,50";
$results = DB::getInstance()->query($query, $params);
or change the class code to bind by placeholder, something along the following lines:
#$params = array(':request' =>'%lolcats%', ':limit'=>$limit);
if(count($params)) {
foreach($params as $key=>$value) {
$this->_query->bindValue($key, $value);
}
}
Looking at this class, the second argument of query function is an optional array of parameters so use this to pass the parameters for your request:
$params = array(':request' => 'lolcats');
$limit = $page - 1 * 50;
$query = sprintf(
"SELECT * FROM users
WHERE concat(name, ' ',lastname, ' ', user_id)
LIKE :request
LIMIT %d,50",
$limt
);
$results = DB::getInstance()->query($query, $params);
Currently I'm stuck on how to add the values of my array into a variable, to output in a query.
Here are my data stored in:
try {
$link->create(array(
'uid' => $user->data()->id,
'name' => Input::get('name'),
'hyperlink' => Input::get('hyperlink')
));
} catch (Exception $e) {
die($e->getMessage());
}
And with this function I'm trying to get the values from that array into 1 variable:
public function insert($table, $fields = array()) {
if (count($fields)) {
$keys = array_keys($fields);
$x = 1;
foreach ($fields as $field => $values) {
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
die($sql);
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
But when I echo the sql it only gives the last value of the array. What am I doing wrong?
Thanks!
You could try something like this, cuts down on the looping a bit, and could be combined into a single line actually... EDIT: neglected to quote the values... updated appropriately
if (count($fields)) {
$field_list = implode(", ", array_keys($fields));
$value_list = implode("', '", array_values($fields));
$sql = "insert into `$table` ($field_list) values('$value_list')";
}
Here is another option and I couldn't figure out what was wrong with your script, it looks correct but wasn't able to find the problem. I always use this class method when inserting db values dynamically.
function insertRecord ($fieldarray)
{
$this->errors = array();
//Connect to the DB for table insert
global $dbconnect, $query;
$dbconnect = db_connect($this->dbname) or trigger_error("SQL", E_USER_ERROR);
//Now, using the contents of $fieldlist which was set in the class constructor we can edit the input array to filter out any items which do not belong in this database table. This removes the SUBMIT button, for example.
$fieldlist = $this->fieldlist;
foreach ($fieldarray as $field => $fieldvalue) {
if (!in_array($field, $fieldlist)) {
unset ($fieldarray[$field]);
} // if
} // foreach
//Now construct the query string to insert a new
//record into the database:
$query = "INSERT INTO $this->tablename SET ";
foreach ($fieldarray as $item => $value) {
$query .= "$item='$value', ";
} // foreach
//You may have noticed that each 'name=value' pair was appended
//to the query string with a trailing comma as a separator,
//so we must remove the final comma like so:
$query = rtrim($query, ', ');
//Now execute the query. Notice here that instead of the default
//error checking I look specifically for a 'duplicate key' error
//and return a simple error message rather terminating the whole
//script with a fatal error.
$result = #mysql_query($query, $dbconnect);
if (mysql_errno() <> 0) {
if (mysql_errno() == 1062) {
$this->errors[] = "A record already exists with this ID.";
} else {
trigger_error("SQL", E_USER_ERROR);
} // if
} // if
//Last act is to return control to the calling script.
return;
} // insertRecord
IMHO the function above has the necessary checks for an insert statement and error handling which I found useful.
I think you can use the function array_values like you use the function array_keys to do this easier.
public function insert($table, $fields = array()) {
if (count($fields)) {
$keys = array_keys($fields);
$values = array_values($fields); // why another logic for the same result.. ?
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES (`" . implode('`, `', $values) . "`)";
die($sql);
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
The problem is the $values = $values is inside the foreach loop.
foreach ($fields as $field => $values) {
// The problem is right here, each time this loops, you are
// setting the entire $values variable to be just the current iteration
// of the $fields variable.
$values = $values;
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
Try this instead:
$sql_values = '';
foreach ($fields as $field => $values) {
if ($x < count($fields)) {
$sql_values.= $values.', ';
}
$x++;
}
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ($sql_values)";
I have a very simple select query using pdo but it is not working.
The generic sql query is
$sql = "select * from table where type != 'address' and type != 'multipleimage'";
Now in pdo I have
$fieldtype = array('address','multipleimage');
$query = $this->db->prepare("SELECT * from table where
(type not in $type) and (userid !=:userid) ");
$query->execute(array(':userid' => 2, $fieldtype ));
Now getting notice + warning
Notice is ' Array to string conversion....'
Warning is 'Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation.....'
Why don't you use NOT IN clause like:
$sql = "select * from table where type not in ('address','multipleimage')";
Something like this, you may have to do some minor changes
<?php
$fieldtype = array('address','multipleimage');
$inQuery = implode(',', array_fill(0, count($fieldtype), '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'select * from table where type not in(' . $inQuery . ')'
);
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $fieldtype);
$stmt->execute();
?>
I have created my own ORM like class called DBConnection.php. It does all CRUD functionalities for any table in the specified database. It uses PDO as well. Feel free to play with it, customize and use in your code if you would like to....
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of DBConnection
*
* #author alemayehu
*/
require_once '../lib/PHPDebug.php';
class DBConnection {
private static $_instance = null;
private $_pdo;
private $_query;
private $_error = false;
private $_results;
private $_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 (Exception $ex) {
PHPDebug::printLogText("Connection Failed : ". $ex->getMessage() , "../lib/debug.txt");
die($ex->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DBConnection();
}
return self::$_instance;
}
public function fetchResultSet($sql, $params = array()){
//var_dump($params);passed
$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++;
}
}else{
echo 'something wrong with the array';
}
var_dump($this->_query);
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
}
return $this->_results;
}
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 error(){
return $this->_error;
}
private 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;//was 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 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 {$table} (`" . implode('`, `', $keys) . "`) VALUES( {$values} )";
//var_dump($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 user_id = {$id}";
if(! $this->query($sql, $fields)->error()){
return true;
}else{
return false;
}
}
public function fetchAllRecords($table, $where){
return $this->query("SELECT * FROM {$table} WHERE $where");
}
public function count(){
return $this->_count;
}
public function getResults(){
return $this->_results;
}
public function first(){
return $this->_results[0];
}
}//end class