unable to delete i row using PDO in php. Here is my code given below
this is inc.common.php
<?php
#session_start();
include_once '../common/inc.config.php';
include_once '../common/inc.globalConstants.php';
$db = new PDO("mysql:host=$mdbhost;dbname=$mdbname",$mdbuser,$mdbpass );
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
include_once '../classes/cls.common.php';
$Cobj=new common($db);
?>
this my cls.class.php
<?php
class common {
public function common($dbcon) {
$this->dbCon = $dbcon;
}
public function getCustomData($tableName,$fields, $conditions = "") {
$stmt = "";
$sql = "";
$sql = "SELECT $fields FROM $tableName $conditions ";
$stmt = $this->dbCon->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
public function delet($tableName, $class_id){
$inputArray['classId']=$class_id;
$count = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
$result = $stmt->execute($inputArray);
return $result;
}
?>
this is my addinfo.php
<?php
include '../common/inc.common.php';
$class_id=$_POST['refid'];
if(isset($_POST['mode']))
{
$tableName="class";
$class_id=$_POST['refid'];
$res=$Cobj->delet($tableName, $class_id);
}
?>
on passing variables using AJAX call i couldn't able to delete the row .Ajax call is success . only problem with PDO delete.
$.ajax({
url: "../masters/addinfo.php",
type: "POST",
data:"refid="+class_id+"&mode=delete",
});
my class table has 4 fields classId,name,date,stat.
The $stmt variable in function delet() is not defined.
public function delet($tableName, $class_id){
$inputArray['classId']=$class_id;
$stmt = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
$result = $stmt->execute($inputArray);
return $result;
}
Will fix this. Note what changed; $count changed to $stmt
Related
I created a function to grab data from my database. I want this function to be reusable just by placing correct arguments for different tables. Here's what I've done :
public function selectdata($table, $arguments='*', $where = null){
if($this->isconnect){
//check whether users put column names in the select clause
if(is_array($arguments)){
$new_args = implode(',', $arguments);
$sql = 'SELECT '.$new_args.' FROM '.$table;
} else {
$sql = 'SELECT '.$arguments.' FROM '.$table;
}
//check whether users use the where clause
if($where != null && is_array($where)){
$where = implode(' ', $where);
$sql .= ' WHERE '.$where ;
}
$query = $this->db->query($sql);
$query -> SetFetchMode(PDO::FETCH_NUM);
while($row = $query->fetch()){
print_r($row);
}
} else {
echo 'failed, moron';
}
}
And this is the way to run the function :
$columnname = array('bookname');
$where = array('bookid','=','2');
echo $database-> selectdata('buku', $columnname, $where);
The code worked quite decently so far, but I'm wondering how I want to use $where but without $columnname in the function. How do I pass the arguments in the function?
And could you point to me the better way to create a function to grab data using PDO?
Just use a PDO class which can look like this:
<?php
class DB_Connect{
var $dbh;
function __construct(){
$host = "xxx";
$db = "xxx";
$user = "xxx";
$password = "xxx";
$this -> dbh = $this -> db_connect($host, $db, $user, $password);
}
public function getDBConnection(){
return $this -> dbh;
}
protected function db_connect($host, $db, $user, $password){
//var_dump($host, $db, $user, $password);exit();
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->getDBConnection();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
}
?>
Now you can include that class and create an object with $dbh = new DB_Connect; and call every statement you want just with the reference on $dbh->query($statement)
This is my prefered way to do this.
EDIT: If you want to use a statement on another Database, just use the __construct($db) method to pass your database name on object creation
Using one of the tutorials I managed to create a working database retrieval using PHP, JSON and jQuery
Now my question is, if I have multiple query statements that I want to execute what is the best solution?
I have tried opening a second connection in different functions and sending the information as an array in array but that does not work.
database.php:
<?php
function getDbConnection() {
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
function home_ratings() {
$db = getDbConnection();
$stmt1 = $db->prepare("select * from table1");
$isOk1 = $stmt1->execute();
$results_home = array();
if ($isOk1)
{
$results_home = $stmt1->fetchAll();
}
else
{
trigger_error('Error executing statement.', E_USER_ERROR);
}
$db = null;
return $results_home;
}
?>
get.php:
<?php
require('constant.php');
require('database.php');
$home = home_ratings();
//$top_rest = top_ratings();
//$newr = new_ratings();
//echo json_encode($home);
echo json_encode(array('home' => $home));
?>
info.js:
$( document ).ready(function() {
$.get( "php/get.php")
.done(function(data) {
var results = jQuery.parseJSON(data);
$.each(results, function(i, value) {
//do what i need to do here
})
});
});
You only need one database connection object if you're connecting to the same database in the same method. Instead of having a function for getDbConnection() instead make the $db variable global and use it within functions (you may need to put a line global $db; in the function to ensure that it can access the global variable).
Example of how your database.php file could look:
<?php
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function home_ratings() {
global $db; // $db scope of global
$stmt1 = $db->prepare("select * from table1");
$isOk1 = $stmt1->execute();
$results_home = array();
if ($isOk1)
{
$results_home = $stmt1->fetchAll();
}
else
{
trigger_error('Error executing statement.', E_USER_ERROR);
}
return $results_home;
}
?>
I want to get a Firstname (Voornaam), and Lastname (Achternaam) from my database with a specific ID.
And I want to put it in my a function.
I made the following function in functions.php:
<?php
/* Naam opvragen */
include('gegevens.php');
function getName($getID)
{
$getname = 'SELECT * FROM KlantGegevens WHERE ID = ' . $getID;
$query = $conn->query($getname);
while($show = $query->fetch_assoc()) {
$voornaam = $show["Voornaam"];
return $voornaam;
}
}
/* Eind naam opvragen */
?>
And i call the function with ($getID (=1)):
<?php getName($getID); ?>
My error is:
Fatal error: Call to a member function query() on a non-object in /home/thijsgp51/domains/thijskempers.nl/public_html/beheer/functions/functions.php on line 8
What am i doing wrong here?
<?php
/* Naam opvragen */
function getName($getID)
{
$db = new PDO('mysql:host=localhost;port=3307;dbname=test', 'root', 'usbw');
$stmt = $db->prepare("SELECT * FROM klantgegevens WHERE ID ='$getID' ");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$voornaam = $row["voornaam"];
return $voornaam;
}
}
$id = 1;
echo getName($id);
?>
I used PDO for the connection try it. Also read this post on sqlinjection very helpful.
In the code i changed your query a bit and put the connection in the function like Till Helge said.
Happy coding!
Try It.
<?php
/* Naam opvragen */
function getName($getID)
{
$db = new PDO('mysql:host=localhost;port=3307;dbname=test', 'root', 'usbw');
$stmt = $db->prepare("SELECT * FROM klantgegevens WHERE ID ='%s",$getID);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$voornaam = $row["voornaam"];
return $voornaam;
}
}
$id = 1;
echo getName($id);
?>
Your funcion get 2 arguments
function getName($voornaam, $achternaam)
you should remove the areguments as you are not using it.
function getName() {
....
}
Change your function definition, remove those 2 arguments, and change concatenation from + to .:
function getName()//or with optional arguments: function getName($voornaam='', $achternaam='')
{
$conn = new mysqli('localhost', 'user', 'pass', 'database');
$getID = 1;
$getname = 'SELECT Voornaam, Achternaam FROM KlantGegevens WHERE ID = ' . $getID;
$query = $conn->query($getname);
while($row = $query->fetch_assoc()) {
$voornaam = $row["Voornaam"];
$achternaam = $row["Achternaam"];
return $voornaam.' '.$achternaam;
}
}
You don't need name and forename in function definition parameters because you get it from database.
As Till Helge pointed out, you still need to open connection to database - either put it as an argument, or call as the first thing inside your function (I have already put that there after edition):
$conn = new mysqli('localhost', 'user', 'pass', 'database');
you didn't pass parameters in your function,
<?php getName(); ?>
I am new to OOP, and I am switching all of my websites code to it! I am currently writing a class that grabs a user's information, and will eventually update it.
The code I am using is below:
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function __construct($userid, $connection, $information) {
$this->userid = $userid;
$this->connection = $connection;
$this->information = $information;
}
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user($_SESSION["logged_in"], $connection, "username");
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Now as you can see on the last two lines of code (one from the end) I have to use the parameters twice. Basically the first parameter says what the ID is, second says what the $connection is, and the third is what I want to grab from the database. So what am I doing wrong? Did I define something I did not need to?
EDIT
Would the following be valid as well?
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user();
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Like is this in-properer, or wrong...?
If the user class has all the information it needs as data members, then user_information doesn't need to take any arguments:
public function user_information() {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $this->userid);
try{
$stmt = $this->connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns[$this->information];
}
Since you have a lot of questions about the way a class works and about OOP I will try to give you a little direction.
There is no standard way of building your class. You are the one that decides what goes where in terms of what belongs to the class and what needs to be injected. This is just to tell you that you cannot pin yourself down. You need to get a feel for it and build a logic.
I took your class and rebuild it some with added comments. Hope that will help you some. Good luck!
<?php
require ("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public $dbconnection;
public function __construct($connection) {
/**
* Your user class interacts with the database.
* Inject the connection here and set your
* global class variable.
*/
$this -> dbconnection = $connection;
}
public function user_information($userid, $column) {
/**
* The userid and column are specific for this
* method action. No need to set these variables
* in the global scope of the class.
*/
$query = "SELECT" . $column . " FROM users WHERE id = :id";
$params = array(':id' => $userid);
try {
$stmt = $this -> dbconnection -> prepare($query);
$stmt -> execute($params);
} catch(PDOException $ex) {
echo("Failed to run query: " . $ex -> getMessage());
}
$result = $stmt -> fetch();
return $result;
}
}
$username = new user($connection);
echo $username -> user_information($_SESSION["logged_in"], $information);
?>
I'm trying to place these in a seperate file that'll be included on every page
$sql = 'select id, name, age, address, pincode from json where name = :name';
$arr = array(":name" => $name);
// There are some 30 diff sql's and arrays
Another page
$name = 'peter';
$conn = connect();
function myType(){
global $conn;
global $sql;
global $arr;
$stmt = $conn->prepare($sql);
$stmt->execute($arr);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
foreach ($row as $value) {
echo $value.' <br>';
}
}
}
myType();
I'm trying to keep the sqls and arrays in a separate file and use them when needed. Keeps things clean and easy to maintain. But the variables are declared later, which gives me: Notice: Undefined variable: name in C:\web\apache\htdocs\dev\json.php on line 24
Can you see a way to do this without uglying things?
Well you should use two files
sql.php
fetch.php
Then in fetch.php you will use require_once 'sql.php'
here's the code for fetch.php:
$name = 'peter';
$conn = connect();
require_once 'sql.php';
function myType(){
global $conn;
global $sql;
global $arr;
$stmt = $conn->prepare($sql);
$stmt->execute($arr);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
foreach ($row as $value) {
echo $value.' <br>';
}
}
}
myType();
And this is sql.php
$sql = 'select id, name, age, address, pincode from json where name = :name';
$arr = array(":name" => $name);
This should be helpful and you can use sql.php whenever you like.
Storing the queries and there bound parameters in a separate include is a bit strange. How will you change the bound parameter after the include?
My suggestion is to create a model that will handle the database operations. The benefit of this is you can encapsulate the database work and keep it separate from your app logic and also easily reuse it throughout.
Basic example:
class CustomersModel
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function getByName($name)
{
$result = array();
$sql = 'select id, name, age, address, pincode from json where name = :name';
if($stmt = $conn->prepare($sql))
{
$stmt->execute(array(":name" => $name));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
return $result;
}
}
Usage:
require_once('/path/to/CustomerModel.php');
$conn = connect();
$model = new CustomerModel($conn);
$customers = $model->getByName('peter');
foreach($customers as $c)
{
echo htmlspecialchars($c['name']) . '<br />;
}